SemaDecl.cpp 690 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/NonTrivialTypeVisitor.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  62. bool AllowTemplates = false,
  63. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  96. return std::make_unique<TypeNameValidatorCCC>(*this);
  97. }
  98. private:
  99. bool AllowInvalidDecl;
  100. bool WantClassName;
  101. bool AllowTemplates;
  102. bool AllowNonTemplates;
  103. };
  104. } // end anonymous namespace
  105. /// Determine whether the token kind starts a simple-type-specifier.
  106. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  107. switch (Kind) {
  108. // FIXME: Take into account the current language when deciding whether a
  109. // token kind is a valid type specifier
  110. case tok::kw_short:
  111. case tok::kw_long:
  112. case tok::kw___int64:
  113. case tok::kw___int128:
  114. case tok::kw_signed:
  115. case tok::kw_unsigned:
  116. case tok::kw_void:
  117. case tok::kw_char:
  118. case tok::kw_int:
  119. case tok::kw_half:
  120. case tok::kw_float:
  121. case tok::kw_double:
  122. case tok::kw__Float16:
  123. case tok::kw___float128:
  124. case tok::kw_wchar_t:
  125. case tok::kw_bool:
  126. case tok::kw___underlying_type:
  127. case tok::kw___auto_type:
  128. return true;
  129. case tok::annot_typename:
  130. case tok::kw_char16_t:
  131. case tok::kw_char32_t:
  132. case tok::kw_typeof:
  133. case tok::annot_decltype:
  134. case tok::kw_decltype:
  135. return getLangOpts().CPlusPlus;
  136. case tok::kw_char8_t:
  137. return getLangOpts().Char8;
  138. default:
  139. break;
  140. }
  141. return false;
  142. }
  143. namespace {
  144. enum class UnqualifiedTypeNameLookupResult {
  145. NotFound,
  146. FoundNonType,
  147. FoundType
  148. };
  149. } // end anonymous namespace
  150. /// Tries to perform unqualified lookup of the type decls in bases for
  151. /// dependent class.
  152. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  153. /// type decl, \a FoundType if only type decls are found.
  154. static UnqualifiedTypeNameLookupResult
  155. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  156. SourceLocation NameLoc,
  157. const CXXRecordDecl *RD) {
  158. if (!RD->hasDefinition())
  159. return UnqualifiedTypeNameLookupResult::NotFound;
  160. // Look for type decls in base classes.
  161. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  162. UnqualifiedTypeNameLookupResult::NotFound;
  163. for (const auto &Base : RD->bases()) {
  164. const CXXRecordDecl *BaseRD = nullptr;
  165. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  166. BaseRD = BaseTT->getAsCXXRecordDecl();
  167. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  168. // Look for type decls in dependent base classes that have known primary
  169. // templates.
  170. if (!TST || !TST->isDependentType())
  171. continue;
  172. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  173. if (!TD)
  174. continue;
  175. if (auto *BasePrimaryTemplate =
  176. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  177. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  178. BaseRD = BasePrimaryTemplate;
  179. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  180. if (const ClassTemplatePartialSpecializationDecl *PS =
  181. CTD->findPartialSpecialization(Base.getType()))
  182. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  183. BaseRD = PS;
  184. }
  185. }
  186. }
  187. if (BaseRD) {
  188. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  189. if (!isa<TypeDecl>(ND))
  190. return UnqualifiedTypeNameLookupResult::FoundNonType;
  191. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  192. }
  193. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  194. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  195. case UnqualifiedTypeNameLookupResult::FoundNonType:
  196. return UnqualifiedTypeNameLookupResult::FoundNonType;
  197. case UnqualifiedTypeNameLookupResult::FoundType:
  198. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  199. break;
  200. case UnqualifiedTypeNameLookupResult::NotFound:
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. return FoundTypeDecl;
  207. }
  208. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  209. const IdentifierInfo &II,
  210. SourceLocation NameLoc) {
  211. // Lookup in the parent class template context, if any.
  212. const CXXRecordDecl *RD = nullptr;
  213. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  214. UnqualifiedTypeNameLookupResult::NotFound;
  215. for (DeclContext *DC = S.CurContext;
  216. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  217. DC = DC->getParent()) {
  218. // Look for type decls in dependent base classes that have known primary
  219. // templates.
  220. RD = dyn_cast<CXXRecordDecl>(DC);
  221. if (RD && RD->getDescribedClassTemplate())
  222. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  223. }
  224. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  225. return nullptr;
  226. // We found some types in dependent base classes. Recover as if the user
  227. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  228. // lookup during template instantiation.
  229. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  230. ASTContext &Context = S.Context;
  231. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  232. cast<Type>(Context.getRecordType(RD)));
  233. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  234. CXXScopeSpec SS;
  235. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  236. TypeLocBuilder Builder;
  237. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  238. DepTL.setNameLoc(NameLoc);
  239. DepTL.setElaboratedKeywordLoc(SourceLocation());
  240. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  241. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  242. }
  243. /// If the identifier refers to a type name within this scope,
  244. /// return the declaration of that type.
  245. ///
  246. /// This routine performs ordinary name lookup of the identifier II
  247. /// within the given scope, with optional C++ scope specifier SS, to
  248. /// determine whether the name refers to a type. If so, returns an
  249. /// opaque pointer (actually a QualType) corresponding to that
  250. /// type. Otherwise, returns NULL.
  251. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  252. Scope *S, CXXScopeSpec *SS,
  253. bool isClassName, bool HasTrailingDot,
  254. ParsedType ObjectTypePtr,
  255. bool IsCtorOrDtorName,
  256. bool WantNontrivialTypeSourceInfo,
  257. bool IsClassTemplateDeductionContext,
  258. IdentifierInfo **CorrectedII) {
  259. // FIXME: Consider allowing this outside C++1z mode as an extension.
  260. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  261. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  262. !isClassName && !HasTrailingDot;
  263. // Determine where we will perform name lookup.
  264. DeclContext *LookupCtx = nullptr;
  265. if (ObjectTypePtr) {
  266. QualType ObjectType = ObjectTypePtr.get();
  267. if (ObjectType->isRecordType())
  268. LookupCtx = computeDeclContext(ObjectType);
  269. } else if (SS && SS->isNotEmpty()) {
  270. LookupCtx = computeDeclContext(*SS, false);
  271. if (!LookupCtx) {
  272. if (isDependentScopeSpecifier(*SS)) {
  273. // C++ [temp.res]p3:
  274. // A qualified-id that refers to a type and in which the
  275. // nested-name-specifier depends on a template-parameter (14.6.2)
  276. // shall be prefixed by the keyword typename to indicate that the
  277. // qualified-id denotes a type, forming an
  278. // elaborated-type-specifier (7.1.5.3).
  279. //
  280. // We therefore do not perform any name lookup if the result would
  281. // refer to a member of an unknown specialization.
  282. if (!isClassName && !IsCtorOrDtorName)
  283. return nullptr;
  284. // We know from the grammar that this name refers to a type,
  285. // so build a dependent node to describe the type.
  286. if (WantNontrivialTypeSourceInfo)
  287. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  288. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  289. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  290. II, NameLoc);
  291. return ParsedType::make(T);
  292. }
  293. return nullptr;
  294. }
  295. if (!LookupCtx->isDependentContext() &&
  296. RequireCompleteDeclContext(*SS, LookupCtx))
  297. return nullptr;
  298. }
  299. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  300. // lookup for class-names.
  301. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  302. LookupOrdinaryName;
  303. LookupResult Result(*this, &II, NameLoc, Kind);
  304. if (LookupCtx) {
  305. // Perform "qualified" name lookup into the declaration context we
  306. // computed, which is either the type of the base of a member access
  307. // expression or the declaration context associated with a prior
  308. // nested-name-specifier.
  309. LookupQualifiedName(Result, LookupCtx);
  310. if (ObjectTypePtr && Result.empty()) {
  311. // C++ [basic.lookup.classref]p3:
  312. // If the unqualified-id is ~type-name, the type-name is looked up
  313. // in the context of the entire postfix-expression. If the type T of
  314. // the object expression is of a class type C, the type-name is also
  315. // looked up in the scope of class C. At least one of the lookups shall
  316. // find a name that refers to (possibly cv-qualified) T.
  317. LookupName(Result, S);
  318. }
  319. } else {
  320. // Perform unqualified name lookup.
  321. LookupName(Result, S);
  322. // For unqualified lookup in a class template in MSVC mode, look into
  323. // dependent base classes where the primary class template is known.
  324. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  325. if (ParsedType TypeInBase =
  326. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  327. return TypeInBase;
  328. }
  329. }
  330. NamedDecl *IIDecl = nullptr;
  331. switch (Result.getResultKind()) {
  332. case LookupResult::NotFound:
  333. case LookupResult::NotFoundInCurrentInstantiation:
  334. if (CorrectedII) {
  335. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  336. AllowDeducedTemplate);
  337. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  338. S, SS, CCC, CTK_ErrorRecovery);
  339. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  340. TemplateTy Template;
  341. bool MemberOfUnknownSpecialization;
  342. UnqualifiedId TemplateName;
  343. TemplateName.setIdentifier(NewII, NameLoc);
  344. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  345. CXXScopeSpec NewSS, *NewSSPtr = SS;
  346. if (SS && NNS) {
  347. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  348. NewSSPtr = &NewSS;
  349. }
  350. if (Correction && (NNS || NewII != &II) &&
  351. // Ignore a correction to a template type as the to-be-corrected
  352. // identifier is not a template (typo correction for template names
  353. // is handled elsewhere).
  354. !(getLangOpts().CPlusPlus && NewSSPtr &&
  355. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  356. Template, MemberOfUnknownSpecialization))) {
  357. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  358. isClassName, HasTrailingDot, ObjectTypePtr,
  359. IsCtorOrDtorName,
  360. WantNontrivialTypeSourceInfo,
  361. IsClassTemplateDeductionContext);
  362. if (Ty) {
  363. diagnoseTypo(Correction,
  364. PDiag(diag::err_unknown_type_or_class_name_suggest)
  365. << Result.getLookupName() << isClassName);
  366. if (SS && NNS)
  367. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  368. *CorrectedII = NewII;
  369. return Ty;
  370. }
  371. }
  372. }
  373. // If typo correction failed or was not performed, fall through
  374. LLVM_FALLTHROUGH;
  375. case LookupResult::FoundOverloaded:
  376. case LookupResult::FoundUnresolvedValue:
  377. Result.suppressDiagnostics();
  378. return nullptr;
  379. case LookupResult::Ambiguous:
  380. // Recover from type-hiding ambiguities by hiding the type. We'll
  381. // do the lookup again when looking for an object, and we can
  382. // diagnose the error then. If we don't do this, then the error
  383. // about hiding the type will be immediately followed by an error
  384. // that only makes sense if the identifier was treated like a type.
  385. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  386. Result.suppressDiagnostics();
  387. return nullptr;
  388. }
  389. // Look to see if we have a type anywhere in the list of results.
  390. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  391. Res != ResEnd; ++Res) {
  392. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  393. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  394. if (!IIDecl ||
  395. (*Res)->getLocation().getRawEncoding() <
  396. IIDecl->getLocation().getRawEncoding())
  397. IIDecl = *Res;
  398. }
  399. }
  400. if (!IIDecl) {
  401. // None of the entities we found is a type, so there is no way
  402. // to even assume that the result is a type. In this case, don't
  403. // complain about the ambiguity. The parser will either try to
  404. // perform this lookup again (e.g., as an object name), which
  405. // will produce the ambiguity, or will complain that it expected
  406. // a type name.
  407. Result.suppressDiagnostics();
  408. return nullptr;
  409. }
  410. // We found a type within the ambiguous lookup; diagnose the
  411. // ambiguity and then return that type. This might be the right
  412. // answer, or it might not be, but it suppresses any attempt to
  413. // perform the name lookup again.
  414. break;
  415. case LookupResult::Found:
  416. IIDecl = Result.getFoundDecl();
  417. break;
  418. }
  419. assert(IIDecl && "Didn't find decl");
  420. QualType T;
  421. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  422. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  423. // instead names the constructors of the class, except when naming a class.
  424. // This is ill-formed when we're not actually forming a ctor or dtor name.
  425. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  426. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  427. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  428. FoundRD->isInjectedClassName() &&
  429. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  430. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  431. << &II << /*Type*/1;
  432. DiagnoseUseOfDecl(IIDecl, NameLoc);
  433. T = Context.getTypeDeclType(TD);
  434. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  435. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  436. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  437. if (!HasTrailingDot)
  438. T = Context.getObjCInterfaceType(IDecl);
  439. } else if (AllowDeducedTemplate) {
  440. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  441. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  442. QualType(), false);
  443. }
  444. if (T.isNull()) {
  445. // If it's not plausibly a type, suppress diagnostics.
  446. Result.suppressDiagnostics();
  447. return nullptr;
  448. }
  449. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  450. // constructor or destructor name (in such a case, the scope specifier
  451. // will be attached to the enclosing Expr or Decl node).
  452. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  453. !isa<ObjCInterfaceDecl>(IIDecl)) {
  454. if (WantNontrivialTypeSourceInfo) {
  455. // Construct a type with type-source information.
  456. TypeLocBuilder Builder;
  457. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  458. T = getElaboratedType(ETK_None, *SS, T);
  459. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  460. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  461. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  462. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  463. } else {
  464. T = getElaboratedType(ETK_None, *SS, T);
  465. }
  466. }
  467. return ParsedType::make(T);
  468. }
  469. // Builds a fake NNS for the given decl context.
  470. static NestedNameSpecifier *
  471. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  472. for (;; DC = DC->getLookupParent()) {
  473. DC = DC->getPrimaryContext();
  474. auto *ND = dyn_cast<NamespaceDecl>(DC);
  475. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  476. return NestedNameSpecifier::Create(Context, nullptr, ND);
  477. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  478. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  479. RD->getTypeForDecl());
  480. else if (isa<TranslationUnitDecl>(DC))
  481. return NestedNameSpecifier::GlobalSpecifier(Context);
  482. }
  483. llvm_unreachable("something isn't in TU scope?");
  484. }
  485. /// Find the parent class with dependent bases of the innermost enclosing method
  486. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  487. /// up allowing unqualified dependent type names at class-level, which MSVC
  488. /// correctly rejects.
  489. static const CXXRecordDecl *
  490. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  491. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  492. DC = DC->getPrimaryContext();
  493. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  494. if (MD->getParent()->hasAnyDependentBases())
  495. return MD->getParent();
  496. }
  497. return nullptr;
  498. }
  499. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  500. SourceLocation NameLoc,
  501. bool IsTemplateTypeArg) {
  502. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  503. NestedNameSpecifier *NNS = nullptr;
  504. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  505. // If we weren't able to parse a default template argument, delay lookup
  506. // until instantiation time by making a non-dependent DependentTypeName. We
  507. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  508. // lookup is retried.
  509. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  510. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  511. // name specifiers.
  512. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  513. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  514. } else if (const CXXRecordDecl *RD =
  515. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  516. // Build a DependentNameType that will perform lookup into RD at
  517. // instantiation time.
  518. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  519. RD->getTypeForDecl());
  520. // Diagnose that this identifier was undeclared, and retry the lookup during
  521. // template instantiation.
  522. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  523. << RD;
  524. } else {
  525. // This is not a situation that we should recover from.
  526. return ParsedType();
  527. }
  528. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  529. // Build type location information. We synthesized the qualifier, so we have
  530. // to build a fake NestedNameSpecifierLoc.
  531. NestedNameSpecifierLocBuilder NNSLocBuilder;
  532. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  533. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  534. TypeLocBuilder Builder;
  535. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  536. DepTL.setNameLoc(NameLoc);
  537. DepTL.setElaboratedKeywordLoc(SourceLocation());
  538. DepTL.setQualifierLoc(QualifierLoc);
  539. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  540. }
  541. /// isTagName() - This method is called *for error recovery purposes only*
  542. /// to determine if the specified name is a valid tag name ("struct foo"). If
  543. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  544. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  545. /// cases in C where the user forgot to specify the tag.
  546. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  547. // Do a tag name lookup in this scope.
  548. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  549. LookupName(R, S, false);
  550. R.suppressDiagnostics();
  551. if (R.getResultKind() == LookupResult::Found)
  552. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  553. switch (TD->getTagKind()) {
  554. case TTK_Struct: return DeclSpec::TST_struct;
  555. case TTK_Interface: return DeclSpec::TST_interface;
  556. case TTK_Union: return DeclSpec::TST_union;
  557. case TTK_Class: return DeclSpec::TST_class;
  558. case TTK_Enum: return DeclSpec::TST_enum;
  559. }
  560. }
  561. return DeclSpec::TST_unspecified;
  562. }
  563. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  564. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  565. /// then downgrade the missing typename error to a warning.
  566. /// This is needed for MSVC compatibility; Example:
  567. /// @code
  568. /// template<class T> class A {
  569. /// public:
  570. /// typedef int TYPE;
  571. /// };
  572. /// template<class T> class B : public A<T> {
  573. /// public:
  574. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  575. /// };
  576. /// @endcode
  577. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  578. if (CurContext->isRecord()) {
  579. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  580. return true;
  581. const Type *Ty = SS->getScopeRep()->getAsType();
  582. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  583. for (const auto &Base : RD->bases())
  584. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  585. return true;
  586. return S->isFunctionPrototypeScope();
  587. }
  588. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  589. }
  590. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  591. SourceLocation IILoc,
  592. Scope *S,
  593. CXXScopeSpec *SS,
  594. ParsedType &SuggestedType,
  595. bool IsTemplateName) {
  596. // Don't report typename errors for editor placeholders.
  597. if (II->isEditorPlaceholder())
  598. return;
  599. // We don't have anything to suggest (yet).
  600. SuggestedType = nullptr;
  601. // There may have been a typo in the name of the type. Look up typo
  602. // results, in case we have something that we can suggest.
  603. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  604. /*AllowTemplates=*/IsTemplateName,
  605. /*AllowNonTemplates=*/!IsTemplateName);
  606. if (TypoCorrection Corrected =
  607. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  608. CCC, CTK_ErrorRecovery)) {
  609. // FIXME: Support error recovery for the template-name case.
  610. bool CanRecover = !IsTemplateName;
  611. if (Corrected.isKeyword()) {
  612. // We corrected to a keyword.
  613. diagnoseTypo(Corrected,
  614. PDiag(IsTemplateName ? diag::err_no_template_suggest
  615. : diag::err_unknown_typename_suggest)
  616. << II);
  617. II = Corrected.getCorrectionAsIdentifierInfo();
  618. } else {
  619. // We found a similarly-named type or interface; suggest that.
  620. if (!SS || !SS->isSet()) {
  621. diagnoseTypo(Corrected,
  622. PDiag(IsTemplateName ? diag::err_no_template_suggest
  623. : diag::err_unknown_typename_suggest)
  624. << II, CanRecover);
  625. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  626. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  627. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  628. II->getName().equals(CorrectedStr);
  629. diagnoseTypo(Corrected,
  630. PDiag(IsTemplateName
  631. ? diag::err_no_member_template_suggest
  632. : diag::err_unknown_nested_typename_suggest)
  633. << II << DC << DroppedSpecifier << SS->getRange(),
  634. CanRecover);
  635. } else {
  636. llvm_unreachable("could not have corrected a typo here");
  637. }
  638. if (!CanRecover)
  639. return;
  640. CXXScopeSpec tmpSS;
  641. if (Corrected.getCorrectionSpecifier())
  642. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  643. SourceRange(IILoc));
  644. // FIXME: Support class template argument deduction here.
  645. SuggestedType =
  646. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  647. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  648. /*IsCtorOrDtorName=*/false,
  649. /*WantNontrivialTypeSourceInfo=*/true);
  650. }
  651. return;
  652. }
  653. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  654. // See if II is a class template that the user forgot to pass arguments to.
  655. UnqualifiedId Name;
  656. Name.setIdentifier(II, IILoc);
  657. CXXScopeSpec EmptySS;
  658. TemplateTy TemplateResult;
  659. bool MemberOfUnknownSpecialization;
  660. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  661. Name, nullptr, true, TemplateResult,
  662. MemberOfUnknownSpecialization) == TNK_Type_template) {
  663. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  664. return;
  665. }
  666. }
  667. // FIXME: Should we move the logic that tries to recover from a missing tag
  668. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  669. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  670. Diag(IILoc, IsTemplateName ? diag::err_no_template
  671. : diag::err_unknown_typename)
  672. << II;
  673. else if (DeclContext *DC = computeDeclContext(*SS, false))
  674. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  675. : diag::err_typename_nested_not_found)
  676. << II << DC << SS->getRange();
  677. else if (isDependentScopeSpecifier(*SS)) {
  678. unsigned DiagID = diag::err_typename_missing;
  679. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  680. DiagID = diag::ext_typename_missing;
  681. Diag(SS->getRange().getBegin(), DiagID)
  682. << SS->getScopeRep() << II->getName()
  683. << SourceRange(SS->getRange().getBegin(), IILoc)
  684. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  685. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  686. *SS, *II, IILoc).get();
  687. } else {
  688. assert(SS && SS->isInvalid() &&
  689. "Invalid scope specifier has already been diagnosed");
  690. }
  691. }
  692. /// Determine whether the given result set contains either a type name
  693. /// or
  694. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  695. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  696. NextToken.is(tok::less);
  697. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  698. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  699. return true;
  700. if (CheckTemplate && isa<TemplateDecl>(*I))
  701. return true;
  702. }
  703. return false;
  704. }
  705. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  706. Scope *S, CXXScopeSpec &SS,
  707. IdentifierInfo *&Name,
  708. SourceLocation NameLoc) {
  709. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  710. SemaRef.LookupParsedName(R, S, &SS);
  711. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  712. StringRef FixItTagName;
  713. switch (Tag->getTagKind()) {
  714. case TTK_Class:
  715. FixItTagName = "class ";
  716. break;
  717. case TTK_Enum:
  718. FixItTagName = "enum ";
  719. break;
  720. case TTK_Struct:
  721. FixItTagName = "struct ";
  722. break;
  723. case TTK_Interface:
  724. FixItTagName = "__interface ";
  725. break;
  726. case TTK_Union:
  727. FixItTagName = "union ";
  728. break;
  729. }
  730. StringRef TagName = FixItTagName.drop_back();
  731. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  732. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  733. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  734. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  735. I != IEnd; ++I)
  736. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  737. << Name << TagName;
  738. // Replace lookup results with just the tag decl.
  739. Result.clear(Sema::LookupTagName);
  740. SemaRef.LookupParsedName(Result, S, &SS);
  741. return true;
  742. }
  743. return false;
  744. }
  745. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  746. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  747. QualType T, SourceLocation NameLoc) {
  748. ASTContext &Context = S.Context;
  749. TypeLocBuilder Builder;
  750. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  751. T = S.getElaboratedType(ETK_None, SS, T);
  752. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  753. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  754. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  755. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  756. }
  757. Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
  758. IdentifierInfo *&Name,
  759. SourceLocation NameLoc,
  760. const Token &NextToken,
  761. CorrectionCandidateCallback *CCC) {
  762. DeclarationNameInfo NameInfo(Name, NameLoc);
  763. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  764. assert(NextToken.isNot(tok::coloncolon) &&
  765. "parse nested name specifiers before calling ClassifyName");
  766. 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. DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
  789. if (Ivar.isInvalid())
  790. return NameClassification::Error();
  791. if (Ivar.isUsable())
  792. return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
  793. // We defer builtin creation until after ivar lookup inside ObjC methods.
  794. if (Result.empty())
  795. LookupBuiltin(Result);
  796. }
  797. bool SecondTry = false;
  798. bool IsFilteredTemplateName = false;
  799. Corrected:
  800. switch (Result.getResultKind()) {
  801. case LookupResult::NotFound:
  802. // If an unqualified-id is followed by a '(', then we have a function
  803. // call.
  804. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  805. // In C++, this is an ADL-only call.
  806. // FIXME: Reference?
  807. if (getLangOpts().CPlusPlus)
  808. return NameClassification::UndeclaredNonType();
  809. // C90 6.3.2.2:
  810. // If the expression that precedes the parenthesized argument list in a
  811. // function call consists solely of an identifier, and if no
  812. // declaration is visible for this identifier, the identifier is
  813. // implicitly declared exactly as if, in the innermost block containing
  814. // the function call, the declaration
  815. //
  816. // extern int identifier ();
  817. //
  818. // appeared.
  819. //
  820. // We also allow this in C99 as an extension.
  821. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
  822. return NameClassification::NonType(D);
  823. }
  824. if (getLangOpts().CPlusPlus2a && !SS.isSet() && NextToken.is(tok::less)) {
  825. // In C++20 onwards, this could be an ADL-only call to a function
  826. // template, and we're required to assume that this is a template name.
  827. //
  828. // FIXME: Find a way to still do typo correction in this case.
  829. TemplateName Template =
  830. Context.getAssumedTemplateName(NameInfo.getName());
  831. return NameClassification::UndeclaredTemplate(Template);
  832. }
  833. // In C, we first see whether there is a tag type by the same name, in
  834. // which case it's likely that the user just forgot to write "enum",
  835. // "struct", or "union".
  836. if (!getLangOpts().CPlusPlus && !SecondTry &&
  837. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  838. break;
  839. }
  840. // Perform typo correction to determine if there is another name that is
  841. // close to this name.
  842. if (!SecondTry && CCC) {
  843. SecondTry = true;
  844. if (TypoCorrection Corrected =
  845. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  846. &SS, *CCC, CTK_ErrorRecovery)) {
  847. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  848. unsigned QualifiedDiag = diag::err_no_member_suggest;
  849. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  850. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  851. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  852. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  853. UnqualifiedDiag = diag::err_no_template_suggest;
  854. QualifiedDiag = diag::err_no_member_template_suggest;
  855. } else if (UnderlyingFirstDecl &&
  856. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  857. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  858. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  859. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  860. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  861. }
  862. if (SS.isEmpty()) {
  863. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  864. } else {// FIXME: is this even reachable? Test it.
  865. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  866. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  867. Name->getName().equals(CorrectedStr);
  868. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  869. << Name << computeDeclContext(SS, false)
  870. << DroppedSpecifier << SS.getRange());
  871. }
  872. // Update the name, so that the caller has the new name.
  873. Name = Corrected.getCorrectionAsIdentifierInfo();
  874. // Typo correction corrected to a keyword.
  875. if (Corrected.isKeyword())
  876. return Name;
  877. // Also update the LookupResult...
  878. // FIXME: This should probably go away at some point
  879. Result.clear();
  880. Result.setLookupName(Corrected.getCorrection());
  881. if (FirstDecl)
  882. Result.addDecl(FirstDecl);
  883. // If we found an Objective-C instance variable, let
  884. // LookupInObjCMethod build the appropriate expression to
  885. // reference the ivar.
  886. // FIXME: This is a gross hack.
  887. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  888. DeclResult R =
  889. LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
  890. if (R.isInvalid())
  891. return NameClassification::Error();
  892. if (R.isUsable())
  893. return NameClassification::NonType(Ivar);
  894. }
  895. goto Corrected;
  896. }
  897. }
  898. // We failed to correct; just fall through and let the parser deal with it.
  899. Result.suppressDiagnostics();
  900. return NameClassification::Unknown();
  901. case LookupResult::NotFoundInCurrentInstantiation: {
  902. // We performed name lookup into the current instantiation, and there were
  903. // dependent bases, so we treat this result the same way as any other
  904. // dependent nested-name-specifier.
  905. // C++ [temp.res]p2:
  906. // A name used in a template declaration or definition and that is
  907. // dependent on a template-parameter is assumed not to name a type
  908. // unless the applicable name lookup finds a type name or the name is
  909. // qualified by the keyword typename.
  910. //
  911. // FIXME: If the next token is '<', we might want to ask the parser to
  912. // perform some heroics to see if we actually have a
  913. // template-argument-list, which would indicate a missing 'template'
  914. // keyword here.
  915. return NameClassification::DependentNonType();
  916. }
  917. case LookupResult::Found:
  918. case LookupResult::FoundOverloaded:
  919. case LookupResult::FoundUnresolvedValue:
  920. break;
  921. case LookupResult::Ambiguous:
  922. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  923. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  924. /*AllowDependent=*/false)) {
  925. // C++ [temp.local]p3:
  926. // A lookup that finds an injected-class-name (10.2) can result in an
  927. // ambiguity in certain cases (for example, if it is found in more than
  928. // one base class). If all of the injected-class-names that are found
  929. // refer to specializations of the same class template, and if the name
  930. // is followed by a template-argument-list, the reference refers to the
  931. // class template itself and not a specialization thereof, and is not
  932. // ambiguous.
  933. //
  934. // This filtering can make an ambiguous result into an unambiguous one,
  935. // so try again after filtering out template names.
  936. FilterAcceptableTemplateNames(Result);
  937. if (!Result.isAmbiguous()) {
  938. IsFilteredTemplateName = true;
  939. break;
  940. }
  941. }
  942. // Diagnose the ambiguity and return an error.
  943. return NameClassification::Error();
  944. }
  945. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  946. (IsFilteredTemplateName ||
  947. hasAnyAcceptableTemplateNames(
  948. Result, /*AllowFunctionTemplates=*/true,
  949. /*AllowDependent=*/false,
  950. /*AllowNonTemplateFunctions*/ !SS.isSet() &&
  951. getLangOpts().CPlusPlus2a))) {
  952. // C++ [temp.names]p3:
  953. // After name lookup (3.4) finds that a name is a template-name or that
  954. // an operator-function-id or a literal- operator-id refers to a set of
  955. // overloaded functions any member of which is a function template if
  956. // this is followed by a <, the < is always taken as the delimiter of a
  957. // template-argument-list and never as the less-than operator.
  958. // C++2a [temp.names]p2:
  959. // A name is also considered to refer to a template if it is an
  960. // unqualified-id followed by a < and name lookup finds either one
  961. // or more functions or finds nothing.
  962. if (!IsFilteredTemplateName)
  963. FilterAcceptableTemplateNames(Result);
  964. bool IsFunctionTemplate;
  965. bool IsVarTemplate;
  966. TemplateName Template;
  967. if (Result.end() - Result.begin() > 1) {
  968. IsFunctionTemplate = true;
  969. Template = Context.getOverloadedTemplateName(Result.begin(),
  970. Result.end());
  971. } else if (!Result.empty()) {
  972. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  973. *Result.begin(), /*AllowFunctionTemplates=*/true,
  974. /*AllowDependent=*/false));
  975. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  976. IsVarTemplate = isa<VarTemplateDecl>(TD);
  977. if (SS.isSet() && !SS.isInvalid())
  978. Template =
  979. Context.getQualifiedTemplateName(SS.getScopeRep(),
  980. /*TemplateKeyword=*/false, TD);
  981. else
  982. Template = TemplateName(TD);
  983. } else {
  984. // All results were non-template functions. This is a function template
  985. // name.
  986. IsFunctionTemplate = true;
  987. Template = Context.getAssumedTemplateName(NameInfo.getName());
  988. }
  989. if (IsFunctionTemplate) {
  990. // Function templates always go through overload resolution, at which
  991. // point we'll perform the various checks (e.g., accessibility) we need
  992. // to based on which function we selected.
  993. Result.suppressDiagnostics();
  994. return NameClassification::FunctionTemplate(Template);
  995. }
  996. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  997. : NameClassification::TypeTemplate(Template);
  998. }
  999. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  1000. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  1001. DiagnoseUseOfDecl(Type, NameLoc);
  1002. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1003. QualType T = Context.getTypeDeclType(Type);
  1004. if (SS.isNotEmpty())
  1005. return buildNestedType(*this, SS, T, NameLoc);
  1006. return ParsedType::make(T);
  1007. }
  1008. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1009. if (!Class) {
  1010. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1011. if (ObjCCompatibleAliasDecl *Alias =
  1012. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1013. Class = Alias->getClassInterface();
  1014. }
  1015. if (Class) {
  1016. DiagnoseUseOfDecl(Class, NameLoc);
  1017. if (NextToken.is(tok::period)) {
  1018. // Interface. <something> is parsed as a property reference expression.
  1019. // Just return "unknown" as a fall-through for now.
  1020. Result.suppressDiagnostics();
  1021. return NameClassification::Unknown();
  1022. }
  1023. QualType T = Context.getObjCInterfaceType(Class);
  1024. return ParsedType::make(T);
  1025. }
  1026. // We can have a type template here if we're classifying a template argument.
  1027. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1028. !isa<VarTemplateDecl>(FirstDecl))
  1029. return NameClassification::TypeTemplate(
  1030. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1031. // Check for a tag type hidden by a non-type decl in a few cases where it
  1032. // seems likely a type is wanted instead of the non-type that was found.
  1033. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1034. if ((NextToken.is(tok::identifier) ||
  1035. (NextIsOp &&
  1036. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1037. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1038. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1039. DiagnoseUseOfDecl(Type, NameLoc);
  1040. QualType T = Context.getTypeDeclType(Type);
  1041. if (SS.isNotEmpty())
  1042. return buildNestedType(*this, SS, T, NameLoc);
  1043. return ParsedType::make(T);
  1044. }
  1045. // FIXME: This is context-dependent. We need to defer building the member
  1046. // expression until the classification is consumed.
  1047. if (FirstDecl->isCXXClassMember())
  1048. return NameClassification::ContextIndependentExpr(
  1049. BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr,
  1050. S));
  1051. // If we already know which single declaration is referenced, just annotate
  1052. // that declaration directly.
  1053. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1054. if (Result.isSingleResult() && !ADL)
  1055. return NameClassification::NonType(Result.getRepresentativeDecl());
  1056. // Build an UnresolvedLookupExpr. Note that this doesn't depend on the
  1057. // context in which we performed classification, so it's safe to do now.
  1058. return NameClassification::ContextIndependentExpr(
  1059. BuildDeclarationNameExpr(SS, Result, ADL));
  1060. }
  1061. ExprResult
  1062. Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
  1063. SourceLocation NameLoc) {
  1064. assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
  1065. CXXScopeSpec SS;
  1066. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  1067. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  1068. }
  1069. ExprResult
  1070. Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
  1071. IdentifierInfo *Name,
  1072. SourceLocation NameLoc,
  1073. bool IsAddressOfOperand) {
  1074. DeclarationNameInfo NameInfo(Name, NameLoc);
  1075. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  1076. NameInfo, IsAddressOfOperand,
  1077. /*TemplateArgs=*/nullptr);
  1078. }
  1079. ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
  1080. NamedDecl *Found,
  1081. SourceLocation NameLoc,
  1082. const Token &NextToken) {
  1083. if (getCurMethodDecl() && SS.isEmpty())
  1084. if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
  1085. return BuildIvarRefExpr(S, NameLoc, Ivar);
  1086. // Reconstruct the lookup result.
  1087. LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
  1088. Result.addDecl(Found);
  1089. Result.resolveKind();
  1090. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1091. return BuildDeclarationNameExpr(SS, Result, ADL);
  1092. }
  1093. Sema::TemplateNameKindForDiagnostics
  1094. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1095. auto *TD = Name.getAsTemplateDecl();
  1096. if (!TD)
  1097. return TemplateNameKindForDiagnostics::DependentTemplate;
  1098. if (isa<ClassTemplateDecl>(TD))
  1099. return TemplateNameKindForDiagnostics::ClassTemplate;
  1100. if (isa<FunctionTemplateDecl>(TD))
  1101. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1102. if (isa<VarTemplateDecl>(TD))
  1103. return TemplateNameKindForDiagnostics::VarTemplate;
  1104. if (isa<TypeAliasTemplateDecl>(TD))
  1105. return TemplateNameKindForDiagnostics::AliasTemplate;
  1106. if (isa<TemplateTemplateParmDecl>(TD))
  1107. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1108. if (isa<ConceptDecl>(TD))
  1109. return TemplateNameKindForDiagnostics::Concept;
  1110. return TemplateNameKindForDiagnostics::DependentTemplate;
  1111. }
  1112. // Determines the context to return to after temporarily entering a
  1113. // context. This depends in an unnecessarily complicated way on the
  1114. // exact ordering of callbacks from the parser.
  1115. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1116. // Functions defined inline within classes aren't parsed until we've
  1117. // finished parsing the top-level class, so the top-level class is
  1118. // the context we'll need to return to.
  1119. // A Lambda call operator whose parent is a class must not be treated
  1120. // as an inline member function. A Lambda can be used legally
  1121. // either as an in-class member initializer or a default argument. These
  1122. // are parsed once the class has been marked complete and so the containing
  1123. // context would be the nested class (when the lambda is defined in one);
  1124. // If the class is not complete, then the lambda is being used in an
  1125. // ill-formed fashion (such as to specify the width of a bit-field, or
  1126. // in an array-bound) - in which case we still want to return the
  1127. // lexically containing DC (which could be a nested class).
  1128. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1129. DC = DC->getLexicalParent();
  1130. // A function not defined within a class will always return to its
  1131. // lexical context.
  1132. if (!isa<CXXRecordDecl>(DC))
  1133. return DC;
  1134. // A C++ inline method/friend is parsed *after* the topmost class
  1135. // it was declared in is fully parsed ("complete"); the topmost
  1136. // class is the context we need to return to.
  1137. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1138. DC = RD;
  1139. // Return the declaration context of the topmost class the inline method is
  1140. // declared in.
  1141. return DC;
  1142. }
  1143. return DC->getLexicalParent();
  1144. }
  1145. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1146. assert(getContainingDC(DC) == CurContext &&
  1147. "The next DeclContext should be lexically contained in the current one.");
  1148. CurContext = DC;
  1149. S->setEntity(DC);
  1150. }
  1151. void Sema::PopDeclContext() {
  1152. assert(CurContext && "DeclContext imbalance!");
  1153. CurContext = getContainingDC(CurContext);
  1154. assert(CurContext && "Popped translation unit!");
  1155. }
  1156. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1157. Decl *D) {
  1158. // Unlike PushDeclContext, the context to which we return is not necessarily
  1159. // the containing DC of TD, because the new context will be some pre-existing
  1160. // TagDecl definition instead of a fresh one.
  1161. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1162. CurContext = cast<TagDecl>(D)->getDefinition();
  1163. assert(CurContext && "skipping definition of undefined tag");
  1164. // Start lookups from the parent of the current context; we don't want to look
  1165. // into the pre-existing complete definition.
  1166. S->setEntity(CurContext->getLookupParent());
  1167. return Result;
  1168. }
  1169. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1170. CurContext = static_cast<decltype(CurContext)>(Context);
  1171. }
  1172. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1173. /// of a declarator's nested name specifier.
  1174. ///
  1175. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1176. // C++0x [basic.lookup.unqual]p13:
  1177. // A name used in the definition of a static data member of class
  1178. // X (after the qualified-id of the static member) is looked up as
  1179. // if the name was used in a member function of X.
  1180. // C++0x [basic.lookup.unqual]p14:
  1181. // If a variable member of a namespace is defined outside of the
  1182. // scope of its namespace then any name used in the definition of
  1183. // the variable member (after the declarator-id) is looked up as
  1184. // if the definition of the variable member occurred in its
  1185. // namespace.
  1186. // Both of these imply that we should push a scope whose context
  1187. // is the semantic context of the declaration. We can't use
  1188. // PushDeclContext here because that context is not necessarily
  1189. // lexically contained in the current context. Fortunately,
  1190. // the containing scope should have the appropriate information.
  1191. assert(!S->getEntity() && "scope already has entity");
  1192. #ifndef NDEBUG
  1193. Scope *Ancestor = S->getParent();
  1194. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1195. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1196. #endif
  1197. CurContext = DC;
  1198. S->setEntity(DC);
  1199. }
  1200. void Sema::ExitDeclaratorContext(Scope *S) {
  1201. assert(S->getEntity() == CurContext && "Context imbalance!");
  1202. // Switch back to the lexical context. The safety of this is
  1203. // enforced by an assert in EnterDeclaratorContext.
  1204. Scope *Ancestor = S->getParent();
  1205. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1206. CurContext = Ancestor->getEntity();
  1207. // We don't need to do anything with the scope, which is going to
  1208. // disappear.
  1209. }
  1210. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1211. // We assume that the caller has already called
  1212. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1213. FunctionDecl *FD = D->getAsFunction();
  1214. if (!FD)
  1215. return;
  1216. // Same implementation as PushDeclContext, but enters the context
  1217. // from the lexical parent, rather than the top-level class.
  1218. assert(CurContext == FD->getLexicalParent() &&
  1219. "The next DeclContext should be lexically contained in the current one.");
  1220. CurContext = FD;
  1221. S->setEntity(CurContext);
  1222. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1223. ParmVarDecl *Param = FD->getParamDecl(P);
  1224. // If the parameter has an identifier, then add it to the scope
  1225. if (Param->getIdentifier()) {
  1226. S->AddDecl(Param);
  1227. IdResolver.AddDecl(Param);
  1228. }
  1229. }
  1230. }
  1231. void Sema::ActOnExitFunctionContext() {
  1232. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1233. // rather than the top-level class.
  1234. assert(CurContext && "DeclContext imbalance!");
  1235. CurContext = CurContext->getLexicalParent();
  1236. assert(CurContext && "Popped translation unit!");
  1237. }
  1238. /// Determine whether we allow overloading of the function
  1239. /// PrevDecl with another declaration.
  1240. ///
  1241. /// This routine determines whether overloading is possible, not
  1242. /// whether some new function is actually an overload. It will return
  1243. /// true in C++ (where we can always provide overloads) or, as an
  1244. /// extension, in C when the previous function is already an
  1245. /// overloaded function declaration or has the "overloadable"
  1246. /// attribute.
  1247. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1248. ASTContext &Context,
  1249. const FunctionDecl *New) {
  1250. if (Context.getLangOpts().CPlusPlus)
  1251. return true;
  1252. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1253. return true;
  1254. return Previous.getResultKind() == LookupResult::Found &&
  1255. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1256. New->hasAttr<OverloadableAttr>());
  1257. }
  1258. /// Add this decl to the scope shadowed decl chains.
  1259. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1260. // Move up the scope chain until we find the nearest enclosing
  1261. // non-transparent context. The declaration will be introduced into this
  1262. // scope.
  1263. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1264. S = S->getParent();
  1265. // Add scoped declarations into their context, so that they can be
  1266. // found later. Declarations without a context won't be inserted
  1267. // into any context.
  1268. if (AddToContext)
  1269. CurContext->addDecl(D);
  1270. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1271. // are function-local declarations.
  1272. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1273. !D->getDeclContext()->getRedeclContext()->Equals(
  1274. D->getLexicalDeclContext()->getRedeclContext()) &&
  1275. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1276. return;
  1277. // Template instantiations should also not be pushed into scope.
  1278. if (isa<FunctionDecl>(D) &&
  1279. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1280. return;
  1281. // If this replaces anything in the current scope,
  1282. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1283. IEnd = IdResolver.end();
  1284. for (; I != IEnd; ++I) {
  1285. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1286. S->RemoveDecl(*I);
  1287. IdResolver.RemoveDecl(*I);
  1288. // Should only need to replace one decl.
  1289. break;
  1290. }
  1291. }
  1292. S->AddDecl(D);
  1293. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1294. // Implicitly-generated labels may end up getting generated in an order that
  1295. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1296. // the label at the appropriate place in the identifier chain.
  1297. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1298. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1299. if (IDC == CurContext) {
  1300. if (!S->isDeclScope(*I))
  1301. continue;
  1302. } else if (IDC->Encloses(CurContext))
  1303. break;
  1304. }
  1305. IdResolver.InsertDeclAfter(I, D);
  1306. } else {
  1307. IdResolver.AddDecl(D);
  1308. }
  1309. }
  1310. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1311. bool AllowInlineNamespace) {
  1312. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1313. }
  1314. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1315. DeclContext *TargetDC = DC->getPrimaryContext();
  1316. do {
  1317. if (DeclContext *ScopeDC = S->getEntity())
  1318. if (ScopeDC->getPrimaryContext() == TargetDC)
  1319. return S;
  1320. } while ((S = S->getParent()));
  1321. return nullptr;
  1322. }
  1323. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1324. DeclContext*,
  1325. ASTContext&);
  1326. /// Filters out lookup results that don't fall within the given scope
  1327. /// as determined by isDeclInScope.
  1328. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1329. bool ConsiderLinkage,
  1330. bool AllowInlineNamespace) {
  1331. LookupResult::Filter F = R.makeFilter();
  1332. while (F.hasNext()) {
  1333. NamedDecl *D = F.next();
  1334. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1335. continue;
  1336. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1337. continue;
  1338. F.erase();
  1339. }
  1340. F.done();
  1341. }
  1342. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1343. /// have compatible owning modules.
  1344. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1345. // FIXME: The Modules TS is not clear about how friend declarations are
  1346. // to be treated. It's not meaningful to have different owning modules for
  1347. // linkage in redeclarations of the same entity, so for now allow the
  1348. // redeclaration and change the owning modules to match.
  1349. if (New->getFriendObjectKind() &&
  1350. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1351. New->setLocalOwningModule(Old->getOwningModule());
  1352. makeMergedDefinitionVisible(New);
  1353. return false;
  1354. }
  1355. Module *NewM = New->getOwningModule();
  1356. Module *OldM = Old->getOwningModule();
  1357. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1358. NewM = NewM->Parent;
  1359. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1360. OldM = OldM->Parent;
  1361. if (NewM == OldM)
  1362. return false;
  1363. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1364. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1365. if (NewIsModuleInterface || OldIsModuleInterface) {
  1366. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1367. // if a declaration of D [...] appears in the purview of a module, all
  1368. // other such declarations shall appear in the purview of the same module
  1369. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1370. << New
  1371. << NewIsModuleInterface
  1372. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1373. << OldIsModuleInterface
  1374. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1375. Diag(Old->getLocation(), diag::note_previous_declaration);
  1376. New->setInvalidDecl();
  1377. return true;
  1378. }
  1379. return false;
  1380. }
  1381. static bool isUsingDecl(NamedDecl *D) {
  1382. return isa<UsingShadowDecl>(D) ||
  1383. isa<UnresolvedUsingTypenameDecl>(D) ||
  1384. isa<UnresolvedUsingValueDecl>(D);
  1385. }
  1386. /// Removes using shadow declarations from the lookup results.
  1387. static void RemoveUsingDecls(LookupResult &R) {
  1388. LookupResult::Filter F = R.makeFilter();
  1389. while (F.hasNext())
  1390. if (isUsingDecl(F.next()))
  1391. F.erase();
  1392. F.done();
  1393. }
  1394. /// Check for this common pattern:
  1395. /// @code
  1396. /// class S {
  1397. /// S(const S&); // DO NOT IMPLEMENT
  1398. /// void operator=(const S&); // DO NOT IMPLEMENT
  1399. /// };
  1400. /// @endcode
  1401. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1402. // FIXME: Should check for private access too but access is set after we get
  1403. // the decl here.
  1404. if (D->doesThisDeclarationHaveABody())
  1405. return false;
  1406. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1407. return CD->isCopyConstructor();
  1408. return D->isCopyAssignmentOperator();
  1409. }
  1410. // We need this to handle
  1411. //
  1412. // typedef struct {
  1413. // void *foo() { return 0; }
  1414. // } A;
  1415. //
  1416. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1417. // for example. If 'A', foo will have external linkage. If we have '*A',
  1418. // foo will have no linkage. Since we can't know until we get to the end
  1419. // of the typedef, this function finds out if D might have non-external linkage.
  1420. // Callers should verify at the end of the TU if it D has external linkage or
  1421. // not.
  1422. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1423. const DeclContext *DC = D->getDeclContext();
  1424. while (!DC->isTranslationUnit()) {
  1425. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1426. if (!RD->hasNameForLinkage())
  1427. return true;
  1428. }
  1429. DC = DC->getParent();
  1430. }
  1431. return !D->isExternallyVisible();
  1432. }
  1433. // FIXME: This needs to be refactored; some other isInMainFile users want
  1434. // these semantics.
  1435. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1436. if (S.TUKind != TU_Complete)
  1437. return false;
  1438. return S.SourceMgr.isInMainFile(Loc);
  1439. }
  1440. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1441. assert(D);
  1442. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1443. return false;
  1444. // Ignore all entities declared within templates, and out-of-line definitions
  1445. // of members of class templates.
  1446. if (D->getDeclContext()->isDependentContext() ||
  1447. D->getLexicalDeclContext()->isDependentContext())
  1448. return false;
  1449. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1450. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1451. return false;
  1452. // A non-out-of-line declaration of a member specialization was implicitly
  1453. // instantiated; it's the out-of-line declaration that we're interested in.
  1454. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1455. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1456. return false;
  1457. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1458. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1459. return false;
  1460. } else {
  1461. // 'static inline' functions are defined in headers; don't warn.
  1462. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1463. return false;
  1464. }
  1465. if (FD->doesThisDeclarationHaveABody() &&
  1466. Context.DeclMustBeEmitted(FD))
  1467. return false;
  1468. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1469. // Constants and utility variables are defined in headers with internal
  1470. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1471. // like "inline".)
  1472. if (!isMainFileLoc(*this, VD->getLocation()))
  1473. return false;
  1474. if (Context.DeclMustBeEmitted(VD))
  1475. return false;
  1476. if (VD->isStaticDataMember() &&
  1477. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1478. return false;
  1479. if (VD->isStaticDataMember() &&
  1480. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1481. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1482. return false;
  1483. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1484. return false;
  1485. } else {
  1486. return false;
  1487. }
  1488. // Only warn for unused decls internal to the translation unit.
  1489. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1490. // for inline functions defined in the main source file, for instance.
  1491. return mightHaveNonExternalLinkage(D);
  1492. }
  1493. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1494. if (!D)
  1495. return;
  1496. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1497. const FunctionDecl *First = FD->getFirstDecl();
  1498. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1499. return; // First should already be in the vector.
  1500. }
  1501. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1502. const VarDecl *First = VD->getFirstDecl();
  1503. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1504. return; // First should already be in the vector.
  1505. }
  1506. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1507. UnusedFileScopedDecls.push_back(D);
  1508. }
  1509. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1510. if (D->isInvalidDecl())
  1511. return false;
  1512. bool Referenced = false;
  1513. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1514. // For a decomposition declaration, warn if none of the bindings are
  1515. // referenced, instead of if the variable itself is referenced (which
  1516. // it is, by the bindings' expressions).
  1517. for (auto *BD : DD->bindings()) {
  1518. if (BD->isReferenced()) {
  1519. Referenced = true;
  1520. break;
  1521. }
  1522. }
  1523. } else if (!D->getDeclName()) {
  1524. return false;
  1525. } else if (D->isReferenced() || D->isUsed()) {
  1526. Referenced = true;
  1527. }
  1528. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1529. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1530. return false;
  1531. if (isa<LabelDecl>(D))
  1532. return true;
  1533. // Except for labels, we only care about unused decls that are local to
  1534. // functions.
  1535. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1536. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1537. // For dependent types, the diagnostic is deferred.
  1538. WithinFunction =
  1539. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1540. if (!WithinFunction)
  1541. return false;
  1542. if (isa<TypedefNameDecl>(D))
  1543. return true;
  1544. // White-list anything that isn't a local variable.
  1545. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1546. return false;
  1547. // Types of valid local variables should be complete, so this should succeed.
  1548. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1549. // White-list anything with an __attribute__((unused)) type.
  1550. const auto *Ty = VD->getType().getTypePtr();
  1551. // Only look at the outermost level of typedef.
  1552. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1553. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1554. return false;
  1555. }
  1556. // If we failed to complete the type for some reason, or if the type is
  1557. // dependent, don't diagnose the variable.
  1558. if (Ty->isIncompleteType() || Ty->isDependentType())
  1559. return false;
  1560. // Look at the element type to ensure that the warning behaviour is
  1561. // consistent for both scalars and arrays.
  1562. Ty = Ty->getBaseElementTypeUnsafe();
  1563. if (const TagType *TT = Ty->getAs<TagType>()) {
  1564. const TagDecl *Tag = TT->getDecl();
  1565. if (Tag->hasAttr<UnusedAttr>())
  1566. return false;
  1567. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1568. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1569. return false;
  1570. if (const Expr *Init = VD->getInit()) {
  1571. if (const ExprWithCleanups *Cleanups =
  1572. dyn_cast<ExprWithCleanups>(Init))
  1573. Init = Cleanups->getSubExpr();
  1574. const CXXConstructExpr *Construct =
  1575. dyn_cast<CXXConstructExpr>(Init);
  1576. if (Construct && !Construct->isElidable()) {
  1577. CXXConstructorDecl *CD = Construct->getConstructor();
  1578. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1579. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1580. return false;
  1581. }
  1582. }
  1583. }
  1584. }
  1585. // TODO: __attribute__((unused)) templates?
  1586. }
  1587. return true;
  1588. }
  1589. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1590. FixItHint &Hint) {
  1591. if (isa<LabelDecl>(D)) {
  1592. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1593. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1594. true);
  1595. if (AfterColon.isInvalid())
  1596. return;
  1597. Hint = FixItHint::CreateRemoval(
  1598. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1599. }
  1600. }
  1601. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1602. if (D->getTypeForDecl()->isDependentType())
  1603. return;
  1604. for (auto *TmpD : D->decls()) {
  1605. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1606. DiagnoseUnusedDecl(T);
  1607. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1608. DiagnoseUnusedNestedTypedefs(R);
  1609. }
  1610. }
  1611. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1612. /// unless they are marked attr(unused).
  1613. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1614. if (!ShouldDiagnoseUnusedDecl(D))
  1615. return;
  1616. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1617. // typedefs can be referenced later on, so the diagnostics are emitted
  1618. // at end-of-translation-unit.
  1619. UnusedLocalTypedefNameCandidates.insert(TD);
  1620. return;
  1621. }
  1622. FixItHint Hint;
  1623. GenerateFixForUnusedDecl(D, Context, Hint);
  1624. unsigned DiagID;
  1625. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1626. DiagID = diag::warn_unused_exception_param;
  1627. else if (isa<LabelDecl>(D))
  1628. DiagID = diag::warn_unused_label;
  1629. else
  1630. DiagID = diag::warn_unused_variable;
  1631. Diag(D->getLocation(), DiagID) << D << Hint;
  1632. }
  1633. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1634. // Verify that we have no forward references left. If so, there was a goto
  1635. // or address of a label taken, but no definition of it. Label fwd
  1636. // definitions are indicated with a null substmt which is also not a resolved
  1637. // MS inline assembly label name.
  1638. bool Diagnose = false;
  1639. if (L->isMSAsmLabel())
  1640. Diagnose = !L->isResolvedMSAsmLabel();
  1641. else
  1642. Diagnose = L->getStmt() == nullptr;
  1643. if (Diagnose)
  1644. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1645. }
  1646. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1647. S->mergeNRVOIntoParent();
  1648. if (S->decl_empty()) return;
  1649. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1650. "Scope shouldn't contain decls!");
  1651. for (auto *TmpD : S->decls()) {
  1652. assert(TmpD && "This decl didn't get pushed??");
  1653. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1654. NamedDecl *D = cast<NamedDecl>(TmpD);
  1655. // Diagnose unused variables in this scope.
  1656. if (!S->hasUnrecoverableErrorOccurred()) {
  1657. DiagnoseUnusedDecl(D);
  1658. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1659. DiagnoseUnusedNestedTypedefs(RD);
  1660. }
  1661. if (!D->getDeclName()) continue;
  1662. // If this was a forward reference to a label, verify it was defined.
  1663. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1664. CheckPoppedLabel(LD, *this);
  1665. // Remove this name from our lexical scope, and warn on it if we haven't
  1666. // already.
  1667. IdResolver.RemoveDecl(D);
  1668. auto ShadowI = ShadowingDecls.find(D);
  1669. if (ShadowI != ShadowingDecls.end()) {
  1670. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1671. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1672. << D << FD << FD->getParent();
  1673. Diag(FD->getLocation(), diag::note_previous_declaration);
  1674. }
  1675. ShadowingDecls.erase(ShadowI);
  1676. }
  1677. }
  1678. }
  1679. /// Look for an Objective-C class in the translation unit.
  1680. ///
  1681. /// \param Id The name of the Objective-C class we're looking for. If
  1682. /// typo-correction fixes this name, the Id will be updated
  1683. /// to the fixed name.
  1684. ///
  1685. /// \param IdLoc The location of the name in the translation unit.
  1686. ///
  1687. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1688. /// if there is no class with the given name.
  1689. ///
  1690. /// \returns The declaration of the named Objective-C class, or NULL if the
  1691. /// class could not be found.
  1692. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1693. SourceLocation IdLoc,
  1694. bool DoTypoCorrection) {
  1695. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1696. // creation from this context.
  1697. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1698. if (!IDecl && DoTypoCorrection) {
  1699. // Perform typo correction at the given location, but only if we
  1700. // find an Objective-C class name.
  1701. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1702. if (TypoCorrection C =
  1703. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1704. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1705. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1706. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1707. Id = IDecl->getIdentifier();
  1708. }
  1709. }
  1710. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1711. // This routine must always return a class definition, if any.
  1712. if (Def && Def->getDefinition())
  1713. Def = Def->getDefinition();
  1714. return Def;
  1715. }
  1716. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1717. /// from S, where a non-field would be declared. This routine copes
  1718. /// with the difference between C and C++ scoping rules in structs and
  1719. /// unions. For example, the following code is well-formed in C but
  1720. /// ill-formed in C++:
  1721. /// @code
  1722. /// struct S6 {
  1723. /// enum { BAR } e;
  1724. /// };
  1725. ///
  1726. /// void test_S6() {
  1727. /// struct S6 a;
  1728. /// a.e = BAR;
  1729. /// }
  1730. /// @endcode
  1731. /// For the declaration of BAR, this routine will return a different
  1732. /// scope. The scope S will be the scope of the unnamed enumeration
  1733. /// within S6. In C++, this routine will return the scope associated
  1734. /// with S6, because the enumeration's scope is a transparent
  1735. /// context but structures can contain non-field names. In C, this
  1736. /// routine will return the translation unit scope, since the
  1737. /// enumeration's scope is a transparent context and structures cannot
  1738. /// contain non-field names.
  1739. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1740. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1741. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1742. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1743. S = S->getParent();
  1744. return S;
  1745. }
  1746. /// Looks up the declaration of "struct objc_super" and
  1747. /// saves it for later use in building builtin declaration of
  1748. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1749. /// pre-existing declaration exists no action takes place.
  1750. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1751. IdentifierInfo *II) {
  1752. if (!II->isStr("objc_msgSendSuper"))
  1753. return;
  1754. ASTContext &Context = ThisSema.Context;
  1755. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1756. SourceLocation(), Sema::LookupTagName);
  1757. ThisSema.LookupName(Result, S);
  1758. if (Result.getResultKind() == LookupResult::Found)
  1759. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1760. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1761. }
  1762. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1763. ASTContext::GetBuiltinTypeError Error) {
  1764. switch (Error) {
  1765. case ASTContext::GE_None:
  1766. return "";
  1767. case ASTContext::GE_Missing_type:
  1768. return BuiltinInfo.getHeaderName(ID);
  1769. case ASTContext::GE_Missing_stdio:
  1770. return "stdio.h";
  1771. case ASTContext::GE_Missing_setjmp:
  1772. return "setjmp.h";
  1773. case ASTContext::GE_Missing_ucontext:
  1774. return "ucontext.h";
  1775. }
  1776. llvm_unreachable("unhandled error kind");
  1777. }
  1778. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1779. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1780. /// if we're creating this built-in in anticipation of redeclaring the
  1781. /// built-in.
  1782. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1783. Scope *S, bool ForRedeclaration,
  1784. SourceLocation Loc) {
  1785. LookupPredefedObjCSuperType(*this, S, II);
  1786. ASTContext::GetBuiltinTypeError Error;
  1787. QualType R = Context.GetBuiltinType(ID, Error);
  1788. if (Error) {
  1789. if (!ForRedeclaration)
  1790. return nullptr;
  1791. // If we have a builtin without an associated type we should not emit a
  1792. // warning when we were not able to find a type for it.
  1793. if (Error == ASTContext::GE_Missing_type)
  1794. return nullptr;
  1795. // If we could not find a type for setjmp it is because the jmp_buf type was
  1796. // not defined prior to the setjmp declaration.
  1797. if (Error == ASTContext::GE_Missing_setjmp) {
  1798. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  1799. << Context.BuiltinInfo.getName(ID);
  1800. return nullptr;
  1801. }
  1802. // Generally, we emit a warning that the declaration requires the
  1803. // appropriate header.
  1804. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1805. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1806. << Context.BuiltinInfo.getName(ID);
  1807. return nullptr;
  1808. }
  1809. if (!ForRedeclaration &&
  1810. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1811. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1812. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1813. << Context.BuiltinInfo.getName(ID) << R;
  1814. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1815. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1816. Diag(Loc, diag::note_include_header_or_declare)
  1817. << Context.BuiltinInfo.getHeaderName(ID)
  1818. << Context.BuiltinInfo.getName(ID);
  1819. }
  1820. if (R.isNull())
  1821. return nullptr;
  1822. DeclContext *Parent = Context.getTranslationUnitDecl();
  1823. if (getLangOpts().CPlusPlus) {
  1824. LinkageSpecDecl *CLinkageDecl =
  1825. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1826. LinkageSpecDecl::lang_c, false);
  1827. CLinkageDecl->setImplicit();
  1828. Parent->addDecl(CLinkageDecl);
  1829. Parent = CLinkageDecl;
  1830. }
  1831. FunctionDecl *New = FunctionDecl::Create(Context,
  1832. Parent,
  1833. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1834. SC_Extern,
  1835. false,
  1836. R->isFunctionProtoType());
  1837. New->setImplicit();
  1838. // Create Decl objects for each parameter, adding them to the
  1839. // FunctionDecl.
  1840. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1841. SmallVector<ParmVarDecl*, 16> Params;
  1842. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1843. ParmVarDecl *parm =
  1844. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1845. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1846. SC_None, nullptr);
  1847. parm->setScopeInfo(0, i);
  1848. Params.push_back(parm);
  1849. }
  1850. New->setParams(Params);
  1851. }
  1852. AddKnownFunctionAttributes(New);
  1853. RegisterLocallyScopedExternCDecl(New, S);
  1854. // TUScope is the translation-unit scope to insert this function into.
  1855. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1856. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1857. // entirely, but we're not there yet.
  1858. DeclContext *SavedContext = CurContext;
  1859. CurContext = Parent;
  1860. PushOnScopeChains(New, TUScope);
  1861. CurContext = SavedContext;
  1862. return New;
  1863. }
  1864. /// Typedef declarations don't have linkage, but they still denote the same
  1865. /// entity if their types are the same.
  1866. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1867. /// isSameEntity.
  1868. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1869. TypedefNameDecl *Decl,
  1870. LookupResult &Previous) {
  1871. // This is only interesting when modules are enabled.
  1872. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1873. return;
  1874. // Empty sets are uninteresting.
  1875. if (Previous.empty())
  1876. return;
  1877. LookupResult::Filter Filter = Previous.makeFilter();
  1878. while (Filter.hasNext()) {
  1879. NamedDecl *Old = Filter.next();
  1880. // Non-hidden declarations are never ignored.
  1881. if (S.isVisible(Old))
  1882. continue;
  1883. // Declarations of the same entity are not ignored, even if they have
  1884. // different linkages.
  1885. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1886. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1887. Decl->getUnderlyingType()))
  1888. continue;
  1889. // If both declarations give a tag declaration a typedef name for linkage
  1890. // purposes, then they declare the same entity.
  1891. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1892. Decl->getAnonDeclWithTypedefName())
  1893. continue;
  1894. }
  1895. Filter.erase();
  1896. }
  1897. Filter.done();
  1898. }
  1899. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1900. QualType OldType;
  1901. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1902. OldType = OldTypedef->getUnderlyingType();
  1903. else
  1904. OldType = Context.getTypeDeclType(Old);
  1905. QualType NewType = New->getUnderlyingType();
  1906. if (NewType->isVariablyModifiedType()) {
  1907. // Must not redefine a typedef with a variably-modified type.
  1908. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1909. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1910. << Kind << NewType;
  1911. if (Old->getLocation().isValid())
  1912. notePreviousDefinition(Old, New->getLocation());
  1913. New->setInvalidDecl();
  1914. return true;
  1915. }
  1916. if (OldType != NewType &&
  1917. !OldType->isDependentType() &&
  1918. !NewType->isDependentType() &&
  1919. !Context.hasSameType(OldType, NewType)) {
  1920. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1921. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1922. << Kind << NewType << OldType;
  1923. if (Old->getLocation().isValid())
  1924. notePreviousDefinition(Old, New->getLocation());
  1925. New->setInvalidDecl();
  1926. return true;
  1927. }
  1928. return false;
  1929. }
  1930. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1931. /// same name and scope as a previous declaration 'Old'. Figure out
  1932. /// how to resolve this situation, merging decls or emitting
  1933. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1934. ///
  1935. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1936. LookupResult &OldDecls) {
  1937. // If the new decl is known invalid already, don't bother doing any
  1938. // merging checks.
  1939. if (New->isInvalidDecl()) return;
  1940. // Allow multiple definitions for ObjC built-in typedefs.
  1941. // FIXME: Verify the underlying types are equivalent!
  1942. if (getLangOpts().ObjC) {
  1943. const IdentifierInfo *TypeID = New->getIdentifier();
  1944. switch (TypeID->getLength()) {
  1945. default: break;
  1946. case 2:
  1947. {
  1948. if (!TypeID->isStr("id"))
  1949. break;
  1950. QualType T = New->getUnderlyingType();
  1951. if (!T->isPointerType())
  1952. break;
  1953. if (!T->isVoidPointerType()) {
  1954. QualType PT = T->castAs<PointerType>()->getPointeeType();
  1955. if (!PT->isStructureType())
  1956. break;
  1957. }
  1958. Context.setObjCIdRedefinitionType(T);
  1959. // Install the built-in type for 'id', ignoring the current definition.
  1960. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1961. return;
  1962. }
  1963. case 5:
  1964. if (!TypeID->isStr("Class"))
  1965. break;
  1966. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1967. // Install the built-in type for 'Class', ignoring the current definition.
  1968. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1969. return;
  1970. case 3:
  1971. if (!TypeID->isStr("SEL"))
  1972. break;
  1973. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1974. // Install the built-in type for 'SEL', ignoring the current definition.
  1975. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1976. return;
  1977. }
  1978. // Fall through - the typedef name was not a builtin type.
  1979. }
  1980. // Verify the old decl was also a type.
  1981. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1982. if (!Old) {
  1983. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1984. << New->getDeclName();
  1985. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1986. if (OldD->getLocation().isValid())
  1987. notePreviousDefinition(OldD, New->getLocation());
  1988. return New->setInvalidDecl();
  1989. }
  1990. // If the old declaration is invalid, just give up here.
  1991. if (Old->isInvalidDecl())
  1992. return New->setInvalidDecl();
  1993. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1994. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1995. auto *NewTag = New->getAnonDeclWithTypedefName();
  1996. NamedDecl *Hidden = nullptr;
  1997. if (OldTag && NewTag &&
  1998. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1999. !hasVisibleDefinition(OldTag, &Hidden)) {
  2000. // There is a definition of this tag, but it is not visible. Use it
  2001. // instead of our tag.
  2002. New->setTypeForDecl(OldTD->getTypeForDecl());
  2003. if (OldTD->isModed())
  2004. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  2005. OldTD->getUnderlyingType());
  2006. else
  2007. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  2008. // Make the old tag definition visible.
  2009. makeMergedDefinitionVisible(Hidden);
  2010. // If this was an unscoped enumeration, yank all of its enumerators
  2011. // out of the scope.
  2012. if (isa<EnumDecl>(NewTag)) {
  2013. Scope *EnumScope = getNonFieldDeclScope(S);
  2014. for (auto *D : NewTag->decls()) {
  2015. auto *ED = cast<EnumConstantDecl>(D);
  2016. assert(EnumScope->isDeclScope(ED));
  2017. EnumScope->RemoveDecl(ED);
  2018. IdResolver.RemoveDecl(ED);
  2019. ED->getLexicalDeclContext()->removeDecl(ED);
  2020. }
  2021. }
  2022. }
  2023. }
  2024. // If the typedef types are not identical, reject them in all languages and
  2025. // with any extensions enabled.
  2026. if (isIncompatibleTypedef(Old, New))
  2027. return;
  2028. // The types match. Link up the redeclaration chain and merge attributes if
  2029. // the old declaration was a typedef.
  2030. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  2031. New->setPreviousDecl(Typedef);
  2032. mergeDeclAttributes(New, Old);
  2033. }
  2034. if (getLangOpts().MicrosoftExt)
  2035. return;
  2036. if (getLangOpts().CPlusPlus) {
  2037. // C++ [dcl.typedef]p2:
  2038. // In a given non-class scope, a typedef specifier can be used to
  2039. // redefine the name of any type declared in that scope to refer
  2040. // to the type to which it already refers.
  2041. if (!isa<CXXRecordDecl>(CurContext))
  2042. return;
  2043. // C++0x [dcl.typedef]p4:
  2044. // In a given class scope, a typedef specifier can be used to redefine
  2045. // any class-name declared in that scope that is not also a typedef-name
  2046. // to refer to the type to which it already refers.
  2047. //
  2048. // This wording came in via DR424, which was a correction to the
  2049. // wording in DR56, which accidentally banned code like:
  2050. //
  2051. // struct S {
  2052. // typedef struct A { } A;
  2053. // };
  2054. //
  2055. // in the C++03 standard. We implement the C++0x semantics, which
  2056. // allow the above but disallow
  2057. //
  2058. // struct S {
  2059. // typedef int I;
  2060. // typedef int I;
  2061. // };
  2062. //
  2063. // since that was the intent of DR56.
  2064. if (!isa<TypedefNameDecl>(Old))
  2065. return;
  2066. Diag(New->getLocation(), diag::err_redefinition)
  2067. << New->getDeclName();
  2068. notePreviousDefinition(Old, New->getLocation());
  2069. return New->setInvalidDecl();
  2070. }
  2071. // Modules always permit redefinition of typedefs, as does C11.
  2072. if (getLangOpts().Modules || getLangOpts().C11)
  2073. return;
  2074. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2075. // is normally mapped to an error, but can be controlled with
  2076. // -Wtypedef-redefinition. If either the original or the redefinition is
  2077. // in a system header, don't emit this for compatibility with GCC.
  2078. if (getDiagnostics().getSuppressSystemWarnings() &&
  2079. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2080. (Old->isImplicit() ||
  2081. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2082. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2083. return;
  2084. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2085. << New->getDeclName();
  2086. notePreviousDefinition(Old, New->getLocation());
  2087. }
  2088. /// DeclhasAttr - returns true if decl Declaration already has the target
  2089. /// attribute.
  2090. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2091. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2092. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2093. for (const auto *i : D->attrs())
  2094. if (i->getKind() == A->getKind()) {
  2095. if (Ann) {
  2096. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2097. return true;
  2098. continue;
  2099. }
  2100. // FIXME: Don't hardcode this check
  2101. if (OA && isa<OwnershipAttr>(i))
  2102. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2103. return true;
  2104. }
  2105. return false;
  2106. }
  2107. static bool isAttributeTargetADefinition(Decl *D) {
  2108. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2109. return VD->isThisDeclarationADefinition();
  2110. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2111. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2112. return true;
  2113. }
  2114. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2115. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2116. ///
  2117. /// \return \c true if any attributes were added to \p New.
  2118. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2119. // Look for alignas attributes on Old, and pick out whichever attribute
  2120. // specifies the strictest alignment requirement.
  2121. AlignedAttr *OldAlignasAttr = nullptr;
  2122. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2123. unsigned OldAlign = 0;
  2124. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2125. // FIXME: We have no way of representing inherited dependent alignments
  2126. // in a case like:
  2127. // template<int A, int B> struct alignas(A) X;
  2128. // template<int A, int B> struct alignas(B) X {};
  2129. // For now, we just ignore any alignas attributes which are not on the
  2130. // definition in such a case.
  2131. if (I->isAlignmentDependent())
  2132. return false;
  2133. if (I->isAlignas())
  2134. OldAlignasAttr = I;
  2135. unsigned Align = I->getAlignment(S.Context);
  2136. if (Align > OldAlign) {
  2137. OldAlign = Align;
  2138. OldStrictestAlignAttr = I;
  2139. }
  2140. }
  2141. // Look for alignas attributes on New.
  2142. AlignedAttr *NewAlignasAttr = nullptr;
  2143. unsigned NewAlign = 0;
  2144. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2145. if (I->isAlignmentDependent())
  2146. return false;
  2147. if (I->isAlignas())
  2148. NewAlignasAttr = I;
  2149. unsigned Align = I->getAlignment(S.Context);
  2150. if (Align > NewAlign)
  2151. NewAlign = Align;
  2152. }
  2153. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2154. // Both declarations have 'alignas' attributes. We require them to match.
  2155. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2156. // fall short. (If two declarations both have alignas, they must both match
  2157. // every definition, and so must match each other if there is a definition.)
  2158. // If either declaration only contains 'alignas(0)' specifiers, then it
  2159. // specifies the natural alignment for the type.
  2160. if (OldAlign == 0 || NewAlign == 0) {
  2161. QualType Ty;
  2162. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2163. Ty = VD->getType();
  2164. else
  2165. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2166. if (OldAlign == 0)
  2167. OldAlign = S.Context.getTypeAlign(Ty);
  2168. if (NewAlign == 0)
  2169. NewAlign = S.Context.getTypeAlign(Ty);
  2170. }
  2171. if (OldAlign != NewAlign) {
  2172. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2173. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2174. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2175. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2176. }
  2177. }
  2178. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2179. // C++11 [dcl.align]p6:
  2180. // if any declaration of an entity has an alignment-specifier,
  2181. // every defining declaration of that entity shall specify an
  2182. // equivalent alignment.
  2183. // C11 6.7.5/7:
  2184. // If the definition of an object does not have an alignment
  2185. // specifier, any other declaration of that object shall also
  2186. // have no alignment specifier.
  2187. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2188. << OldAlignasAttr;
  2189. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2190. << OldAlignasAttr;
  2191. }
  2192. bool AnyAdded = false;
  2193. // Ensure we have an attribute representing the strictest alignment.
  2194. if (OldAlign > NewAlign) {
  2195. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2196. Clone->setInherited(true);
  2197. New->addAttr(Clone);
  2198. AnyAdded = true;
  2199. }
  2200. // Ensure we have an alignas attribute if the old declaration had one.
  2201. if (OldAlignasAttr && !NewAlignasAttr &&
  2202. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2203. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2204. Clone->setInherited(true);
  2205. New->addAttr(Clone);
  2206. AnyAdded = true;
  2207. }
  2208. return AnyAdded;
  2209. }
  2210. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2211. const InheritableAttr *Attr,
  2212. Sema::AvailabilityMergeKind AMK) {
  2213. // This function copies an attribute Attr from a previous declaration to the
  2214. // new declaration D if the new declaration doesn't itself have that attribute
  2215. // yet or if that attribute allows duplicates.
  2216. // If you're adding a new attribute that requires logic different from
  2217. // "use explicit attribute on decl if present, else use attribute from
  2218. // previous decl", for example if the attribute needs to be consistent
  2219. // between redeclarations, you need to call a custom merge function here.
  2220. InheritableAttr *NewAttr = nullptr;
  2221. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2222. NewAttr = S.mergeAvailabilityAttr(
  2223. D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
  2224. AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
  2225. AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
  2226. AA->getPriority());
  2227. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2228. NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
  2229. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2230. NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
  2231. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2232. NewAttr = S.mergeDLLImportAttr(D, *ImportA);
  2233. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2234. NewAttr = S.mergeDLLExportAttr(D, *ExportA);
  2235. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2236. NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
  2237. FA->getFirstArg());
  2238. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2239. NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
  2240. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2241. NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
  2242. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2243. NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
  2244. IA->getSemanticSpelling());
  2245. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2246. NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
  2247. &S.Context.Idents.get(AA->getSpelling()));
  2248. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2249. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2250. isa<CUDAGlobalAttr>(Attr))) {
  2251. // CUDA target attributes are part of function signature for
  2252. // overloading purposes and must not be merged.
  2253. return false;
  2254. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2255. NewAttr = S.mergeMinSizeAttr(D, *MA);
  2256. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2257. NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
  2258. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2259. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2260. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2261. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2262. else if (isa<AlignedAttr>(Attr))
  2263. // AlignedAttrs are handled separately, because we need to handle all
  2264. // such attributes on a declaration at the same time.
  2265. NewAttr = nullptr;
  2266. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2267. (AMK == Sema::AMK_Override ||
  2268. AMK == Sema::AMK_ProtocolImplementation))
  2269. NewAttr = nullptr;
  2270. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2271. NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid());
  2272. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2273. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2274. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2275. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2276. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2277. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2278. if (NewAttr) {
  2279. NewAttr->setInherited(true);
  2280. D->addAttr(NewAttr);
  2281. if (isa<MSInheritanceAttr>(NewAttr))
  2282. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2283. return true;
  2284. }
  2285. return false;
  2286. }
  2287. static const NamedDecl *getDefinition(const Decl *D) {
  2288. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2289. return TD->getDefinition();
  2290. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2291. const VarDecl *Def = VD->getDefinition();
  2292. if (Def)
  2293. return Def;
  2294. return VD->getActingDefinition();
  2295. }
  2296. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2297. return FD->getDefinition();
  2298. return nullptr;
  2299. }
  2300. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2301. for (const auto *Attribute : D->attrs())
  2302. if (Attribute->getKind() == Kind)
  2303. return true;
  2304. return false;
  2305. }
  2306. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2307. /// there are no new attributes in this declaration.
  2308. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2309. if (!New->hasAttrs())
  2310. return;
  2311. const NamedDecl *Def = getDefinition(Old);
  2312. if (!Def || Def == New)
  2313. return;
  2314. AttrVec &NewAttributes = New->getAttrs();
  2315. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2316. const Attr *NewAttribute = NewAttributes[I];
  2317. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2318. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2319. Sema::SkipBodyInfo SkipBody;
  2320. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2321. // If we're skipping this definition, drop the "alias" attribute.
  2322. if (SkipBody.ShouldSkip) {
  2323. NewAttributes.erase(NewAttributes.begin() + I);
  2324. --E;
  2325. continue;
  2326. }
  2327. } else {
  2328. VarDecl *VD = cast<VarDecl>(New);
  2329. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2330. VarDecl::TentativeDefinition
  2331. ? diag::err_alias_after_tentative
  2332. : diag::err_redefinition;
  2333. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2334. if (Diag == diag::err_redefinition)
  2335. S.notePreviousDefinition(Def, VD->getLocation());
  2336. else
  2337. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2338. VD->setInvalidDecl();
  2339. }
  2340. ++I;
  2341. continue;
  2342. }
  2343. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2344. // Tentative definitions are only interesting for the alias check above.
  2345. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2346. ++I;
  2347. continue;
  2348. }
  2349. }
  2350. if (hasAttribute(Def, NewAttribute->getKind())) {
  2351. ++I;
  2352. continue; // regular attr merging will take care of validating this.
  2353. }
  2354. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2355. // C's _Noreturn is allowed to be added to a function after it is defined.
  2356. ++I;
  2357. continue;
  2358. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2359. if (AA->isAlignas()) {
  2360. // C++11 [dcl.align]p6:
  2361. // if any declaration of an entity has an alignment-specifier,
  2362. // every defining declaration of that entity shall specify an
  2363. // equivalent alignment.
  2364. // C11 6.7.5/7:
  2365. // If the definition of an object does not have an alignment
  2366. // specifier, any other declaration of that object shall also
  2367. // have no alignment specifier.
  2368. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2369. << AA;
  2370. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2371. << AA;
  2372. NewAttributes.erase(NewAttributes.begin() + I);
  2373. --E;
  2374. continue;
  2375. }
  2376. } else if (isa<SelectAnyAttr>(NewAttribute) &&
  2377. cast<VarDecl>(New)->isInline() &&
  2378. !cast<VarDecl>(New)->isInlineSpecified()) {
  2379. // Don't warn about applying selectany to implicitly inline variables.
  2380. // Older compilers and language modes would require the use of selectany
  2381. // to make such variables inline, and it would have no effect if we
  2382. // honored it.
  2383. ++I;
  2384. continue;
  2385. }
  2386. S.Diag(NewAttribute->getLocation(),
  2387. diag::warn_attribute_precede_definition);
  2388. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2389. NewAttributes.erase(NewAttributes.begin() + I);
  2390. --E;
  2391. }
  2392. }
  2393. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2394. const ConstInitAttr *CIAttr,
  2395. bool AttrBeforeInit) {
  2396. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2397. // Figure out a good way to write this specifier on the old declaration.
  2398. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2399. // enough of the attribute list spelling information to extract that without
  2400. // heroics.
  2401. std::string SuitableSpelling;
  2402. if (S.getLangOpts().CPlusPlus2a)
  2403. SuitableSpelling =
  2404. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit});
  2405. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2406. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2407. InsertLoc,
  2408. {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"),
  2409. tok::coloncolon,
  2410. S.PP.getIdentifierInfo("require_constant_initialization"),
  2411. tok::r_square, tok::r_square});
  2412. if (SuitableSpelling.empty())
  2413. SuitableSpelling = S.PP.getLastMacroWithSpelling(
  2414. InsertLoc,
  2415. {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2416. S.PP.getIdentifierInfo("require_constant_initialization"),
  2417. tok::r_paren, tok::r_paren});
  2418. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a)
  2419. SuitableSpelling = "constinit";
  2420. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2421. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2422. if (SuitableSpelling.empty())
  2423. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2424. SuitableSpelling += " ";
  2425. if (AttrBeforeInit) {
  2426. // extern constinit int a;
  2427. // int a = 0; // error (missing 'constinit'), accepted as extension
  2428. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2429. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2430. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2431. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2432. } else {
  2433. // int a = 0;
  2434. // constinit extern int a; // error (missing 'constinit')
  2435. S.Diag(CIAttr->getLocation(),
  2436. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2437. : diag::warn_require_const_init_added_too_late)
  2438. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2439. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2440. << CIAttr->isConstinit()
  2441. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2442. }
  2443. }
  2444. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2445. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2446. AvailabilityMergeKind AMK) {
  2447. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2448. UsedAttr *NewAttr = OldAttr->clone(Context);
  2449. NewAttr->setInherited(true);
  2450. New->addAttr(NewAttr);
  2451. }
  2452. if (!Old->hasAttrs() && !New->hasAttrs())
  2453. return;
  2454. // [dcl.constinit]p1:
  2455. // If the [constinit] specifier is applied to any declaration of a
  2456. // variable, it shall be applied to the initializing declaration.
  2457. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2458. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2459. if (bool(OldConstInit) != bool(NewConstInit)) {
  2460. const auto *OldVD = cast<VarDecl>(Old);
  2461. auto *NewVD = cast<VarDecl>(New);
  2462. // Find the initializing declaration. Note that we might not have linked
  2463. // the new declaration into the redeclaration chain yet.
  2464. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2465. if (!InitDecl &&
  2466. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2467. InitDecl = NewVD;
  2468. if (InitDecl == NewVD) {
  2469. // This is the initializing declaration. If it would inherit 'constinit',
  2470. // that's ill-formed. (Note that we do not apply this to the attribute
  2471. // form).
  2472. if (OldConstInit && OldConstInit->isConstinit())
  2473. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2474. /*AttrBeforeInit=*/true);
  2475. } else if (NewConstInit) {
  2476. // This is the first time we've been told that this declaration should
  2477. // have a constant initializer. If we already saw the initializing
  2478. // declaration, this is too late.
  2479. if (InitDecl && InitDecl != NewVD) {
  2480. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2481. /*AttrBeforeInit=*/false);
  2482. NewVD->dropAttr<ConstInitAttr>();
  2483. }
  2484. }
  2485. }
  2486. // Attributes declared post-definition are currently ignored.
  2487. checkNewAttributesAfterDef(*this, New, Old);
  2488. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2489. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2490. if (!OldA->isEquivalent(NewA)) {
  2491. // This redeclaration changes __asm__ label.
  2492. Diag(New->getLocation(), diag::err_different_asm_label);
  2493. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2494. }
  2495. } else if (Old->isUsed()) {
  2496. // This redeclaration adds an __asm__ label to a declaration that has
  2497. // already been ODR-used.
  2498. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2499. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2500. }
  2501. }
  2502. // Re-declaration cannot add abi_tag's.
  2503. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2504. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2505. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2506. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2507. NewTag) == OldAbiTagAttr->tags_end()) {
  2508. Diag(NewAbiTagAttr->getLocation(),
  2509. diag::err_new_abi_tag_on_redeclaration)
  2510. << NewTag;
  2511. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2512. }
  2513. }
  2514. } else {
  2515. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2516. Diag(Old->getLocation(), diag::note_previous_declaration);
  2517. }
  2518. }
  2519. // This redeclaration adds a section attribute.
  2520. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2521. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2522. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2523. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2524. Diag(Old->getLocation(), diag::note_previous_declaration);
  2525. }
  2526. }
  2527. }
  2528. // Redeclaration adds code-seg attribute.
  2529. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2530. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2531. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2532. Diag(New->getLocation(), diag::warn_mismatched_section)
  2533. << 0 /*codeseg*/;
  2534. Diag(Old->getLocation(), diag::note_previous_declaration);
  2535. }
  2536. if (!Old->hasAttrs())
  2537. return;
  2538. bool foundAny = New->hasAttrs();
  2539. // Ensure that any moving of objects within the allocated map is done before
  2540. // we process them.
  2541. if (!foundAny) New->setAttrs(AttrVec());
  2542. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2543. // Ignore deprecated/unavailable/availability attributes if requested.
  2544. AvailabilityMergeKind LocalAMK = AMK_None;
  2545. if (isa<DeprecatedAttr>(I) ||
  2546. isa<UnavailableAttr>(I) ||
  2547. isa<AvailabilityAttr>(I)) {
  2548. switch (AMK) {
  2549. case AMK_None:
  2550. continue;
  2551. case AMK_Redeclaration:
  2552. case AMK_Override:
  2553. case AMK_ProtocolImplementation:
  2554. LocalAMK = AMK;
  2555. break;
  2556. }
  2557. }
  2558. // Already handled.
  2559. if (isa<UsedAttr>(I))
  2560. continue;
  2561. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2562. foundAny = true;
  2563. }
  2564. if (mergeAlignedAttrs(*this, New, Old))
  2565. foundAny = true;
  2566. if (!foundAny) New->dropAttrs();
  2567. }
  2568. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2569. /// to the new one.
  2570. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2571. const ParmVarDecl *oldDecl,
  2572. Sema &S) {
  2573. // C++11 [dcl.attr.depend]p2:
  2574. // The first declaration of a function shall specify the
  2575. // carries_dependency attribute for its declarator-id if any declaration
  2576. // of the function specifies the carries_dependency attribute.
  2577. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2578. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2579. S.Diag(CDA->getLocation(),
  2580. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2581. // Find the first declaration of the parameter.
  2582. // FIXME: Should we build redeclaration chains for function parameters?
  2583. const FunctionDecl *FirstFD =
  2584. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2585. const ParmVarDecl *FirstVD =
  2586. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2587. S.Diag(FirstVD->getLocation(),
  2588. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2589. }
  2590. if (!oldDecl->hasAttrs())
  2591. return;
  2592. bool foundAny = newDecl->hasAttrs();
  2593. // Ensure that any moving of objects within the allocated map is
  2594. // done before we process them.
  2595. if (!foundAny) newDecl->setAttrs(AttrVec());
  2596. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2597. if (!DeclHasAttr(newDecl, I)) {
  2598. InheritableAttr *newAttr =
  2599. cast<InheritableParamAttr>(I->clone(S.Context));
  2600. newAttr->setInherited(true);
  2601. newDecl->addAttr(newAttr);
  2602. foundAny = true;
  2603. }
  2604. }
  2605. if (!foundAny) newDecl->dropAttrs();
  2606. }
  2607. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2608. const ParmVarDecl *OldParam,
  2609. Sema &S) {
  2610. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2611. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2612. if (*Oldnullability != *Newnullability) {
  2613. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2614. << DiagNullabilityKind(
  2615. *Newnullability,
  2616. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2617. != 0))
  2618. << DiagNullabilityKind(
  2619. *Oldnullability,
  2620. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2621. != 0));
  2622. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2623. }
  2624. } else {
  2625. QualType NewT = NewParam->getType();
  2626. NewT = S.Context.getAttributedType(
  2627. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2628. NewT, NewT);
  2629. NewParam->setType(NewT);
  2630. }
  2631. }
  2632. }
  2633. namespace {
  2634. /// Used in MergeFunctionDecl to keep track of function parameters in
  2635. /// C.
  2636. struct GNUCompatibleParamWarning {
  2637. ParmVarDecl *OldParm;
  2638. ParmVarDecl *NewParm;
  2639. QualType PromotedType;
  2640. };
  2641. } // end anonymous namespace
  2642. /// getSpecialMember - get the special member enum for a method.
  2643. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2644. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2645. if (Ctor->isDefaultConstructor())
  2646. return Sema::CXXDefaultConstructor;
  2647. if (Ctor->isCopyConstructor())
  2648. return Sema::CXXCopyConstructor;
  2649. if (Ctor->isMoveConstructor())
  2650. return Sema::CXXMoveConstructor;
  2651. } else if (isa<CXXDestructorDecl>(MD)) {
  2652. return Sema::CXXDestructor;
  2653. } else if (MD->isCopyAssignmentOperator()) {
  2654. return Sema::CXXCopyAssignment;
  2655. } else if (MD->isMoveAssignmentOperator()) {
  2656. return Sema::CXXMoveAssignment;
  2657. }
  2658. return Sema::CXXInvalid;
  2659. }
  2660. // Determine whether the previous declaration was a definition, implicit
  2661. // declaration, or a declaration.
  2662. template <typename T>
  2663. static std::pair<diag::kind, SourceLocation>
  2664. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2665. diag::kind PrevDiag;
  2666. SourceLocation OldLocation = Old->getLocation();
  2667. if (Old->isThisDeclarationADefinition())
  2668. PrevDiag = diag::note_previous_definition;
  2669. else if (Old->isImplicit()) {
  2670. PrevDiag = diag::note_previous_implicit_declaration;
  2671. if (OldLocation.isInvalid())
  2672. OldLocation = New->getLocation();
  2673. } else
  2674. PrevDiag = diag::note_previous_declaration;
  2675. return std::make_pair(PrevDiag, OldLocation);
  2676. }
  2677. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2678. /// only extern inline functions can be redefined, and even then only in
  2679. /// GNU89 mode.
  2680. static bool canRedefineFunction(const FunctionDecl *FD,
  2681. const LangOptions& LangOpts) {
  2682. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2683. !LangOpts.CPlusPlus &&
  2684. FD->isInlineSpecified() &&
  2685. FD->getStorageClass() == SC_Extern);
  2686. }
  2687. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2688. const AttributedType *AT = T->getAs<AttributedType>();
  2689. while (AT && !AT->isCallingConv())
  2690. AT = AT->getModifiedType()->getAs<AttributedType>();
  2691. return AT;
  2692. }
  2693. template <typename T>
  2694. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2695. const DeclContext *DC = Old->getDeclContext();
  2696. if (DC->isRecord())
  2697. return false;
  2698. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2699. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2700. return true;
  2701. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2702. return true;
  2703. return false;
  2704. }
  2705. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2706. static bool isExternC(VarTemplateDecl *) { return false; }
  2707. /// Check whether a redeclaration of an entity introduced by a
  2708. /// using-declaration is valid, given that we know it's not an overload
  2709. /// (nor a hidden tag declaration).
  2710. template<typename ExpectedDecl>
  2711. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2712. ExpectedDecl *New) {
  2713. // C++11 [basic.scope.declarative]p4:
  2714. // Given a set of declarations in a single declarative region, each of
  2715. // which specifies the same unqualified name,
  2716. // -- they shall all refer to the same entity, or all refer to functions
  2717. // and function templates; or
  2718. // -- exactly one declaration shall declare a class name or enumeration
  2719. // name that is not a typedef name and the other declarations shall all
  2720. // refer to the same variable or enumerator, or all refer to functions
  2721. // and function templates; in this case the class name or enumeration
  2722. // name is hidden (3.3.10).
  2723. // C++11 [namespace.udecl]p14:
  2724. // If a function declaration in namespace scope or block scope has the
  2725. // same name and the same parameter-type-list as a function introduced
  2726. // by a using-declaration, and the declarations do not declare the same
  2727. // function, the program is ill-formed.
  2728. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2729. if (Old &&
  2730. !Old->getDeclContext()->getRedeclContext()->Equals(
  2731. New->getDeclContext()->getRedeclContext()) &&
  2732. !(isExternC(Old) && isExternC(New)))
  2733. Old = nullptr;
  2734. if (!Old) {
  2735. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2736. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2737. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2738. return true;
  2739. }
  2740. return false;
  2741. }
  2742. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2743. const FunctionDecl *B) {
  2744. assert(A->getNumParams() == B->getNumParams());
  2745. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2746. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2747. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2748. if (AttrA == AttrB)
  2749. return true;
  2750. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2751. AttrA->isDynamic() == AttrB->isDynamic();
  2752. };
  2753. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2754. }
  2755. /// If necessary, adjust the semantic declaration context for a qualified
  2756. /// declaration to name the correct inline namespace within the qualifier.
  2757. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2758. DeclaratorDecl *OldD) {
  2759. // The only case where we need to update the DeclContext is when
  2760. // redeclaration lookup for a qualified name finds a declaration
  2761. // in an inline namespace within the context named by the qualifier:
  2762. //
  2763. // inline namespace N { int f(); }
  2764. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2765. //
  2766. // For unqualified declarations, the semantic context *can* change
  2767. // along the redeclaration chain (for local extern declarations,
  2768. // extern "C" declarations, and friend declarations in particular).
  2769. if (!NewD->getQualifier())
  2770. return;
  2771. // NewD is probably already in the right context.
  2772. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2773. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2774. if (NamedDC->Equals(SemaDC))
  2775. return;
  2776. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2777. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2778. "unexpected context for redeclaration");
  2779. auto *LexDC = NewD->getLexicalDeclContext();
  2780. auto FixSemaDC = [=](NamedDecl *D) {
  2781. if (!D)
  2782. return;
  2783. D->setDeclContext(SemaDC);
  2784. D->setLexicalDeclContext(LexDC);
  2785. };
  2786. FixSemaDC(NewD);
  2787. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2788. FixSemaDC(FD->getDescribedFunctionTemplate());
  2789. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2790. FixSemaDC(VD->getDescribedVarTemplate());
  2791. }
  2792. /// MergeFunctionDecl - We just parsed a function 'New' from
  2793. /// declarator D which has the same name and scope as a previous
  2794. /// declaration 'Old'. Figure out how to resolve this situation,
  2795. /// merging decls or emitting diagnostics as appropriate.
  2796. ///
  2797. /// In C++, New and Old must be declarations that are not
  2798. /// overloaded. Use IsOverload to determine whether New and Old are
  2799. /// overloaded, and to select the Old declaration that New should be
  2800. /// merged with.
  2801. ///
  2802. /// Returns true if there was an error, false otherwise.
  2803. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2804. Scope *S, bool MergeTypeWithOld) {
  2805. // Verify the old decl was also a function.
  2806. FunctionDecl *Old = OldD->getAsFunction();
  2807. if (!Old) {
  2808. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2809. if (New->getFriendObjectKind()) {
  2810. Diag(New->getLocation(), diag::err_using_decl_friend);
  2811. Diag(Shadow->getTargetDecl()->getLocation(),
  2812. diag::note_using_decl_target);
  2813. Diag(Shadow->getUsingDecl()->getLocation(),
  2814. diag::note_using_decl) << 0;
  2815. return true;
  2816. }
  2817. // Check whether the two declarations might declare the same function.
  2818. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2819. return true;
  2820. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2821. } else {
  2822. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2823. << New->getDeclName();
  2824. notePreviousDefinition(OldD, New->getLocation());
  2825. return true;
  2826. }
  2827. }
  2828. // If the old declaration is invalid, just give up here.
  2829. if (Old->isInvalidDecl())
  2830. return true;
  2831. // Disallow redeclaration of some builtins.
  2832. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2833. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2834. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2835. << Old << Old->getType();
  2836. return true;
  2837. }
  2838. diag::kind PrevDiag;
  2839. SourceLocation OldLocation;
  2840. std::tie(PrevDiag, OldLocation) =
  2841. getNoteDiagForInvalidRedeclaration(Old, New);
  2842. // Don't complain about this if we're in GNU89 mode and the old function
  2843. // is an extern inline function.
  2844. // Don't complain about specializations. They are not supposed to have
  2845. // storage classes.
  2846. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2847. New->getStorageClass() == SC_Static &&
  2848. Old->hasExternalFormalLinkage() &&
  2849. !New->getTemplateSpecializationInfo() &&
  2850. !canRedefineFunction(Old, getLangOpts())) {
  2851. if (getLangOpts().MicrosoftExt) {
  2852. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2853. Diag(OldLocation, PrevDiag);
  2854. } else {
  2855. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2856. Diag(OldLocation, PrevDiag);
  2857. return true;
  2858. }
  2859. }
  2860. if (New->hasAttr<InternalLinkageAttr>() &&
  2861. !Old->hasAttr<InternalLinkageAttr>()) {
  2862. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2863. << New->getDeclName();
  2864. notePreviousDefinition(Old, New->getLocation());
  2865. New->dropAttr<InternalLinkageAttr>();
  2866. }
  2867. if (CheckRedeclarationModuleOwnership(New, Old))
  2868. return true;
  2869. if (!getLangOpts().CPlusPlus) {
  2870. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2871. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2872. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2873. << New << OldOvl;
  2874. // Try our best to find a decl that actually has the overloadable
  2875. // attribute for the note. In most cases (e.g. programs with only one
  2876. // broken declaration/definition), this won't matter.
  2877. //
  2878. // FIXME: We could do this if we juggled some extra state in
  2879. // OverloadableAttr, rather than just removing it.
  2880. const Decl *DiagOld = Old;
  2881. if (OldOvl) {
  2882. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2883. const auto *A = D->getAttr<OverloadableAttr>();
  2884. return A && !A->isImplicit();
  2885. });
  2886. // If we've implicitly added *all* of the overloadable attrs to this
  2887. // chain, emitting a "previous redecl" note is pointless.
  2888. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2889. }
  2890. if (DiagOld)
  2891. Diag(DiagOld->getLocation(),
  2892. diag::note_attribute_overloadable_prev_overload)
  2893. << OldOvl;
  2894. if (OldOvl)
  2895. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2896. else
  2897. New->dropAttr<OverloadableAttr>();
  2898. }
  2899. }
  2900. // If a function is first declared with a calling convention, but is later
  2901. // declared or defined without one, all following decls assume the calling
  2902. // convention of the first.
  2903. //
  2904. // It's OK if a function is first declared without a calling convention,
  2905. // but is later declared or defined with the default calling convention.
  2906. //
  2907. // To test if either decl has an explicit calling convention, we look for
  2908. // AttributedType sugar nodes on the type as written. If they are missing or
  2909. // were canonicalized away, we assume the calling convention was implicit.
  2910. //
  2911. // Note also that we DO NOT return at this point, because we still have
  2912. // other tests to run.
  2913. QualType OldQType = Context.getCanonicalType(Old->getType());
  2914. QualType NewQType = Context.getCanonicalType(New->getType());
  2915. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2916. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2917. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2918. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2919. bool RequiresAdjustment = false;
  2920. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2921. FunctionDecl *First = Old->getFirstDecl();
  2922. const FunctionType *FT =
  2923. First->getType().getCanonicalType()->castAs<FunctionType>();
  2924. FunctionType::ExtInfo FI = FT->getExtInfo();
  2925. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2926. if (!NewCCExplicit) {
  2927. // Inherit the CC from the previous declaration if it was specified
  2928. // there but not here.
  2929. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2930. RequiresAdjustment = true;
  2931. } else if (New->getBuiltinID()) {
  2932. // Calling Conventions on a Builtin aren't really useful and setting a
  2933. // default calling convention and cdecl'ing some builtin redeclarations is
  2934. // common, so warn and ignore the calling convention on the redeclaration.
  2935. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  2936. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2937. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  2938. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2939. RequiresAdjustment = true;
  2940. } else {
  2941. // Calling conventions aren't compatible, so complain.
  2942. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2943. Diag(New->getLocation(), diag::err_cconv_change)
  2944. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2945. << !FirstCCExplicit
  2946. << (!FirstCCExplicit ? "" :
  2947. FunctionType::getNameForCallConv(FI.getCC()));
  2948. // Put the note on the first decl, since it is the one that matters.
  2949. Diag(First->getLocation(), diag::note_previous_declaration);
  2950. return true;
  2951. }
  2952. }
  2953. // FIXME: diagnose the other way around?
  2954. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2955. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2956. RequiresAdjustment = true;
  2957. }
  2958. // Merge regparm attribute.
  2959. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2960. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2961. if (NewTypeInfo.getHasRegParm()) {
  2962. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2963. << NewType->getRegParmType()
  2964. << OldType->getRegParmType();
  2965. Diag(OldLocation, diag::note_previous_declaration);
  2966. return true;
  2967. }
  2968. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2969. RequiresAdjustment = true;
  2970. }
  2971. // Merge ns_returns_retained attribute.
  2972. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2973. if (NewTypeInfo.getProducesResult()) {
  2974. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2975. << "'ns_returns_retained'";
  2976. Diag(OldLocation, diag::note_previous_declaration);
  2977. return true;
  2978. }
  2979. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2980. RequiresAdjustment = true;
  2981. }
  2982. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2983. NewTypeInfo.getNoCallerSavedRegs()) {
  2984. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2985. AnyX86NoCallerSavedRegistersAttr *Attr =
  2986. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2987. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2988. Diag(OldLocation, diag::note_previous_declaration);
  2989. return true;
  2990. }
  2991. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2992. RequiresAdjustment = true;
  2993. }
  2994. if (RequiresAdjustment) {
  2995. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2996. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2997. New->setType(QualType(AdjustedType, 0));
  2998. NewQType = Context.getCanonicalType(New->getType());
  2999. }
  3000. // If this redeclaration makes the function inline, we may need to add it to
  3001. // UndefinedButUsed.
  3002. if (!Old->isInlined() && New->isInlined() &&
  3003. !New->hasAttr<GNUInlineAttr>() &&
  3004. !getLangOpts().GNUInline &&
  3005. Old->isUsed(false) &&
  3006. !Old->isDefined() && !New->isThisDeclarationADefinition())
  3007. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3008. SourceLocation()));
  3009. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  3010. // about it.
  3011. if (New->hasAttr<GNUInlineAttr>() &&
  3012. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  3013. UndefinedButUsed.erase(Old->getCanonicalDecl());
  3014. }
  3015. // If pass_object_size params don't match up perfectly, this isn't a valid
  3016. // redeclaration.
  3017. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  3018. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  3019. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  3020. << New->getDeclName();
  3021. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3022. return true;
  3023. }
  3024. if (getLangOpts().CPlusPlus) {
  3025. // C++1z [over.load]p2
  3026. // Certain function declarations cannot be overloaded:
  3027. // -- Function declarations that differ only in the return type,
  3028. // the exception specification, or both cannot be overloaded.
  3029. // Check the exception specifications match. This may recompute the type of
  3030. // both Old and New if it resolved exception specifications, so grab the
  3031. // types again after this. Because this updates the type, we do this before
  3032. // any of the other checks below, which may update the "de facto" NewQType
  3033. // but do not necessarily update the type of New.
  3034. if (CheckEquivalentExceptionSpec(Old, New))
  3035. return true;
  3036. OldQType = Context.getCanonicalType(Old->getType());
  3037. NewQType = Context.getCanonicalType(New->getType());
  3038. // Go back to the type source info to compare the declared return types,
  3039. // per C++1y [dcl.type.auto]p13:
  3040. // Redeclarations or specializations of a function or function template
  3041. // with a declared return type that uses a placeholder type shall also
  3042. // use that placeholder, not a deduced type.
  3043. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  3044. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3045. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3046. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3047. OldDeclaredReturnType)) {
  3048. QualType ResQT;
  3049. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3050. OldDeclaredReturnType->isObjCObjectPointerType())
  3051. // FIXME: This does the wrong thing for a deduced return type.
  3052. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3053. if (ResQT.isNull()) {
  3054. if (New->isCXXClassMember() && New->isOutOfLine())
  3055. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3056. << New << New->getReturnTypeSourceRange();
  3057. else
  3058. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3059. << New->getReturnTypeSourceRange();
  3060. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3061. << Old->getReturnTypeSourceRange();
  3062. return true;
  3063. }
  3064. else
  3065. NewQType = ResQT;
  3066. }
  3067. QualType OldReturnType = OldType->getReturnType();
  3068. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3069. if (OldReturnType != NewReturnType) {
  3070. // If this function has a deduced return type and has already been
  3071. // defined, copy the deduced value from the old declaration.
  3072. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3073. if (OldAT && OldAT->isDeduced()) {
  3074. New->setType(
  3075. SubstAutoType(New->getType(),
  3076. OldAT->isDependentType() ? Context.DependentTy
  3077. : OldAT->getDeducedType()));
  3078. NewQType = Context.getCanonicalType(
  3079. SubstAutoType(NewQType,
  3080. OldAT->isDependentType() ? Context.DependentTy
  3081. : OldAT->getDeducedType()));
  3082. }
  3083. }
  3084. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3085. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3086. if (OldMethod && NewMethod) {
  3087. // Preserve triviality.
  3088. NewMethod->setTrivial(OldMethod->isTrivial());
  3089. // MSVC allows explicit template specialization at class scope:
  3090. // 2 CXXMethodDecls referring to the same function will be injected.
  3091. // We don't want a redeclaration error.
  3092. bool IsClassScopeExplicitSpecialization =
  3093. OldMethod->isFunctionTemplateSpecialization() &&
  3094. NewMethod->isFunctionTemplateSpecialization();
  3095. bool isFriend = NewMethod->getFriendObjectKind();
  3096. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3097. !IsClassScopeExplicitSpecialization) {
  3098. // -- Member function declarations with the same name and the
  3099. // same parameter types cannot be overloaded if any of them
  3100. // is a static member function declaration.
  3101. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3102. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3103. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3104. return true;
  3105. }
  3106. // C++ [class.mem]p1:
  3107. // [...] A member shall not be declared twice in the
  3108. // member-specification, except that a nested class or member
  3109. // class template can be declared and then later defined.
  3110. if (!inTemplateInstantiation()) {
  3111. unsigned NewDiag;
  3112. if (isa<CXXConstructorDecl>(OldMethod))
  3113. NewDiag = diag::err_constructor_redeclared;
  3114. else if (isa<CXXDestructorDecl>(NewMethod))
  3115. NewDiag = diag::err_destructor_redeclared;
  3116. else if (isa<CXXConversionDecl>(NewMethod))
  3117. NewDiag = diag::err_conv_function_redeclared;
  3118. else
  3119. NewDiag = diag::err_member_redeclared;
  3120. Diag(New->getLocation(), NewDiag);
  3121. } else {
  3122. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3123. << New << New->getType();
  3124. }
  3125. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3126. return true;
  3127. // Complain if this is an explicit declaration of a special
  3128. // member that was initially declared implicitly.
  3129. //
  3130. // As an exception, it's okay to befriend such methods in order
  3131. // to permit the implicit constructor/destructor/operator calls.
  3132. } else if (OldMethod->isImplicit()) {
  3133. if (isFriend) {
  3134. NewMethod->setImplicit();
  3135. } else {
  3136. Diag(NewMethod->getLocation(),
  3137. diag::err_definition_of_implicitly_declared_member)
  3138. << New << getSpecialMember(OldMethod);
  3139. return true;
  3140. }
  3141. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3142. Diag(NewMethod->getLocation(),
  3143. diag::err_definition_of_explicitly_defaulted_member)
  3144. << getSpecialMember(OldMethod);
  3145. return true;
  3146. }
  3147. }
  3148. // C++11 [dcl.attr.noreturn]p1:
  3149. // The first declaration of a function shall specify the noreturn
  3150. // attribute if any declaration of that function specifies the noreturn
  3151. // attribute.
  3152. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  3153. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  3154. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  3155. Diag(Old->getFirstDecl()->getLocation(),
  3156. diag::note_noreturn_missing_first_decl);
  3157. }
  3158. // C++11 [dcl.attr.depend]p2:
  3159. // The first declaration of a function shall specify the
  3160. // carries_dependency attribute for its declarator-id if any declaration
  3161. // of the function specifies the carries_dependency attribute.
  3162. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3163. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3164. Diag(CDA->getLocation(),
  3165. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3166. Diag(Old->getFirstDecl()->getLocation(),
  3167. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3168. }
  3169. // (C++98 8.3.5p3):
  3170. // All declarations for a function shall agree exactly in both the
  3171. // return type and the parameter-type-list.
  3172. // We also want to respect all the extended bits except noreturn.
  3173. // noreturn should now match unless the old type info didn't have it.
  3174. QualType OldQTypeForComparison = OldQType;
  3175. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3176. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3177. const FunctionType *OldTypeForComparison
  3178. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3179. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3180. assert(OldQTypeForComparison.isCanonical());
  3181. }
  3182. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3183. // As a special case, retain the language linkage from previous
  3184. // declarations of a friend function as an extension.
  3185. //
  3186. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3187. // and is useful because there's otherwise no way to specify language
  3188. // linkage within class scope.
  3189. //
  3190. // Check cautiously as the friend object kind isn't yet complete.
  3191. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3192. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3193. Diag(OldLocation, PrevDiag);
  3194. } else {
  3195. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3196. Diag(OldLocation, PrevDiag);
  3197. return true;
  3198. }
  3199. }
  3200. // If the function types are compatible, merge the declarations. Ignore the
  3201. // exception specifier because it was already checked above in
  3202. // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
  3203. // about incompatible types under -fms-compatibility.
  3204. if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
  3205. NewQType))
  3206. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3207. // If the types are imprecise (due to dependent constructs in friends or
  3208. // local extern declarations), it's OK if they differ. We'll check again
  3209. // during instantiation.
  3210. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3211. return false;
  3212. // Fall through for conflicting redeclarations and redefinitions.
  3213. }
  3214. // C: Function types need to be compatible, not identical. This handles
  3215. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3216. if (!getLangOpts().CPlusPlus &&
  3217. Context.typesAreCompatible(OldQType, NewQType)) {
  3218. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3219. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3220. const FunctionProtoType *OldProto = nullptr;
  3221. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3222. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3223. // The old declaration provided a function prototype, but the
  3224. // new declaration does not. Merge in the prototype.
  3225. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3226. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3227. NewQType =
  3228. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3229. OldProto->getExtProtoInfo());
  3230. New->setType(NewQType);
  3231. New->setHasInheritedPrototype();
  3232. // Synthesize parameters with the same types.
  3233. SmallVector<ParmVarDecl*, 16> Params;
  3234. for (const auto &ParamType : OldProto->param_types()) {
  3235. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3236. SourceLocation(), nullptr,
  3237. ParamType, /*TInfo=*/nullptr,
  3238. SC_None, nullptr);
  3239. Param->setScopeInfo(0, Params.size());
  3240. Param->setImplicit();
  3241. Params.push_back(Param);
  3242. }
  3243. New->setParams(Params);
  3244. }
  3245. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3246. }
  3247. // GNU C permits a K&R definition to follow a prototype declaration
  3248. // if the declared types of the parameters in the K&R definition
  3249. // match the types in the prototype declaration, even when the
  3250. // promoted types of the parameters from the K&R definition differ
  3251. // from the types in the prototype. GCC then keeps the types from
  3252. // the prototype.
  3253. //
  3254. // If a variadic prototype is followed by a non-variadic K&R definition,
  3255. // the K&R definition becomes variadic. This is sort of an edge case, but
  3256. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3257. // C99 6.9.1p8.
  3258. if (!getLangOpts().CPlusPlus &&
  3259. Old->hasPrototype() && !New->hasPrototype() &&
  3260. New->getType()->getAs<FunctionProtoType>() &&
  3261. Old->getNumParams() == New->getNumParams()) {
  3262. SmallVector<QualType, 16> ArgTypes;
  3263. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3264. const FunctionProtoType *OldProto
  3265. = Old->getType()->getAs<FunctionProtoType>();
  3266. const FunctionProtoType *NewProto
  3267. = New->getType()->getAs<FunctionProtoType>();
  3268. // Determine whether this is the GNU C extension.
  3269. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3270. NewProto->getReturnType());
  3271. bool LooseCompatible = !MergedReturn.isNull();
  3272. for (unsigned Idx = 0, End = Old->getNumParams();
  3273. LooseCompatible && Idx != End; ++Idx) {
  3274. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3275. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3276. if (Context.typesAreCompatible(OldParm->getType(),
  3277. NewProto->getParamType(Idx))) {
  3278. ArgTypes.push_back(NewParm->getType());
  3279. } else if (Context.typesAreCompatible(OldParm->getType(),
  3280. NewParm->getType(),
  3281. /*CompareUnqualified=*/true)) {
  3282. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3283. NewProto->getParamType(Idx) };
  3284. Warnings.push_back(Warn);
  3285. ArgTypes.push_back(NewParm->getType());
  3286. } else
  3287. LooseCompatible = false;
  3288. }
  3289. if (LooseCompatible) {
  3290. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3291. Diag(Warnings[Warn].NewParm->getLocation(),
  3292. diag::ext_param_promoted_not_compatible_with_prototype)
  3293. << Warnings[Warn].PromotedType
  3294. << Warnings[Warn].OldParm->getType();
  3295. if (Warnings[Warn].OldParm->getLocation().isValid())
  3296. Diag(Warnings[Warn].OldParm->getLocation(),
  3297. diag::note_previous_declaration);
  3298. }
  3299. if (MergeTypeWithOld)
  3300. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3301. OldProto->getExtProtoInfo()));
  3302. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3303. }
  3304. // Fall through to diagnose conflicting types.
  3305. }
  3306. // A function that has already been declared has been redeclared or
  3307. // defined with a different type; show an appropriate diagnostic.
  3308. // If the previous declaration was an implicitly-generated builtin
  3309. // declaration, then at the very least we should use a specialized note.
  3310. unsigned BuiltinID;
  3311. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3312. // If it's actually a library-defined builtin function like 'malloc'
  3313. // or 'printf', just warn about the incompatible redeclaration.
  3314. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3315. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3316. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3317. << Old << Old->getType();
  3318. // If this is a global redeclaration, just forget hereafter
  3319. // about the "builtin-ness" of the function.
  3320. //
  3321. // Doing this for local extern declarations is problematic. If
  3322. // the builtin declaration remains visible, a second invalid
  3323. // local declaration will produce a hard error; if it doesn't
  3324. // remain visible, a single bogus local redeclaration (which is
  3325. // actually only a warning) could break all the downstream code.
  3326. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3327. New->getIdentifier()->revertBuiltin();
  3328. return false;
  3329. }
  3330. PrevDiag = diag::note_previous_builtin_declaration;
  3331. }
  3332. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3333. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3334. return true;
  3335. }
  3336. /// Completes the merge of two function declarations that are
  3337. /// known to be compatible.
  3338. ///
  3339. /// This routine handles the merging of attributes and other
  3340. /// properties of function declarations from the old declaration to
  3341. /// the new declaration, once we know that New is in fact a
  3342. /// redeclaration of Old.
  3343. ///
  3344. /// \returns false
  3345. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3346. Scope *S, bool MergeTypeWithOld) {
  3347. // Merge the attributes
  3348. mergeDeclAttributes(New, Old);
  3349. // Merge "pure" flag.
  3350. if (Old->isPure())
  3351. New->setPure();
  3352. // Merge "used" flag.
  3353. if (Old->getMostRecentDecl()->isUsed(false))
  3354. New->setIsUsed();
  3355. // Merge attributes from the parameters. These can mismatch with K&R
  3356. // declarations.
  3357. if (New->getNumParams() == Old->getNumParams())
  3358. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3359. ParmVarDecl *NewParam = New->getParamDecl(i);
  3360. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3361. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3362. mergeParamDeclTypes(NewParam, OldParam, *this);
  3363. }
  3364. if (getLangOpts().CPlusPlus)
  3365. return MergeCXXFunctionDecl(New, Old, S);
  3366. // Merge the function types so the we get the composite types for the return
  3367. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3368. // was visible.
  3369. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3370. if (!Merged.isNull() && MergeTypeWithOld)
  3371. New->setType(Merged);
  3372. return false;
  3373. }
  3374. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3375. ObjCMethodDecl *oldMethod) {
  3376. // Merge the attributes, including deprecated/unavailable
  3377. AvailabilityMergeKind MergeKind =
  3378. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3379. ? AMK_ProtocolImplementation
  3380. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3381. : AMK_Override;
  3382. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3383. // Merge attributes from the parameters.
  3384. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3385. oe = oldMethod->param_end();
  3386. for (ObjCMethodDecl::param_iterator
  3387. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3388. ni != ne && oi != oe; ++ni, ++oi)
  3389. mergeParamDeclAttributes(*ni, *oi, *this);
  3390. CheckObjCMethodOverride(newMethod, oldMethod);
  3391. }
  3392. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3393. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3394. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3395. ? diag::err_redefinition_different_type
  3396. : diag::err_redeclaration_different_type)
  3397. << New->getDeclName() << New->getType() << Old->getType();
  3398. diag::kind PrevDiag;
  3399. SourceLocation OldLocation;
  3400. std::tie(PrevDiag, OldLocation)
  3401. = getNoteDiagForInvalidRedeclaration(Old, New);
  3402. S.Diag(OldLocation, PrevDiag);
  3403. New->setInvalidDecl();
  3404. }
  3405. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3406. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3407. /// emitting diagnostics as appropriate.
  3408. ///
  3409. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3410. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3411. /// is attached.
  3412. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3413. bool MergeTypeWithOld) {
  3414. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3415. return;
  3416. QualType MergedT;
  3417. if (getLangOpts().CPlusPlus) {
  3418. if (New->getType()->isUndeducedType()) {
  3419. // We don't know what the new type is until the initializer is attached.
  3420. return;
  3421. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3422. // These could still be something that needs exception specs checked.
  3423. return MergeVarDeclExceptionSpecs(New, Old);
  3424. }
  3425. // C++ [basic.link]p10:
  3426. // [...] the types specified by all declarations referring to a given
  3427. // object or function shall be identical, except that declarations for an
  3428. // array object can specify array types that differ by the presence or
  3429. // absence of a major array bound (8.3.4).
  3430. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3431. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3432. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3433. // We are merging a variable declaration New into Old. If it has an array
  3434. // bound, and that bound differs from Old's bound, we should diagnose the
  3435. // mismatch.
  3436. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3437. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3438. PrevVD = PrevVD->getPreviousDecl()) {
  3439. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3440. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3441. continue;
  3442. if (!Context.hasSameType(NewArray, PrevVDTy))
  3443. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3444. }
  3445. }
  3446. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3447. if (Context.hasSameType(OldArray->getElementType(),
  3448. NewArray->getElementType()))
  3449. MergedT = New->getType();
  3450. }
  3451. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3452. // has no array bound, it should not inherit one from Old, if Old is not
  3453. // visible.
  3454. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3455. if (Context.hasSameType(OldArray->getElementType(),
  3456. NewArray->getElementType()))
  3457. MergedT = Old->getType();
  3458. }
  3459. }
  3460. else if (New->getType()->isObjCObjectPointerType() &&
  3461. Old->getType()->isObjCObjectPointerType()) {
  3462. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3463. Old->getType());
  3464. }
  3465. } else {
  3466. // C 6.2.7p2:
  3467. // All declarations that refer to the same object or function shall have
  3468. // compatible type.
  3469. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3470. }
  3471. if (MergedT.isNull()) {
  3472. // It's OK if we couldn't merge types if either type is dependent, for a
  3473. // block-scope variable. In other cases (static data members of class
  3474. // templates, variable templates, ...), we require the types to be
  3475. // equivalent.
  3476. // FIXME: The C++ standard doesn't say anything about this.
  3477. if ((New->getType()->isDependentType() ||
  3478. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3479. // If the old type was dependent, we can't merge with it, so the new type
  3480. // becomes dependent for now. We'll reproduce the original type when we
  3481. // instantiate the TypeSourceInfo for the variable.
  3482. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3483. New->setType(Context.DependentTy);
  3484. return;
  3485. }
  3486. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3487. }
  3488. // Don't actually update the type on the new declaration if the old
  3489. // declaration was an extern declaration in a different scope.
  3490. if (MergeTypeWithOld)
  3491. New->setType(MergedT);
  3492. }
  3493. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3494. LookupResult &Previous) {
  3495. // C11 6.2.7p4:
  3496. // For an identifier with internal or external linkage declared
  3497. // in a scope in which a prior declaration of that identifier is
  3498. // visible, if the prior declaration specifies internal or
  3499. // external linkage, the type of the identifier at the later
  3500. // declaration becomes the composite type.
  3501. //
  3502. // If the variable isn't visible, we do not merge with its type.
  3503. if (Previous.isShadowed())
  3504. return false;
  3505. if (S.getLangOpts().CPlusPlus) {
  3506. // C++11 [dcl.array]p3:
  3507. // If there is a preceding declaration of the entity in the same
  3508. // scope in which the bound was specified, an omitted array bound
  3509. // is taken to be the same as in that earlier declaration.
  3510. return NewVD->isPreviousDeclInSameBlockScope() ||
  3511. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3512. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3513. } else {
  3514. // If the old declaration was function-local, don't merge with its
  3515. // type unless we're in the same function.
  3516. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3517. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3518. }
  3519. }
  3520. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3521. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3522. /// situation, merging decls or emitting diagnostics as appropriate.
  3523. ///
  3524. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3525. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3526. /// definitions here, since the initializer hasn't been attached.
  3527. ///
  3528. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3529. // If the new decl is already invalid, don't do any other checking.
  3530. if (New->isInvalidDecl())
  3531. return;
  3532. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3533. return;
  3534. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3535. // Verify the old decl was also a variable or variable template.
  3536. VarDecl *Old = nullptr;
  3537. VarTemplateDecl *OldTemplate = nullptr;
  3538. if (Previous.isSingleResult()) {
  3539. if (NewTemplate) {
  3540. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3541. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3542. if (auto *Shadow =
  3543. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3544. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3545. return New->setInvalidDecl();
  3546. } else {
  3547. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3548. if (auto *Shadow =
  3549. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3550. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3551. return New->setInvalidDecl();
  3552. }
  3553. }
  3554. if (!Old) {
  3555. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3556. << New->getDeclName();
  3557. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3558. New->getLocation());
  3559. return New->setInvalidDecl();
  3560. }
  3561. // Ensure the template parameters are compatible.
  3562. if (NewTemplate &&
  3563. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3564. OldTemplate->getTemplateParameters(),
  3565. /*Complain=*/true, TPL_TemplateMatch))
  3566. return New->setInvalidDecl();
  3567. // C++ [class.mem]p1:
  3568. // A member shall not be declared twice in the member-specification [...]
  3569. //
  3570. // Here, we need only consider static data members.
  3571. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3572. Diag(New->getLocation(), diag::err_duplicate_member)
  3573. << New->getIdentifier();
  3574. Diag(Old->getLocation(), diag::note_previous_declaration);
  3575. New->setInvalidDecl();
  3576. }
  3577. mergeDeclAttributes(New, Old);
  3578. // Warn if an already-declared variable is made a weak_import in a subsequent
  3579. // declaration
  3580. if (New->hasAttr<WeakImportAttr>() &&
  3581. Old->getStorageClass() == SC_None &&
  3582. !Old->hasAttr<WeakImportAttr>()) {
  3583. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3584. notePreviousDefinition(Old, New->getLocation());
  3585. // Remove weak_import attribute on new declaration.
  3586. New->dropAttr<WeakImportAttr>();
  3587. }
  3588. if (New->hasAttr<InternalLinkageAttr>() &&
  3589. !Old->hasAttr<InternalLinkageAttr>()) {
  3590. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3591. << New->getDeclName();
  3592. notePreviousDefinition(Old, New->getLocation());
  3593. New->dropAttr<InternalLinkageAttr>();
  3594. }
  3595. // Merge the types.
  3596. VarDecl *MostRecent = Old->getMostRecentDecl();
  3597. if (MostRecent != Old) {
  3598. MergeVarDeclTypes(New, MostRecent,
  3599. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3600. if (New->isInvalidDecl())
  3601. return;
  3602. }
  3603. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3604. if (New->isInvalidDecl())
  3605. return;
  3606. diag::kind PrevDiag;
  3607. SourceLocation OldLocation;
  3608. std::tie(PrevDiag, OldLocation) =
  3609. getNoteDiagForInvalidRedeclaration(Old, New);
  3610. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3611. if (New->getStorageClass() == SC_Static &&
  3612. !New->isStaticDataMember() &&
  3613. Old->hasExternalFormalLinkage()) {
  3614. if (getLangOpts().MicrosoftExt) {
  3615. Diag(New->getLocation(), diag::ext_static_non_static)
  3616. << New->getDeclName();
  3617. Diag(OldLocation, PrevDiag);
  3618. } else {
  3619. Diag(New->getLocation(), diag::err_static_non_static)
  3620. << New->getDeclName();
  3621. Diag(OldLocation, PrevDiag);
  3622. return New->setInvalidDecl();
  3623. }
  3624. }
  3625. // C99 6.2.2p4:
  3626. // For an identifier declared with the storage-class specifier
  3627. // extern in a scope in which a prior declaration of that
  3628. // identifier is visible,23) if the prior declaration specifies
  3629. // internal or external linkage, the linkage of the identifier at
  3630. // the later declaration is the same as the linkage specified at
  3631. // the prior declaration. If no prior declaration is visible, or
  3632. // if the prior declaration specifies no linkage, then the
  3633. // identifier has external linkage.
  3634. if (New->hasExternalStorage() && Old->hasLinkage())
  3635. /* Okay */;
  3636. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3637. !New->isStaticDataMember() &&
  3638. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3639. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3640. Diag(OldLocation, PrevDiag);
  3641. return New->setInvalidDecl();
  3642. }
  3643. // Check if extern is followed by non-extern and vice-versa.
  3644. if (New->hasExternalStorage() &&
  3645. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3646. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3647. Diag(OldLocation, PrevDiag);
  3648. return New->setInvalidDecl();
  3649. }
  3650. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3651. !New->hasExternalStorage()) {
  3652. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3653. Diag(OldLocation, PrevDiag);
  3654. return New->setInvalidDecl();
  3655. }
  3656. if (CheckRedeclarationModuleOwnership(New, Old))
  3657. return;
  3658. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3659. // FIXME: The test for external storage here seems wrong? We still
  3660. // need to check for mismatches.
  3661. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3662. // Don't complain about out-of-line definitions of static members.
  3663. !(Old->getLexicalDeclContext()->isRecord() &&
  3664. !New->getLexicalDeclContext()->isRecord())) {
  3665. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3666. Diag(OldLocation, PrevDiag);
  3667. return New->setInvalidDecl();
  3668. }
  3669. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3670. if (VarDecl *Def = Old->getDefinition()) {
  3671. // C++1z [dcl.fcn.spec]p4:
  3672. // If the definition of a variable appears in a translation unit before
  3673. // its first declaration as inline, the program is ill-formed.
  3674. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3675. Diag(Def->getLocation(), diag::note_previous_definition);
  3676. }
  3677. }
  3678. // If this redeclaration makes the variable inline, we may need to add it to
  3679. // UndefinedButUsed.
  3680. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3681. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3682. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3683. SourceLocation()));
  3684. if (New->getTLSKind() != Old->getTLSKind()) {
  3685. if (!Old->getTLSKind()) {
  3686. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3687. Diag(OldLocation, PrevDiag);
  3688. } else if (!New->getTLSKind()) {
  3689. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3690. Diag(OldLocation, PrevDiag);
  3691. } else {
  3692. // Do not allow redeclaration to change the variable between requiring
  3693. // static and dynamic initialization.
  3694. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3695. // declaration to determine the kind. Do we need to be compatible here?
  3696. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3697. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3698. Diag(OldLocation, PrevDiag);
  3699. }
  3700. }
  3701. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3702. if (getLangOpts().CPlusPlus &&
  3703. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3704. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3705. Old->getCanonicalDecl()->isConstexpr()) {
  3706. // This definition won't be a definition any more once it's been merged.
  3707. Diag(New->getLocation(),
  3708. diag::warn_deprecated_redundant_constexpr_static_def);
  3709. } else if (VarDecl *Def = Old->getDefinition()) {
  3710. if (checkVarDeclRedefinition(Def, New))
  3711. return;
  3712. }
  3713. }
  3714. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3715. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3716. Diag(OldLocation, PrevDiag);
  3717. New->setInvalidDecl();
  3718. return;
  3719. }
  3720. // Merge "used" flag.
  3721. if (Old->getMostRecentDecl()->isUsed(false))
  3722. New->setIsUsed();
  3723. // Keep a chain of previous declarations.
  3724. New->setPreviousDecl(Old);
  3725. if (NewTemplate)
  3726. NewTemplate->setPreviousDecl(OldTemplate);
  3727. adjustDeclContextForDeclaratorDecl(New, Old);
  3728. // Inherit access appropriately.
  3729. New->setAccess(Old->getAccess());
  3730. if (NewTemplate)
  3731. NewTemplate->setAccess(New->getAccess());
  3732. if (Old->isInline())
  3733. New->setImplicitlyInline();
  3734. }
  3735. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3736. SourceManager &SrcMgr = getSourceManager();
  3737. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3738. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3739. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3740. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3741. auto &HSI = PP.getHeaderSearchInfo();
  3742. StringRef HdrFilename =
  3743. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3744. auto noteFromModuleOrInclude = [&](Module *Mod,
  3745. SourceLocation IncLoc) -> bool {
  3746. // Redefinition errors with modules are common with non modular mapped
  3747. // headers, example: a non-modular header H in module A that also gets
  3748. // included directly in a TU. Pointing twice to the same header/definition
  3749. // is confusing, try to get better diagnostics when modules is on.
  3750. if (IncLoc.isValid()) {
  3751. if (Mod) {
  3752. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3753. << HdrFilename.str() << Mod->getFullModuleName();
  3754. if (!Mod->DefinitionLoc.isInvalid())
  3755. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3756. << Mod->getFullModuleName();
  3757. } else {
  3758. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3759. << HdrFilename.str();
  3760. }
  3761. return true;
  3762. }
  3763. return false;
  3764. };
  3765. // Is it the same file and same offset? Provide more information on why
  3766. // this leads to a redefinition error.
  3767. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3768. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3769. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3770. bool EmittedDiag =
  3771. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3772. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3773. // If the header has no guards, emit a note suggesting one.
  3774. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3775. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3776. if (EmittedDiag)
  3777. return;
  3778. }
  3779. // Redefinition coming from different files or couldn't do better above.
  3780. if (Old->getLocation().isValid())
  3781. Diag(Old->getLocation(), diag::note_previous_definition);
  3782. }
  3783. /// We've just determined that \p Old and \p New both appear to be definitions
  3784. /// of the same variable. Either diagnose or fix the problem.
  3785. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3786. if (!hasVisibleDefinition(Old) &&
  3787. (New->getFormalLinkage() == InternalLinkage ||
  3788. New->isInline() ||
  3789. New->getDescribedVarTemplate() ||
  3790. New->getNumTemplateParameterLists() ||
  3791. New->getDeclContext()->isDependentContext())) {
  3792. // The previous definition is hidden, and multiple definitions are
  3793. // permitted (in separate TUs). Demote this to a declaration.
  3794. New->demoteThisDefinitionToDeclaration();
  3795. // Make the canonical definition visible.
  3796. if (auto *OldTD = Old->getDescribedVarTemplate())
  3797. makeMergedDefinitionVisible(OldTD);
  3798. makeMergedDefinitionVisible(Old);
  3799. return false;
  3800. } else {
  3801. Diag(New->getLocation(), diag::err_redefinition) << New;
  3802. notePreviousDefinition(Old, New->getLocation());
  3803. New->setInvalidDecl();
  3804. return true;
  3805. }
  3806. }
  3807. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3808. /// no declarator (e.g. "struct foo;") is parsed.
  3809. Decl *
  3810. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3811. RecordDecl *&AnonRecord) {
  3812. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3813. AnonRecord);
  3814. }
  3815. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3816. // disambiguate entities defined in different scopes.
  3817. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3818. // compatibility.
  3819. // We will pick our mangling number depending on which version of MSVC is being
  3820. // targeted.
  3821. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3822. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3823. ? S->getMSCurManglingNumber()
  3824. : S->getMSLastManglingNumber();
  3825. }
  3826. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3827. if (!Context.getLangOpts().CPlusPlus)
  3828. return;
  3829. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3830. // If this tag is the direct child of a class, number it if
  3831. // it is anonymous.
  3832. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3833. return;
  3834. MangleNumberingContext &MCtx =
  3835. Context.getManglingNumberContext(Tag->getParent());
  3836. Context.setManglingNumber(
  3837. Tag, MCtx.getManglingNumber(
  3838. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3839. return;
  3840. }
  3841. // If this tag isn't a direct child of a class, number it if it is local.
  3842. MangleNumberingContext *MCtx;
  3843. Decl *ManglingContextDecl;
  3844. std::tie(MCtx, ManglingContextDecl) =
  3845. getCurrentMangleNumberContext(Tag->getDeclContext());
  3846. if (MCtx) {
  3847. Context.setManglingNumber(
  3848. Tag, MCtx->getManglingNumber(
  3849. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3850. }
  3851. }
  3852. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3853. TypedefNameDecl *NewTD) {
  3854. if (TagFromDeclSpec->isInvalidDecl())
  3855. return;
  3856. // Do nothing if the tag already has a name for linkage purposes.
  3857. if (TagFromDeclSpec->hasNameForLinkage())
  3858. return;
  3859. // A well-formed anonymous tag must always be a TUK_Definition.
  3860. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3861. // The type must match the tag exactly; no qualifiers allowed.
  3862. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3863. Context.getTagDeclType(TagFromDeclSpec))) {
  3864. if (getLangOpts().CPlusPlus)
  3865. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3866. return;
  3867. }
  3868. // If we've already computed linkage for the anonymous tag, then
  3869. // adding a typedef name for the anonymous decl can change that
  3870. // linkage, which might be a serious problem. Diagnose this as
  3871. // unsupported and ignore the typedef name. TODO: we should
  3872. // pursue this as a language defect and establish a formal rule
  3873. // for how to handle it.
  3874. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3875. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3876. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3877. tagLoc = getLocForEndOfToken(tagLoc);
  3878. llvm::SmallString<40> textToInsert;
  3879. textToInsert += ' ';
  3880. textToInsert += NewTD->getIdentifier()->getName();
  3881. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3882. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3883. return;
  3884. }
  3885. // Otherwise, set this is the anon-decl typedef for the tag.
  3886. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3887. }
  3888. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3889. switch (T) {
  3890. case DeclSpec::TST_class:
  3891. return 0;
  3892. case DeclSpec::TST_struct:
  3893. return 1;
  3894. case DeclSpec::TST_interface:
  3895. return 2;
  3896. case DeclSpec::TST_union:
  3897. return 3;
  3898. case DeclSpec::TST_enum:
  3899. return 4;
  3900. default:
  3901. llvm_unreachable("unexpected type specifier");
  3902. }
  3903. }
  3904. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3905. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3906. /// parameters to cope with template friend declarations.
  3907. Decl *
  3908. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3909. MultiTemplateParamsArg TemplateParams,
  3910. bool IsExplicitInstantiation,
  3911. RecordDecl *&AnonRecord) {
  3912. Decl *TagD = nullptr;
  3913. TagDecl *Tag = nullptr;
  3914. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3915. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3916. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3917. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3918. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3919. TagD = DS.getRepAsDecl();
  3920. if (!TagD) // We probably had an error
  3921. return nullptr;
  3922. // Note that the above type specs guarantee that the
  3923. // type rep is a Decl, whereas in many of the others
  3924. // it's a Type.
  3925. if (isa<TagDecl>(TagD))
  3926. Tag = cast<TagDecl>(TagD);
  3927. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3928. Tag = CTD->getTemplatedDecl();
  3929. }
  3930. if (Tag) {
  3931. handleTagNumbering(Tag, S);
  3932. Tag->setFreeStanding();
  3933. if (Tag->isInvalidDecl())
  3934. return Tag;
  3935. }
  3936. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3937. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3938. // or incomplete types shall not be restrict-qualified."
  3939. if (TypeQuals & DeclSpec::TQ_restrict)
  3940. Diag(DS.getRestrictSpecLoc(),
  3941. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3942. << DS.getSourceRange();
  3943. }
  3944. if (DS.isInlineSpecified())
  3945. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3946. << getLangOpts().CPlusPlus17;
  3947. if (DS.hasConstexprSpecifier()) {
  3948. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3949. // and definitions of functions and variables.
  3950. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  3951. // the declaration of a function or function template
  3952. if (Tag)
  3953. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3954. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  3955. << DS.getConstexprSpecifier();
  3956. else
  3957. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  3958. << DS.getConstexprSpecifier();
  3959. // Don't emit warnings after this error.
  3960. return TagD;
  3961. }
  3962. DiagnoseFunctionSpecifiers(DS);
  3963. if (DS.isFriendSpecified()) {
  3964. // If we're dealing with a decl but not a TagDecl, assume that
  3965. // whatever routines created it handled the friendship aspect.
  3966. if (TagD && !Tag)
  3967. return nullptr;
  3968. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3969. }
  3970. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3971. bool IsExplicitSpecialization =
  3972. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3973. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3974. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3975. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3976. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3977. // nested-name-specifier unless it is an explicit instantiation
  3978. // or an explicit specialization.
  3979. //
  3980. // FIXME: We allow class template partial specializations here too, per the
  3981. // obvious intent of DR1819.
  3982. //
  3983. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3984. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3985. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3986. return nullptr;
  3987. }
  3988. // Track whether this decl-specifier declares anything.
  3989. bool DeclaresAnything = true;
  3990. // Handle anonymous struct definitions.
  3991. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3992. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3993. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3994. if (getLangOpts().CPlusPlus ||
  3995. Record->getDeclContext()->isRecord()) {
  3996. // If CurContext is a DeclContext that can contain statements,
  3997. // RecursiveASTVisitor won't visit the decls that
  3998. // BuildAnonymousStructOrUnion() will put into CurContext.
  3999. // Also store them here so that they can be part of the
  4000. // DeclStmt that gets created in this case.
  4001. // FIXME: Also return the IndirectFieldDecls created by
  4002. // BuildAnonymousStructOr union, for the same reason?
  4003. if (CurContext->isFunctionOrMethod())
  4004. AnonRecord = Record;
  4005. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  4006. Context.getPrintingPolicy());
  4007. }
  4008. DeclaresAnything = false;
  4009. }
  4010. }
  4011. // C11 6.7.2.1p2:
  4012. // A struct-declaration that does not declare an anonymous structure or
  4013. // anonymous union shall contain a struct-declarator-list.
  4014. //
  4015. // This rule also existed in C89 and C99; the grammar for struct-declaration
  4016. // did not permit a struct-declaration without a struct-declarator-list.
  4017. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  4018. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  4019. // Check for Microsoft C extension: anonymous struct/union member.
  4020. // Handle 2 kinds of anonymous struct/union:
  4021. // struct STRUCT;
  4022. // union UNION;
  4023. // and
  4024. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  4025. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  4026. if ((Tag && Tag->getDeclName()) ||
  4027. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  4028. RecordDecl *Record = nullptr;
  4029. if (Tag)
  4030. Record = dyn_cast<RecordDecl>(Tag);
  4031. else if (const RecordType *RT =
  4032. DS.getRepAsType().get()->getAsStructureType())
  4033. Record = RT->getDecl();
  4034. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  4035. Record = UT->getDecl();
  4036. if (Record && getLangOpts().MicrosoftExt) {
  4037. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  4038. << Record->isUnion() << DS.getSourceRange();
  4039. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  4040. }
  4041. DeclaresAnything = false;
  4042. }
  4043. }
  4044. // Skip all the checks below if we have a type error.
  4045. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  4046. (TagD && TagD->isInvalidDecl()))
  4047. return TagD;
  4048. if (getLangOpts().CPlusPlus &&
  4049. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  4050. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4051. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4052. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4053. DeclaresAnything = false;
  4054. if (!DS.isMissingDeclaratorOk()) {
  4055. // Customize diagnostic for a typedef missing a name.
  4056. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4057. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4058. << DS.getSourceRange();
  4059. else
  4060. DeclaresAnything = false;
  4061. }
  4062. if (DS.isModulePrivateSpecified() &&
  4063. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4064. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4065. << Tag->getTagKind()
  4066. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4067. ActOnDocumentableDecl(TagD);
  4068. // C 6.7/2:
  4069. // A declaration [...] shall declare at least a declarator [...], a tag,
  4070. // or the members of an enumeration.
  4071. // C++ [dcl.dcl]p3:
  4072. // [If there are no declarators], and except for the declaration of an
  4073. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4074. // names into the program, or shall redeclare a name introduced by a
  4075. // previous declaration.
  4076. if (!DeclaresAnything) {
  4077. // In C, we allow this as a (popular) extension / bug. Don't bother
  4078. // producing further diagnostics for redundant qualifiers after this.
  4079. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4080. return TagD;
  4081. }
  4082. // C++ [dcl.stc]p1:
  4083. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4084. // init-declarator-list of the declaration shall not be empty.
  4085. // C++ [dcl.fct.spec]p1:
  4086. // If a cv-qualifier appears in a decl-specifier-seq, the
  4087. // init-declarator-list of the declaration shall not be empty.
  4088. //
  4089. // Spurious qualifiers here appear to be valid in C.
  4090. unsigned DiagID = diag::warn_standalone_specifier;
  4091. if (getLangOpts().CPlusPlus)
  4092. DiagID = diag::ext_standalone_specifier;
  4093. // Note that a linkage-specification sets a storage class, but
  4094. // 'extern "C" struct foo;' is actually valid and not theoretically
  4095. // useless.
  4096. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4097. if (SCS == DeclSpec::SCS_mutable)
  4098. // Since mutable is not a viable storage class specifier in C, there is
  4099. // no reason to treat it as an extension. Instead, diagnose as an error.
  4100. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4101. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4102. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4103. << DeclSpec::getSpecifierName(SCS);
  4104. }
  4105. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4106. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4107. << DeclSpec::getSpecifierName(TSCS);
  4108. if (DS.getTypeQualifiers()) {
  4109. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4110. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4111. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4112. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4113. // Restrict is covered above.
  4114. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4115. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4116. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4117. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4118. }
  4119. // Warn about ignored type attributes, for example:
  4120. // __attribute__((aligned)) struct A;
  4121. // Attributes should be placed after tag to apply to type declaration.
  4122. if (!DS.getAttributes().empty()) {
  4123. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4124. if (TypeSpecType == DeclSpec::TST_class ||
  4125. TypeSpecType == DeclSpec::TST_struct ||
  4126. TypeSpecType == DeclSpec::TST_interface ||
  4127. TypeSpecType == DeclSpec::TST_union ||
  4128. TypeSpecType == DeclSpec::TST_enum) {
  4129. for (const ParsedAttr &AL : DS.getAttributes())
  4130. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4131. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4132. }
  4133. }
  4134. return TagD;
  4135. }
  4136. /// We are trying to inject an anonymous member into the given scope;
  4137. /// check if there's an existing declaration that can't be overloaded.
  4138. ///
  4139. /// \return true if this is a forbidden redeclaration
  4140. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4141. Scope *S,
  4142. DeclContext *Owner,
  4143. DeclarationName Name,
  4144. SourceLocation NameLoc,
  4145. bool IsUnion) {
  4146. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4147. Sema::ForVisibleRedeclaration);
  4148. if (!SemaRef.LookupName(R, S)) return false;
  4149. // Pick a representative declaration.
  4150. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4151. assert(PrevDecl && "Expected a non-null Decl");
  4152. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4153. return false;
  4154. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4155. << IsUnion << Name;
  4156. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4157. return true;
  4158. }
  4159. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4160. /// anonymous struct or union AnonRecord into the owning context Owner
  4161. /// and scope S. This routine will be invoked just after we realize
  4162. /// that an unnamed union or struct is actually an anonymous union or
  4163. /// struct, e.g.,
  4164. ///
  4165. /// @code
  4166. /// union {
  4167. /// int i;
  4168. /// float f;
  4169. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4170. /// // f into the surrounding scope.x
  4171. /// @endcode
  4172. ///
  4173. /// This routine is recursive, injecting the names of nested anonymous
  4174. /// structs/unions into the owning context and scope as well.
  4175. static bool
  4176. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4177. RecordDecl *AnonRecord, AccessSpecifier AS,
  4178. SmallVectorImpl<NamedDecl *> &Chaining) {
  4179. bool Invalid = false;
  4180. // Look every FieldDecl and IndirectFieldDecl with a name.
  4181. for (auto *D : AnonRecord->decls()) {
  4182. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4183. cast<NamedDecl>(D)->getDeclName()) {
  4184. ValueDecl *VD = cast<ValueDecl>(D);
  4185. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4186. VD->getLocation(),
  4187. AnonRecord->isUnion())) {
  4188. // C++ [class.union]p2:
  4189. // The names of the members of an anonymous union shall be
  4190. // distinct from the names of any other entity in the
  4191. // scope in which the anonymous union is declared.
  4192. Invalid = true;
  4193. } else {
  4194. // C++ [class.union]p2:
  4195. // For the purpose of name lookup, after the anonymous union
  4196. // definition, the members of the anonymous union are
  4197. // considered to have been defined in the scope in which the
  4198. // anonymous union is declared.
  4199. unsigned OldChainingSize = Chaining.size();
  4200. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4201. Chaining.append(IF->chain_begin(), IF->chain_end());
  4202. else
  4203. Chaining.push_back(VD);
  4204. assert(Chaining.size() >= 2);
  4205. NamedDecl **NamedChain =
  4206. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4207. for (unsigned i = 0; i < Chaining.size(); i++)
  4208. NamedChain[i] = Chaining[i];
  4209. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4210. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4211. VD->getType(), {NamedChain, Chaining.size()});
  4212. for (const auto *Attr : VD->attrs())
  4213. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4214. IndirectField->setAccess(AS);
  4215. IndirectField->setImplicit();
  4216. SemaRef.PushOnScopeChains(IndirectField, S);
  4217. // That includes picking up the appropriate access specifier.
  4218. if (AS != AS_none) IndirectField->setAccess(AS);
  4219. Chaining.resize(OldChainingSize);
  4220. }
  4221. }
  4222. }
  4223. return Invalid;
  4224. }
  4225. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4226. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4227. /// illegal input values are mapped to SC_None.
  4228. static StorageClass
  4229. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4230. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4231. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4232. "Parser allowed 'typedef' as storage class VarDecl.");
  4233. switch (StorageClassSpec) {
  4234. case DeclSpec::SCS_unspecified: return SC_None;
  4235. case DeclSpec::SCS_extern:
  4236. if (DS.isExternInLinkageSpec())
  4237. return SC_None;
  4238. return SC_Extern;
  4239. case DeclSpec::SCS_static: return SC_Static;
  4240. case DeclSpec::SCS_auto: return SC_Auto;
  4241. case DeclSpec::SCS_register: return SC_Register;
  4242. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4243. // Illegal SCSs map to None: error reporting is up to the caller.
  4244. case DeclSpec::SCS_mutable: // Fall through.
  4245. case DeclSpec::SCS_typedef: return SC_None;
  4246. }
  4247. llvm_unreachable("unknown storage class specifier");
  4248. }
  4249. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4250. assert(Record->hasInClassInitializer());
  4251. for (const auto *I : Record->decls()) {
  4252. const auto *FD = dyn_cast<FieldDecl>(I);
  4253. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4254. FD = IFD->getAnonField();
  4255. if (FD && FD->hasInClassInitializer())
  4256. return FD->getLocation();
  4257. }
  4258. llvm_unreachable("couldn't find in-class initializer");
  4259. }
  4260. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4261. SourceLocation DefaultInitLoc) {
  4262. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4263. return;
  4264. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4265. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4266. }
  4267. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4268. CXXRecordDecl *AnonUnion) {
  4269. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4270. return;
  4271. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4272. }
  4273. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4274. /// anonymous structure or union. Anonymous unions are a C++ feature
  4275. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4276. /// are a C11 feature and GNU C++ extension.
  4277. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4278. AccessSpecifier AS,
  4279. RecordDecl *Record,
  4280. const PrintingPolicy &Policy) {
  4281. DeclContext *Owner = Record->getDeclContext();
  4282. // Diagnose whether this anonymous struct/union is an extension.
  4283. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4284. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4285. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4286. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4287. else if (!Record->isUnion() && !getLangOpts().C11)
  4288. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4289. // C and C++ require different kinds of checks for anonymous
  4290. // structs/unions.
  4291. bool Invalid = false;
  4292. if (getLangOpts().CPlusPlus) {
  4293. const char *PrevSpec = nullptr;
  4294. if (Record->isUnion()) {
  4295. // C++ [class.union]p6:
  4296. // C++17 [class.union.anon]p2:
  4297. // Anonymous unions declared in a named namespace or in the
  4298. // global namespace shall be declared static.
  4299. unsigned DiagID;
  4300. DeclContext *OwnerScope = Owner->getRedeclContext();
  4301. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4302. (OwnerScope->isTranslationUnit() ||
  4303. (OwnerScope->isNamespace() &&
  4304. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4305. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4306. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4307. // Recover by adding 'static'.
  4308. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4309. PrevSpec, DiagID, Policy);
  4310. }
  4311. // C++ [class.union]p6:
  4312. // A storage class is not allowed in a declaration of an
  4313. // anonymous union in a class scope.
  4314. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4315. isa<RecordDecl>(Owner)) {
  4316. Diag(DS.getStorageClassSpecLoc(),
  4317. diag::err_anonymous_union_with_storage_spec)
  4318. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4319. // Recover by removing the storage specifier.
  4320. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4321. SourceLocation(),
  4322. PrevSpec, DiagID, Context.getPrintingPolicy());
  4323. }
  4324. }
  4325. // Ignore const/volatile/restrict qualifiers.
  4326. if (DS.getTypeQualifiers()) {
  4327. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4328. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4329. << Record->isUnion() << "const"
  4330. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4331. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4332. Diag(DS.getVolatileSpecLoc(),
  4333. diag::ext_anonymous_struct_union_qualified)
  4334. << Record->isUnion() << "volatile"
  4335. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4336. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4337. Diag(DS.getRestrictSpecLoc(),
  4338. diag::ext_anonymous_struct_union_qualified)
  4339. << Record->isUnion() << "restrict"
  4340. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4341. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4342. Diag(DS.getAtomicSpecLoc(),
  4343. diag::ext_anonymous_struct_union_qualified)
  4344. << Record->isUnion() << "_Atomic"
  4345. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4346. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4347. Diag(DS.getUnalignedSpecLoc(),
  4348. diag::ext_anonymous_struct_union_qualified)
  4349. << Record->isUnion() << "__unaligned"
  4350. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4351. DS.ClearTypeQualifiers();
  4352. }
  4353. // C++ [class.union]p2:
  4354. // The member-specification of an anonymous union shall only
  4355. // define non-static data members. [Note: nested types and
  4356. // functions cannot be declared within an anonymous union. ]
  4357. for (auto *Mem : Record->decls()) {
  4358. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4359. // C++ [class.union]p3:
  4360. // An anonymous union shall not have private or protected
  4361. // members (clause 11).
  4362. assert(FD->getAccess() != AS_none);
  4363. if (FD->getAccess() != AS_public) {
  4364. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4365. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4366. Invalid = true;
  4367. }
  4368. // C++ [class.union]p1
  4369. // An object of a class with a non-trivial constructor, a non-trivial
  4370. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4371. // assignment operator cannot be a member of a union, nor can an
  4372. // array of such objects.
  4373. if (CheckNontrivialField(FD))
  4374. Invalid = true;
  4375. } else if (Mem->isImplicit()) {
  4376. // Any implicit members are fine.
  4377. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4378. // This is a type that showed up in an
  4379. // elaborated-type-specifier inside the anonymous struct or
  4380. // union, but which actually declares a type outside of the
  4381. // anonymous struct or union. It's okay.
  4382. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4383. if (!MemRecord->isAnonymousStructOrUnion() &&
  4384. MemRecord->getDeclName()) {
  4385. // Visual C++ allows type definition in anonymous struct or union.
  4386. if (getLangOpts().MicrosoftExt)
  4387. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4388. << Record->isUnion();
  4389. else {
  4390. // This is a nested type declaration.
  4391. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4392. << Record->isUnion();
  4393. Invalid = true;
  4394. }
  4395. } else {
  4396. // This is an anonymous type definition within another anonymous type.
  4397. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4398. // not part of standard C++.
  4399. Diag(MemRecord->getLocation(),
  4400. diag::ext_anonymous_record_with_anonymous_type)
  4401. << Record->isUnion();
  4402. }
  4403. } else if (isa<AccessSpecDecl>(Mem)) {
  4404. // Any access specifier is fine.
  4405. } else if (isa<StaticAssertDecl>(Mem)) {
  4406. // In C++1z, static_assert declarations are also fine.
  4407. } else {
  4408. // We have something that isn't a non-static data
  4409. // member. Complain about it.
  4410. unsigned DK = diag::err_anonymous_record_bad_member;
  4411. if (isa<TypeDecl>(Mem))
  4412. DK = diag::err_anonymous_record_with_type;
  4413. else if (isa<FunctionDecl>(Mem))
  4414. DK = diag::err_anonymous_record_with_function;
  4415. else if (isa<VarDecl>(Mem))
  4416. DK = diag::err_anonymous_record_with_static;
  4417. // Visual C++ allows type definition in anonymous struct or union.
  4418. if (getLangOpts().MicrosoftExt &&
  4419. DK == diag::err_anonymous_record_with_type)
  4420. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4421. << Record->isUnion();
  4422. else {
  4423. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4424. Invalid = true;
  4425. }
  4426. }
  4427. }
  4428. // C++11 [class.union]p8 (DR1460):
  4429. // At most one variant member of a union may have a
  4430. // brace-or-equal-initializer.
  4431. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4432. Owner->isRecord())
  4433. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4434. cast<CXXRecordDecl>(Record));
  4435. }
  4436. if (!Record->isUnion() && !Owner->isRecord()) {
  4437. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4438. << getLangOpts().CPlusPlus;
  4439. Invalid = true;
  4440. }
  4441. // C++ [dcl.dcl]p3:
  4442. // [If there are no declarators], and except for the declaration of an
  4443. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4444. // names into the program
  4445. // C++ [class.mem]p2:
  4446. // each such member-declaration shall either declare at least one member
  4447. // name of the class or declare at least one unnamed bit-field
  4448. //
  4449. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4450. if (getLangOpts().CPlusPlus && Record->field_empty())
  4451. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4452. // Mock up a declarator.
  4453. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4454. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4455. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4456. // Create a declaration for this anonymous struct/union.
  4457. NamedDecl *Anon = nullptr;
  4458. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4459. Anon = FieldDecl::Create(
  4460. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4461. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4462. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4463. /*InitStyle=*/ICIS_NoInit);
  4464. Anon->setAccess(AS);
  4465. if (getLangOpts().CPlusPlus)
  4466. FieldCollector->Add(cast<FieldDecl>(Anon));
  4467. } else {
  4468. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4469. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4470. if (SCSpec == DeclSpec::SCS_mutable) {
  4471. // mutable can only appear on non-static class members, so it's always
  4472. // an error here
  4473. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4474. Invalid = true;
  4475. SC = SC_None;
  4476. }
  4477. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4478. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4479. Context.getTypeDeclType(Record), TInfo, SC);
  4480. // Default-initialize the implicit variable. This initialization will be
  4481. // trivial in almost all cases, except if a union member has an in-class
  4482. // initializer:
  4483. // union { int n = 0; };
  4484. ActOnUninitializedDecl(Anon);
  4485. }
  4486. Anon->setImplicit();
  4487. // Mark this as an anonymous struct/union type.
  4488. Record->setAnonymousStructOrUnion(true);
  4489. // Add the anonymous struct/union object to the current
  4490. // context. We'll be referencing this object when we refer to one of
  4491. // its members.
  4492. Owner->addDecl(Anon);
  4493. // Inject the members of the anonymous struct/union into the owning
  4494. // context and into the identifier resolver chain for name lookup
  4495. // purposes.
  4496. SmallVector<NamedDecl*, 2> Chain;
  4497. Chain.push_back(Anon);
  4498. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4499. Invalid = true;
  4500. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4501. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4502. MangleNumberingContext *MCtx;
  4503. Decl *ManglingContextDecl;
  4504. std::tie(MCtx, ManglingContextDecl) =
  4505. getCurrentMangleNumberContext(NewVD->getDeclContext());
  4506. if (MCtx) {
  4507. Context.setManglingNumber(
  4508. NewVD, MCtx->getManglingNumber(
  4509. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4510. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4511. }
  4512. }
  4513. }
  4514. if (Invalid)
  4515. Anon->setInvalidDecl();
  4516. return Anon;
  4517. }
  4518. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4519. /// Microsoft C anonymous structure.
  4520. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4521. /// Example:
  4522. ///
  4523. /// struct A { int a; };
  4524. /// struct B { struct A; int b; };
  4525. ///
  4526. /// void foo() {
  4527. /// B var;
  4528. /// var.a = 3;
  4529. /// }
  4530. ///
  4531. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4532. RecordDecl *Record) {
  4533. assert(Record && "expected a record!");
  4534. // Mock up a declarator.
  4535. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4536. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4537. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4538. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4539. QualType RecTy = Context.getTypeDeclType(Record);
  4540. // Create a declaration for this anonymous struct.
  4541. NamedDecl *Anon =
  4542. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4543. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4544. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4545. /*InitStyle=*/ICIS_NoInit);
  4546. Anon->setImplicit();
  4547. // Add the anonymous struct object to the current context.
  4548. CurContext->addDecl(Anon);
  4549. // Inject the members of the anonymous struct into the current
  4550. // context and into the identifier resolver chain for name lookup
  4551. // purposes.
  4552. SmallVector<NamedDecl*, 2> Chain;
  4553. Chain.push_back(Anon);
  4554. RecordDecl *RecordDef = Record->getDefinition();
  4555. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4556. diag::err_field_incomplete) ||
  4557. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4558. AS_none, Chain)) {
  4559. Anon->setInvalidDecl();
  4560. ParentDecl->setInvalidDecl();
  4561. }
  4562. return Anon;
  4563. }
  4564. /// GetNameForDeclarator - Determine the full declaration name for the
  4565. /// given Declarator.
  4566. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4567. return GetNameFromUnqualifiedId(D.getName());
  4568. }
  4569. /// Retrieves the declaration name from a parsed unqualified-id.
  4570. DeclarationNameInfo
  4571. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4572. DeclarationNameInfo NameInfo;
  4573. NameInfo.setLoc(Name.StartLocation);
  4574. switch (Name.getKind()) {
  4575. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4576. case UnqualifiedIdKind::IK_Identifier:
  4577. NameInfo.setName(Name.Identifier);
  4578. return NameInfo;
  4579. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4580. // C++ [temp.deduct.guide]p3:
  4581. // The simple-template-id shall name a class template specialization.
  4582. // The template-name shall be the same identifier as the template-name
  4583. // of the simple-template-id.
  4584. // These together intend to imply that the template-name shall name a
  4585. // class template.
  4586. // FIXME: template<typename T> struct X {};
  4587. // template<typename T> using Y = X<T>;
  4588. // Y(int) -> Y<int>;
  4589. // satisfies these rules but does not name a class template.
  4590. TemplateName TN = Name.TemplateName.get().get();
  4591. auto *Template = TN.getAsTemplateDecl();
  4592. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4593. Diag(Name.StartLocation,
  4594. diag::err_deduction_guide_name_not_class_template)
  4595. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4596. if (Template)
  4597. Diag(Template->getLocation(), diag::note_template_decl_here);
  4598. return DeclarationNameInfo();
  4599. }
  4600. NameInfo.setName(
  4601. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4602. return NameInfo;
  4603. }
  4604. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4605. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4606. Name.OperatorFunctionId.Operator));
  4607. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4608. = Name.OperatorFunctionId.SymbolLocations[0];
  4609. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4610. = Name.EndLocation.getRawEncoding();
  4611. return NameInfo;
  4612. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4613. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4614. Name.Identifier));
  4615. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4616. return NameInfo;
  4617. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4618. TypeSourceInfo *TInfo;
  4619. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4620. if (Ty.isNull())
  4621. return DeclarationNameInfo();
  4622. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4623. Context.getCanonicalType(Ty)));
  4624. NameInfo.setNamedTypeInfo(TInfo);
  4625. return NameInfo;
  4626. }
  4627. case UnqualifiedIdKind::IK_ConstructorName: {
  4628. TypeSourceInfo *TInfo;
  4629. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4630. if (Ty.isNull())
  4631. return DeclarationNameInfo();
  4632. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4633. Context.getCanonicalType(Ty)));
  4634. NameInfo.setNamedTypeInfo(TInfo);
  4635. return NameInfo;
  4636. }
  4637. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4638. // In well-formed code, we can only have a constructor
  4639. // template-id that refers to the current context, so go there
  4640. // to find the actual type being constructed.
  4641. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4642. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4643. return DeclarationNameInfo();
  4644. // Determine the type of the class being constructed.
  4645. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4646. // FIXME: Check two things: that the template-id names the same type as
  4647. // CurClassType, and that the template-id does not occur when the name
  4648. // was qualified.
  4649. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4650. Context.getCanonicalType(CurClassType)));
  4651. // FIXME: should we retrieve TypeSourceInfo?
  4652. NameInfo.setNamedTypeInfo(nullptr);
  4653. return NameInfo;
  4654. }
  4655. case UnqualifiedIdKind::IK_DestructorName: {
  4656. TypeSourceInfo *TInfo;
  4657. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4658. if (Ty.isNull())
  4659. return DeclarationNameInfo();
  4660. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4661. Context.getCanonicalType(Ty)));
  4662. NameInfo.setNamedTypeInfo(TInfo);
  4663. return NameInfo;
  4664. }
  4665. case UnqualifiedIdKind::IK_TemplateId: {
  4666. TemplateName TName = Name.TemplateId->Template.get();
  4667. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4668. return Context.getNameForTemplate(TName, TNameLoc);
  4669. }
  4670. } // switch (Name.getKind())
  4671. llvm_unreachable("Unknown name kind");
  4672. }
  4673. static QualType getCoreType(QualType Ty) {
  4674. do {
  4675. if (Ty->isPointerType() || Ty->isReferenceType())
  4676. Ty = Ty->getPointeeType();
  4677. else if (Ty->isArrayType())
  4678. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4679. else
  4680. return Ty.withoutLocalFastQualifiers();
  4681. } while (true);
  4682. }
  4683. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4684. /// and Definition have "nearly" matching parameters. This heuristic is
  4685. /// used to improve diagnostics in the case where an out-of-line function
  4686. /// definition doesn't match any declaration within the class or namespace.
  4687. /// Also sets Params to the list of indices to the parameters that differ
  4688. /// between the declaration and the definition. If hasSimilarParameters
  4689. /// returns true and Params is empty, then all of the parameters match.
  4690. static bool hasSimilarParameters(ASTContext &Context,
  4691. FunctionDecl *Declaration,
  4692. FunctionDecl *Definition,
  4693. SmallVectorImpl<unsigned> &Params) {
  4694. Params.clear();
  4695. if (Declaration->param_size() != Definition->param_size())
  4696. return false;
  4697. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4698. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4699. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4700. // The parameter types are identical
  4701. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4702. continue;
  4703. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4704. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4705. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4706. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4707. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4708. (DeclTyName && DeclTyName == DefTyName))
  4709. Params.push_back(Idx);
  4710. else // The two parameters aren't even close
  4711. return false;
  4712. }
  4713. return true;
  4714. }
  4715. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4716. /// declarator needs to be rebuilt in the current instantiation.
  4717. /// Any bits of declarator which appear before the name are valid for
  4718. /// consideration here. That's specifically the type in the decl spec
  4719. /// and the base type in any member-pointer chunks.
  4720. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4721. DeclarationName Name) {
  4722. // The types we specifically need to rebuild are:
  4723. // - typenames, typeofs, and decltypes
  4724. // - types which will become injected class names
  4725. // Of course, we also need to rebuild any type referencing such a
  4726. // type. It's safest to just say "dependent", but we call out a
  4727. // few cases here.
  4728. DeclSpec &DS = D.getMutableDeclSpec();
  4729. switch (DS.getTypeSpecType()) {
  4730. case DeclSpec::TST_typename:
  4731. case DeclSpec::TST_typeofType:
  4732. case DeclSpec::TST_underlyingType:
  4733. case DeclSpec::TST_atomic: {
  4734. // Grab the type from the parser.
  4735. TypeSourceInfo *TSI = nullptr;
  4736. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4737. if (T.isNull() || !T->isDependentType()) break;
  4738. // Make sure there's a type source info. This isn't really much
  4739. // of a waste; most dependent types should have type source info
  4740. // attached already.
  4741. if (!TSI)
  4742. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4743. // Rebuild the type in the current instantiation.
  4744. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4745. if (!TSI) return true;
  4746. // Store the new type back in the decl spec.
  4747. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4748. DS.UpdateTypeRep(LocType);
  4749. break;
  4750. }
  4751. case DeclSpec::TST_decltype:
  4752. case DeclSpec::TST_typeofExpr: {
  4753. Expr *E = DS.getRepAsExpr();
  4754. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4755. if (Result.isInvalid()) return true;
  4756. DS.UpdateExprRep(Result.get());
  4757. break;
  4758. }
  4759. default:
  4760. // Nothing to do for these decl specs.
  4761. break;
  4762. }
  4763. // It doesn't matter what order we do this in.
  4764. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4765. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4766. // The only type information in the declarator which can come
  4767. // before the declaration name is the base type of a member
  4768. // pointer.
  4769. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4770. continue;
  4771. // Rebuild the scope specifier in-place.
  4772. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4773. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4774. return true;
  4775. }
  4776. return false;
  4777. }
  4778. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4779. D.setFunctionDefinitionKind(FDK_Declaration);
  4780. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4781. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4782. Dcl && Dcl->getDeclContext()->isFileContext())
  4783. Dcl->setTopLevelDeclInObjCContainer();
  4784. if (getLangOpts().OpenCL)
  4785. setCurrentOpenCLExtensionForDecl(Dcl);
  4786. return Dcl;
  4787. }
  4788. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4789. /// If T is the name of a class, then each of the following shall have a
  4790. /// name different from T:
  4791. /// - every static data member of class T;
  4792. /// - every member function of class T
  4793. /// - every member of class T that is itself a type;
  4794. /// \returns true if the declaration name violates these rules.
  4795. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4796. DeclarationNameInfo NameInfo) {
  4797. DeclarationName Name = NameInfo.getName();
  4798. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4799. while (Record && Record->isAnonymousStructOrUnion())
  4800. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4801. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4802. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4803. return true;
  4804. }
  4805. return false;
  4806. }
  4807. /// Diagnose a declaration whose declarator-id has the given
  4808. /// nested-name-specifier.
  4809. ///
  4810. /// \param SS The nested-name-specifier of the declarator-id.
  4811. ///
  4812. /// \param DC The declaration context to which the nested-name-specifier
  4813. /// resolves.
  4814. ///
  4815. /// \param Name The name of the entity being declared.
  4816. ///
  4817. /// \param Loc The location of the name of the entity being declared.
  4818. ///
  4819. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4820. /// we're declaring an explicit / partial specialization / instantiation.
  4821. ///
  4822. /// \returns true if we cannot safely recover from this error, false otherwise.
  4823. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4824. DeclarationName Name,
  4825. SourceLocation Loc, bool IsTemplateId) {
  4826. DeclContext *Cur = CurContext;
  4827. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4828. Cur = Cur->getParent();
  4829. // If the user provided a superfluous scope specifier that refers back to the
  4830. // class in which the entity is already declared, diagnose and ignore it.
  4831. //
  4832. // class X {
  4833. // void X::f();
  4834. // };
  4835. //
  4836. // Note, it was once ill-formed to give redundant qualification in all
  4837. // contexts, but that rule was removed by DR482.
  4838. if (Cur->Equals(DC)) {
  4839. if (Cur->isRecord()) {
  4840. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4841. : diag::err_member_extra_qualification)
  4842. << Name << FixItHint::CreateRemoval(SS.getRange());
  4843. SS.clear();
  4844. } else {
  4845. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4846. }
  4847. return false;
  4848. }
  4849. // Check whether the qualifying scope encloses the scope of the original
  4850. // declaration. For a template-id, we perform the checks in
  4851. // CheckTemplateSpecializationScope.
  4852. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4853. if (Cur->isRecord())
  4854. Diag(Loc, diag::err_member_qualification)
  4855. << Name << SS.getRange();
  4856. else if (isa<TranslationUnitDecl>(DC))
  4857. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4858. << Name << SS.getRange();
  4859. else if (isa<FunctionDecl>(Cur))
  4860. Diag(Loc, diag::err_invalid_declarator_in_function)
  4861. << Name << SS.getRange();
  4862. else if (isa<BlockDecl>(Cur))
  4863. Diag(Loc, diag::err_invalid_declarator_in_block)
  4864. << Name << SS.getRange();
  4865. else
  4866. Diag(Loc, diag::err_invalid_declarator_scope)
  4867. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4868. return true;
  4869. }
  4870. if (Cur->isRecord()) {
  4871. // Cannot qualify members within a class.
  4872. Diag(Loc, diag::err_member_qualification)
  4873. << Name << SS.getRange();
  4874. SS.clear();
  4875. // C++ constructors and destructors with incorrect scopes can break
  4876. // our AST invariants by having the wrong underlying types. If
  4877. // that's the case, then drop this declaration entirely.
  4878. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4879. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4880. !Context.hasSameType(Name.getCXXNameType(),
  4881. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4882. return true;
  4883. return false;
  4884. }
  4885. // C++11 [dcl.meaning]p1:
  4886. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4887. // not begin with a decltype-specifer"
  4888. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4889. while (SpecLoc.getPrefix())
  4890. SpecLoc = SpecLoc.getPrefix();
  4891. if (dyn_cast_or_null<DecltypeType>(
  4892. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4893. Diag(Loc, diag::err_decltype_in_declarator)
  4894. << SpecLoc.getTypeLoc().getSourceRange();
  4895. return false;
  4896. }
  4897. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4898. MultiTemplateParamsArg TemplateParamLists) {
  4899. // TODO: consider using NameInfo for diagnostic.
  4900. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4901. DeclarationName Name = NameInfo.getName();
  4902. // All of these full declarators require an identifier. If it doesn't have
  4903. // one, the ParsedFreeStandingDeclSpec action should be used.
  4904. if (D.isDecompositionDeclarator()) {
  4905. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4906. } else if (!Name) {
  4907. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4908. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4909. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4910. return nullptr;
  4911. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4912. return nullptr;
  4913. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4914. // we find one that is.
  4915. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4916. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4917. S = S->getParent();
  4918. DeclContext *DC = CurContext;
  4919. if (D.getCXXScopeSpec().isInvalid())
  4920. D.setInvalidType();
  4921. else if (D.getCXXScopeSpec().isSet()) {
  4922. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4923. UPPC_DeclarationQualifier))
  4924. return nullptr;
  4925. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4926. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4927. if (!DC || isa<EnumDecl>(DC)) {
  4928. // If we could not compute the declaration context, it's because the
  4929. // declaration context is dependent but does not refer to a class,
  4930. // class template, or class template partial specialization. Complain
  4931. // and return early, to avoid the coming semantic disaster.
  4932. Diag(D.getIdentifierLoc(),
  4933. diag::err_template_qualified_declarator_no_match)
  4934. << D.getCXXScopeSpec().getScopeRep()
  4935. << D.getCXXScopeSpec().getRange();
  4936. return nullptr;
  4937. }
  4938. bool IsDependentContext = DC->isDependentContext();
  4939. if (!IsDependentContext &&
  4940. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4941. return nullptr;
  4942. // If a class is incomplete, do not parse entities inside it.
  4943. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4944. Diag(D.getIdentifierLoc(),
  4945. diag::err_member_def_undefined_record)
  4946. << Name << DC << D.getCXXScopeSpec().getRange();
  4947. return nullptr;
  4948. }
  4949. if (!D.getDeclSpec().isFriendSpecified()) {
  4950. if (diagnoseQualifiedDeclaration(
  4951. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4952. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4953. if (DC->isRecord())
  4954. return nullptr;
  4955. D.setInvalidType();
  4956. }
  4957. }
  4958. // Check whether we need to rebuild the type of the given
  4959. // declaration in the current instantiation.
  4960. if (EnteringContext && IsDependentContext &&
  4961. TemplateParamLists.size() != 0) {
  4962. ContextRAII SavedContext(*this, DC);
  4963. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4964. D.setInvalidType();
  4965. }
  4966. }
  4967. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4968. QualType R = TInfo->getType();
  4969. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4970. UPPC_DeclarationType))
  4971. D.setInvalidType();
  4972. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4973. forRedeclarationInCurContext());
  4974. // See if this is a redefinition of a variable in the same scope.
  4975. if (!D.getCXXScopeSpec().isSet()) {
  4976. bool IsLinkageLookup = false;
  4977. bool CreateBuiltins = false;
  4978. // If the declaration we're planning to build will be a function
  4979. // or object with linkage, then look for another declaration with
  4980. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4981. //
  4982. // If the declaration we're planning to build will be declared with
  4983. // external linkage in the translation unit, create any builtin with
  4984. // the same name.
  4985. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4986. /* Do nothing*/;
  4987. else if (CurContext->isFunctionOrMethod() &&
  4988. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4989. R->isFunctionType())) {
  4990. IsLinkageLookup = true;
  4991. CreateBuiltins =
  4992. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4993. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4994. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4995. CreateBuiltins = true;
  4996. if (IsLinkageLookup) {
  4997. Previous.clear(LookupRedeclarationWithLinkage);
  4998. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4999. }
  5000. LookupName(Previous, S, CreateBuiltins);
  5001. } else { // Something like "int foo::x;"
  5002. LookupQualifiedName(Previous, DC);
  5003. // C++ [dcl.meaning]p1:
  5004. // When the declarator-id is qualified, the declaration shall refer to a
  5005. // previously declared member of the class or namespace to which the
  5006. // qualifier refers (or, in the case of a namespace, of an element of the
  5007. // inline namespace set of that namespace (7.3.1)) or to a specialization
  5008. // thereof; [...]
  5009. //
  5010. // Note that we already checked the context above, and that we do not have
  5011. // enough information to make sure that Previous contains the declaration
  5012. // we want to match. For example, given:
  5013. //
  5014. // class X {
  5015. // void f();
  5016. // void f(float);
  5017. // };
  5018. //
  5019. // void X::f(int) { } // ill-formed
  5020. //
  5021. // In this case, Previous will point to the overload set
  5022. // containing the two f's declared in X, but neither of them
  5023. // matches.
  5024. // C++ [dcl.meaning]p1:
  5025. // [...] the member shall not merely have been introduced by a
  5026. // using-declaration in the scope of the class or namespace nominated by
  5027. // the nested-name-specifier of the declarator-id.
  5028. RemoveUsingDecls(Previous);
  5029. }
  5030. if (Previous.isSingleResult() &&
  5031. Previous.getFoundDecl()->isTemplateParameter()) {
  5032. // Maybe we will complain about the shadowed template parameter.
  5033. if (!D.isInvalidType())
  5034. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  5035. Previous.getFoundDecl());
  5036. // Just pretend that we didn't see the previous declaration.
  5037. Previous.clear();
  5038. }
  5039. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  5040. // Forget that the previous declaration is the injected-class-name.
  5041. Previous.clear();
  5042. // In C++, the previous declaration we find might be a tag type
  5043. // (class or enum). In this case, the new declaration will hide the
  5044. // tag type. Note that this applies to functions, function templates, and
  5045. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  5046. if (Previous.isSingleTagDecl() &&
  5047. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  5048. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  5049. Previous.clear();
  5050. // Check that there are no default arguments other than in the parameters
  5051. // of a function declaration (C++ only).
  5052. if (getLangOpts().CPlusPlus)
  5053. CheckExtraCXXDefaultArguments(D);
  5054. NamedDecl *New;
  5055. bool AddToScope = true;
  5056. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5057. if (TemplateParamLists.size()) {
  5058. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5059. return nullptr;
  5060. }
  5061. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5062. } else if (R->isFunctionType()) {
  5063. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5064. TemplateParamLists,
  5065. AddToScope);
  5066. } else {
  5067. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5068. AddToScope);
  5069. }
  5070. if (!New)
  5071. return nullptr;
  5072. // If this has an identifier and is not a function template specialization,
  5073. // add it to the scope stack.
  5074. if (New->getDeclName() && AddToScope)
  5075. PushOnScopeChains(New, S);
  5076. if (isInOpenMPDeclareTargetContext())
  5077. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5078. return New;
  5079. }
  5080. /// Helper method to turn variable array types into constant array
  5081. /// types in certain situations which would otherwise be errors (for
  5082. /// GCC compatibility).
  5083. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5084. ASTContext &Context,
  5085. bool &SizeIsNegative,
  5086. llvm::APSInt &Oversized) {
  5087. // This method tries to turn a variable array into a constant
  5088. // array even when the size isn't an ICE. This is necessary
  5089. // for compatibility with code that depends on gcc's buggy
  5090. // constant expression folding, like struct {char x[(int)(char*)2];}
  5091. SizeIsNegative = false;
  5092. Oversized = 0;
  5093. if (T->isDependentType())
  5094. return QualType();
  5095. QualifierCollector Qs;
  5096. const Type *Ty = Qs.strip(T);
  5097. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5098. QualType Pointee = PTy->getPointeeType();
  5099. QualType FixedType =
  5100. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5101. Oversized);
  5102. if (FixedType.isNull()) return FixedType;
  5103. FixedType = Context.getPointerType(FixedType);
  5104. return Qs.apply(Context, FixedType);
  5105. }
  5106. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5107. QualType Inner = PTy->getInnerType();
  5108. QualType FixedType =
  5109. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5110. Oversized);
  5111. if (FixedType.isNull()) return FixedType;
  5112. FixedType = Context.getParenType(FixedType);
  5113. return Qs.apply(Context, FixedType);
  5114. }
  5115. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5116. if (!VLATy)
  5117. return QualType();
  5118. // FIXME: We should probably handle this case
  5119. if (VLATy->getElementType()->isVariablyModifiedType())
  5120. return QualType();
  5121. Expr::EvalResult Result;
  5122. if (!VLATy->getSizeExpr() ||
  5123. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5124. return QualType();
  5125. llvm::APSInt Res = Result.Val.getInt();
  5126. // Check whether the array size is negative.
  5127. if (Res.isSigned() && Res.isNegative()) {
  5128. SizeIsNegative = true;
  5129. return QualType();
  5130. }
  5131. // Check whether the array is too large to be addressed.
  5132. unsigned ActiveSizeBits
  5133. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  5134. Res);
  5135. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5136. Oversized = Res;
  5137. return QualType();
  5138. }
  5139. return Context.getConstantArrayType(
  5140. VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
  5141. }
  5142. static void
  5143. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5144. SrcTL = SrcTL.getUnqualifiedLoc();
  5145. DstTL = DstTL.getUnqualifiedLoc();
  5146. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5147. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5148. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5149. DstPTL.getPointeeLoc());
  5150. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5151. return;
  5152. }
  5153. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5154. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5155. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5156. DstPTL.getInnerLoc());
  5157. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5158. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5159. return;
  5160. }
  5161. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5162. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5163. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5164. TypeLoc DstElemTL = DstATL.getElementLoc();
  5165. DstElemTL.initializeFullCopy(SrcElemTL);
  5166. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5167. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5168. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5169. }
  5170. /// Helper method to turn variable array types into constant array
  5171. /// types in certain situations which would otherwise be errors (for
  5172. /// GCC compatibility).
  5173. static TypeSourceInfo*
  5174. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5175. ASTContext &Context,
  5176. bool &SizeIsNegative,
  5177. llvm::APSInt &Oversized) {
  5178. QualType FixedTy
  5179. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5180. SizeIsNegative, Oversized);
  5181. if (FixedTy.isNull())
  5182. return nullptr;
  5183. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5184. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5185. FixedTInfo->getTypeLoc());
  5186. return FixedTInfo;
  5187. }
  5188. /// Register the given locally-scoped extern "C" declaration so
  5189. /// that it can be found later for redeclarations. We include any extern "C"
  5190. /// declaration that is not visible in the translation unit here, not just
  5191. /// function-scope declarations.
  5192. void
  5193. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5194. if (!getLangOpts().CPlusPlus &&
  5195. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5196. // Don't need to track declarations in the TU in C.
  5197. return;
  5198. // Note that we have a locally-scoped external with this name.
  5199. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5200. }
  5201. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5202. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5203. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5204. return Result.empty() ? nullptr : *Result.begin();
  5205. }
  5206. /// Diagnose function specifiers on a declaration of an identifier that
  5207. /// does not identify a function.
  5208. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5209. // FIXME: We should probably indicate the identifier in question to avoid
  5210. // confusion for constructs like "virtual int a(), b;"
  5211. if (DS.isVirtualSpecified())
  5212. Diag(DS.getVirtualSpecLoc(),
  5213. diag::err_virtual_non_function);
  5214. if (DS.hasExplicitSpecifier())
  5215. Diag(DS.getExplicitSpecLoc(),
  5216. diag::err_explicit_non_function);
  5217. if (DS.isNoreturnSpecified())
  5218. Diag(DS.getNoreturnSpecLoc(),
  5219. diag::err_noreturn_non_function);
  5220. }
  5221. NamedDecl*
  5222. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5223. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5224. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5225. if (D.getCXXScopeSpec().isSet()) {
  5226. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5227. << D.getCXXScopeSpec().getRange();
  5228. D.setInvalidType();
  5229. // Pretend we didn't see the scope specifier.
  5230. DC = CurContext;
  5231. Previous.clear();
  5232. }
  5233. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5234. if (D.getDeclSpec().isInlineSpecified())
  5235. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5236. << getLangOpts().CPlusPlus17;
  5237. if (D.getDeclSpec().hasConstexprSpecifier())
  5238. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5239. << 1 << D.getDeclSpec().getConstexprSpecifier();
  5240. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5241. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5242. Diag(D.getName().StartLocation,
  5243. diag::err_deduction_guide_invalid_specifier)
  5244. << "typedef";
  5245. else
  5246. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5247. << D.getName().getSourceRange();
  5248. return nullptr;
  5249. }
  5250. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5251. if (!NewTD) return nullptr;
  5252. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5253. ProcessDeclAttributes(S, NewTD, D);
  5254. CheckTypedefForVariablyModifiedType(S, NewTD);
  5255. bool Redeclaration = D.isRedeclaration();
  5256. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5257. D.setRedeclaration(Redeclaration);
  5258. return ND;
  5259. }
  5260. void
  5261. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5262. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5263. // then it shall have block scope.
  5264. // Note that variably modified types must be fixed before merging the decl so
  5265. // that redeclarations will match.
  5266. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5267. QualType T = TInfo->getType();
  5268. if (T->isVariablyModifiedType()) {
  5269. setFunctionHasBranchProtectedScope();
  5270. if (S->getFnParent() == nullptr) {
  5271. bool SizeIsNegative;
  5272. llvm::APSInt Oversized;
  5273. TypeSourceInfo *FixedTInfo =
  5274. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5275. SizeIsNegative,
  5276. Oversized);
  5277. if (FixedTInfo) {
  5278. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5279. NewTD->setTypeSourceInfo(FixedTInfo);
  5280. } else {
  5281. if (SizeIsNegative)
  5282. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5283. else if (T->isVariableArrayType())
  5284. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5285. else if (Oversized.getBoolValue())
  5286. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5287. << Oversized.toString(10);
  5288. else
  5289. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5290. NewTD->setInvalidDecl();
  5291. }
  5292. }
  5293. }
  5294. }
  5295. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5296. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5297. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5298. NamedDecl*
  5299. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5300. LookupResult &Previous, bool &Redeclaration) {
  5301. // Find the shadowed declaration before filtering for scope.
  5302. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5303. // Merge the decl with the existing one if appropriate. If the decl is
  5304. // in an outer scope, it isn't the same thing.
  5305. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5306. /*AllowInlineNamespace*/false);
  5307. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5308. if (!Previous.empty()) {
  5309. Redeclaration = true;
  5310. MergeTypedefNameDecl(S, NewTD, Previous);
  5311. } else {
  5312. inferGslPointerAttribute(NewTD);
  5313. }
  5314. if (ShadowedDecl && !Redeclaration)
  5315. CheckShadow(NewTD, ShadowedDecl, Previous);
  5316. // If this is the C FILE type, notify the AST context.
  5317. if (IdentifierInfo *II = NewTD->getIdentifier())
  5318. if (!NewTD->isInvalidDecl() &&
  5319. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5320. if (II->isStr("FILE"))
  5321. Context.setFILEDecl(NewTD);
  5322. else if (II->isStr("jmp_buf"))
  5323. Context.setjmp_bufDecl(NewTD);
  5324. else if (II->isStr("sigjmp_buf"))
  5325. Context.setsigjmp_bufDecl(NewTD);
  5326. else if (II->isStr("ucontext_t"))
  5327. Context.setucontext_tDecl(NewTD);
  5328. }
  5329. return NewTD;
  5330. }
  5331. /// Determines whether the given declaration is an out-of-scope
  5332. /// previous declaration.
  5333. ///
  5334. /// This routine should be invoked when name lookup has found a
  5335. /// previous declaration (PrevDecl) that is not in the scope where a
  5336. /// new declaration by the same name is being introduced. If the new
  5337. /// declaration occurs in a local scope, previous declarations with
  5338. /// linkage may still be considered previous declarations (C99
  5339. /// 6.2.2p4-5, C++ [basic.link]p6).
  5340. ///
  5341. /// \param PrevDecl the previous declaration found by name
  5342. /// lookup
  5343. ///
  5344. /// \param DC the context in which the new declaration is being
  5345. /// declared.
  5346. ///
  5347. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5348. /// for a new delcaration with the same name.
  5349. static bool
  5350. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5351. ASTContext &Context) {
  5352. if (!PrevDecl)
  5353. return false;
  5354. if (!PrevDecl->hasLinkage())
  5355. return false;
  5356. if (Context.getLangOpts().CPlusPlus) {
  5357. // C++ [basic.link]p6:
  5358. // If there is a visible declaration of an entity with linkage
  5359. // having the same name and type, ignoring entities declared
  5360. // outside the innermost enclosing namespace scope, the block
  5361. // scope declaration declares that same entity and receives the
  5362. // linkage of the previous declaration.
  5363. DeclContext *OuterContext = DC->getRedeclContext();
  5364. if (!OuterContext->isFunctionOrMethod())
  5365. // This rule only applies to block-scope declarations.
  5366. return false;
  5367. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5368. if (PrevOuterContext->isRecord())
  5369. // We found a member function: ignore it.
  5370. return false;
  5371. // Find the innermost enclosing namespace for the new and
  5372. // previous declarations.
  5373. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5374. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5375. // The previous declaration is in a different namespace, so it
  5376. // isn't the same function.
  5377. if (!OuterContext->Equals(PrevOuterContext))
  5378. return false;
  5379. }
  5380. return true;
  5381. }
  5382. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5383. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5384. if (!SS.isSet()) return;
  5385. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5386. }
  5387. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5388. QualType type = decl->getType();
  5389. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5390. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5391. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5392. unsigned kind = -1U;
  5393. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5394. if (var->hasAttr<BlocksAttr>())
  5395. kind = 0; // __block
  5396. else if (!var->hasLocalStorage())
  5397. kind = 1; // global
  5398. } else if (isa<ObjCIvarDecl>(decl)) {
  5399. kind = 3; // ivar
  5400. } else if (isa<FieldDecl>(decl)) {
  5401. kind = 2; // field
  5402. }
  5403. if (kind != -1U) {
  5404. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5405. << kind;
  5406. }
  5407. } else if (lifetime == Qualifiers::OCL_None) {
  5408. // Try to infer lifetime.
  5409. if (!type->isObjCLifetimeType())
  5410. return false;
  5411. lifetime = type->getObjCARCImplicitLifetime();
  5412. type = Context.getLifetimeQualifiedType(type, lifetime);
  5413. decl->setType(type);
  5414. }
  5415. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5416. // Thread-local variables cannot have lifetime.
  5417. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5418. var->getTLSKind()) {
  5419. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5420. << var->getType();
  5421. return true;
  5422. }
  5423. }
  5424. return false;
  5425. }
  5426. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5427. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5428. // the wrong linkage.
  5429. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5430. // 'weak' only applies to declarations with external linkage.
  5431. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5432. if (!ND.isExternallyVisible()) {
  5433. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5434. ND.dropAttr<WeakAttr>();
  5435. }
  5436. }
  5437. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5438. if (ND.isExternallyVisible()) {
  5439. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5440. ND.dropAttr<WeakRefAttr>();
  5441. ND.dropAttr<AliasAttr>();
  5442. }
  5443. }
  5444. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5445. if (VD->hasInit()) {
  5446. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5447. assert(VD->isThisDeclarationADefinition() &&
  5448. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5449. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5450. VD->dropAttr<AliasAttr>();
  5451. }
  5452. }
  5453. }
  5454. // 'selectany' only applies to externally visible variable declarations.
  5455. // It does not apply to functions.
  5456. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5457. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5458. S.Diag(Attr->getLocation(),
  5459. diag::err_attribute_selectany_non_extern_data);
  5460. ND.dropAttr<SelectAnyAttr>();
  5461. }
  5462. }
  5463. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5464. auto *VD = dyn_cast<VarDecl>(&ND);
  5465. bool IsAnonymousNS = false;
  5466. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5467. if (VD) {
  5468. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5469. while (NS && !IsAnonymousNS) {
  5470. IsAnonymousNS = NS->isAnonymousNamespace();
  5471. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5472. }
  5473. }
  5474. // dll attributes require external linkage. Static locals may have external
  5475. // linkage but still cannot be explicitly imported or exported.
  5476. // In Microsoft mode, a variable defined in anonymous namespace must have
  5477. // external linkage in order to be exported.
  5478. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5479. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5480. (!AnonNSInMicrosoftMode &&
  5481. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5482. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5483. << &ND << Attr;
  5484. ND.setInvalidDecl();
  5485. }
  5486. }
  5487. // Virtual functions cannot be marked as 'notail'.
  5488. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5489. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5490. if (MD->isVirtual()) {
  5491. S.Diag(ND.getLocation(),
  5492. diag::err_invalid_attribute_on_virtual_function)
  5493. << Attr;
  5494. ND.dropAttr<NotTailCalledAttr>();
  5495. }
  5496. // Check the attributes on the function type, if any.
  5497. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5498. // Don't declare this variable in the second operand of the for-statement;
  5499. // GCC miscompiles that by ending its lifetime before evaluating the
  5500. // third operand. See gcc.gnu.org/PR86769.
  5501. AttributedTypeLoc ATL;
  5502. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5503. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5504. TL = ATL.getModifiedLoc()) {
  5505. // The [[lifetimebound]] attribute can be applied to the implicit object
  5506. // parameter of a non-static member function (other than a ctor or dtor)
  5507. // by applying it to the function type.
  5508. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5509. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5510. if (!MD || MD->isStatic()) {
  5511. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5512. << !MD << A->getRange();
  5513. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5514. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5515. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5516. }
  5517. }
  5518. }
  5519. }
  5520. }
  5521. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5522. NamedDecl *NewDecl,
  5523. bool IsSpecialization,
  5524. bool IsDefinition) {
  5525. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5526. return;
  5527. bool IsTemplate = false;
  5528. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5529. OldDecl = OldTD->getTemplatedDecl();
  5530. IsTemplate = true;
  5531. if (!IsSpecialization)
  5532. IsDefinition = false;
  5533. }
  5534. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5535. NewDecl = NewTD->getTemplatedDecl();
  5536. IsTemplate = true;
  5537. }
  5538. if (!OldDecl || !NewDecl)
  5539. return;
  5540. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5541. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5542. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5543. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5544. // dllimport and dllexport are inheritable attributes so we have to exclude
  5545. // inherited attribute instances.
  5546. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5547. (NewExportAttr && !NewExportAttr->isInherited());
  5548. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5549. // the only exception being explicit specializations.
  5550. // Implicitly generated declarations are also excluded for now because there
  5551. // is no other way to switch these to use dllimport or dllexport.
  5552. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5553. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5554. // Allow with a warning for free functions and global variables.
  5555. bool JustWarn = false;
  5556. if (!OldDecl->isCXXClassMember()) {
  5557. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5558. if (VD && !VD->getDescribedVarTemplate())
  5559. JustWarn = true;
  5560. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5561. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5562. JustWarn = true;
  5563. }
  5564. // We cannot change a declaration that's been used because IR has already
  5565. // been emitted. Dllimported functions will still work though (modulo
  5566. // address equality) as they can use the thunk.
  5567. if (OldDecl->isUsed())
  5568. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5569. JustWarn = false;
  5570. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5571. : diag::err_attribute_dll_redeclaration;
  5572. S.Diag(NewDecl->getLocation(), DiagID)
  5573. << NewDecl
  5574. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5575. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5576. if (!JustWarn) {
  5577. NewDecl->setInvalidDecl();
  5578. return;
  5579. }
  5580. }
  5581. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5582. // exceptions being inline function definitions (except for function
  5583. // templates), local extern declarations, qualified friend declarations or
  5584. // special MSVC extension: in the last case, the declaration is treated as if
  5585. // it were marked dllexport.
  5586. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5587. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5588. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5589. // Ignore static data because out-of-line definitions are diagnosed
  5590. // separately.
  5591. IsStaticDataMember = VD->isStaticDataMember();
  5592. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5593. VarDecl::DeclarationOnly;
  5594. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5595. IsInline = FD->isInlined();
  5596. IsQualifiedFriend = FD->getQualifier() &&
  5597. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5598. }
  5599. if (OldImportAttr && !HasNewAttr &&
  5600. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5601. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5602. if (IsMicrosoft && IsDefinition) {
  5603. S.Diag(NewDecl->getLocation(),
  5604. diag::warn_redeclaration_without_import_attribute)
  5605. << NewDecl;
  5606. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5607. NewDecl->dropAttr<DLLImportAttr>();
  5608. NewDecl->addAttr(
  5609. DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
  5610. } else {
  5611. S.Diag(NewDecl->getLocation(),
  5612. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5613. << NewDecl << OldImportAttr;
  5614. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5615. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5616. OldDecl->dropAttr<DLLImportAttr>();
  5617. NewDecl->dropAttr<DLLImportAttr>();
  5618. }
  5619. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5620. // In MinGW, seeing a function declared inline drops the dllimport
  5621. // attribute.
  5622. OldDecl->dropAttr<DLLImportAttr>();
  5623. NewDecl->dropAttr<DLLImportAttr>();
  5624. S.Diag(NewDecl->getLocation(),
  5625. diag::warn_dllimport_dropped_from_inline_function)
  5626. << NewDecl << OldImportAttr;
  5627. }
  5628. // A specialization of a class template member function is processed here
  5629. // since it's a redeclaration. If the parent class is dllexport, the
  5630. // specialization inherits that attribute. This doesn't happen automatically
  5631. // since the parent class isn't instantiated until later.
  5632. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5633. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5634. !NewImportAttr && !NewExportAttr) {
  5635. if (const DLLExportAttr *ParentExportAttr =
  5636. MD->getParent()->getAttr<DLLExportAttr>()) {
  5637. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5638. NewAttr->setInherited(true);
  5639. NewDecl->addAttr(NewAttr);
  5640. }
  5641. }
  5642. }
  5643. }
  5644. /// Given that we are within the definition of the given function,
  5645. /// will that definition behave like C99's 'inline', where the
  5646. /// definition is discarded except for optimization purposes?
  5647. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5648. // Try to avoid calling GetGVALinkageForFunction.
  5649. // All cases of this require the 'inline' keyword.
  5650. if (!FD->isInlined()) return false;
  5651. // This is only possible in C++ with the gnu_inline attribute.
  5652. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5653. return false;
  5654. // Okay, go ahead and call the relatively-more-expensive function.
  5655. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5656. }
  5657. /// Determine whether a variable is extern "C" prior to attaching
  5658. /// an initializer. We can't just call isExternC() here, because that
  5659. /// will also compute and cache whether the declaration is externally
  5660. /// visible, which might change when we attach the initializer.
  5661. ///
  5662. /// This can only be used if the declaration is known to not be a
  5663. /// redeclaration of an internal linkage declaration.
  5664. ///
  5665. /// For instance:
  5666. ///
  5667. /// auto x = []{};
  5668. ///
  5669. /// Attaching the initializer here makes this declaration not externally
  5670. /// visible, because its type has internal linkage.
  5671. ///
  5672. /// FIXME: This is a hack.
  5673. template<typename T>
  5674. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5675. if (S.getLangOpts().CPlusPlus) {
  5676. // In C++, the overloadable attribute negates the effects of extern "C".
  5677. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5678. return false;
  5679. // So do CUDA's host/device attributes.
  5680. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5681. D->template hasAttr<CUDAHostAttr>()))
  5682. return false;
  5683. }
  5684. return D->isExternC();
  5685. }
  5686. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5687. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5688. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5689. isa<OMPDeclareMapperDecl>(DC))
  5690. return VD->hasExternalStorage();
  5691. if (DC->isFileContext())
  5692. return true;
  5693. if (DC->isRecord())
  5694. return false;
  5695. llvm_unreachable("Unexpected context");
  5696. }
  5697. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5698. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5699. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5700. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5701. return true;
  5702. if (DC->isRecord())
  5703. return false;
  5704. llvm_unreachable("Unexpected context");
  5705. }
  5706. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5707. ParsedAttr::Kind Kind) {
  5708. // Check decl attributes on the DeclSpec.
  5709. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5710. return true;
  5711. // Walk the declarator structure, checking decl attributes that were in a type
  5712. // position to the decl itself.
  5713. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5714. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5715. return true;
  5716. }
  5717. // Finally, check attributes on the decl itself.
  5718. return PD.getAttributes().hasAttribute(Kind);
  5719. }
  5720. /// Adjust the \c DeclContext for a function or variable that might be a
  5721. /// function-local external declaration.
  5722. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5723. if (!DC->isFunctionOrMethod())
  5724. return false;
  5725. // If this is a local extern function or variable declared within a function
  5726. // template, don't add it into the enclosing namespace scope until it is
  5727. // instantiated; it might have a dependent type right now.
  5728. if (DC->isDependentContext())
  5729. return true;
  5730. // C++11 [basic.link]p7:
  5731. // When a block scope declaration of an entity with linkage is not found to
  5732. // refer to some other declaration, then that entity is a member of the
  5733. // innermost enclosing namespace.
  5734. //
  5735. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5736. // semantically-enclosing namespace, not a lexically-enclosing one.
  5737. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5738. DC = DC->getParent();
  5739. return true;
  5740. }
  5741. /// Returns true if given declaration has external C language linkage.
  5742. static bool isDeclExternC(const Decl *D) {
  5743. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5744. return FD->isExternC();
  5745. if (const auto *VD = dyn_cast<VarDecl>(D))
  5746. return VD->isExternC();
  5747. llvm_unreachable("Unknown type of decl!");
  5748. }
  5749. NamedDecl *Sema::ActOnVariableDeclarator(
  5750. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5751. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5752. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5753. QualType R = TInfo->getType();
  5754. DeclarationName Name = GetNameForDeclarator(D).getName();
  5755. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5756. if (D.isDecompositionDeclarator()) {
  5757. // Take the name of the first declarator as our name for diagnostic
  5758. // purposes.
  5759. auto &Decomp = D.getDecompositionDeclarator();
  5760. if (!Decomp.bindings().empty()) {
  5761. II = Decomp.bindings()[0].Name;
  5762. Name = II;
  5763. }
  5764. } else if (!II) {
  5765. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5766. return nullptr;
  5767. }
  5768. if (getLangOpts().OpenCL) {
  5769. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5770. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5771. // argument.
  5772. if (R->isImageType() || R->isPipeType()) {
  5773. Diag(D.getIdentifierLoc(),
  5774. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5775. << R;
  5776. D.setInvalidType();
  5777. return nullptr;
  5778. }
  5779. // OpenCL v1.2 s6.9.r:
  5780. // The event type cannot be used to declare a program scope variable.
  5781. // OpenCL v2.0 s6.9.q:
  5782. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5783. if (NULL == S->getParent()) {
  5784. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5785. Diag(D.getIdentifierLoc(),
  5786. diag::err_invalid_type_for_program_scope_var) << R;
  5787. D.setInvalidType();
  5788. return nullptr;
  5789. }
  5790. }
  5791. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5792. QualType NR = R;
  5793. while (NR->isPointerType()) {
  5794. if (NR->isFunctionPointerType()) {
  5795. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5796. D.setInvalidType();
  5797. break;
  5798. }
  5799. NR = NR->getPointeeType();
  5800. }
  5801. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5802. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5803. // half array type (unless the cl_khr_fp16 extension is enabled).
  5804. if (Context.getBaseElementType(R)->isHalfType()) {
  5805. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5806. D.setInvalidType();
  5807. }
  5808. }
  5809. if (R->isSamplerT()) {
  5810. // OpenCL v1.2 s6.9.b p4:
  5811. // The sampler type cannot be used with the __local and __global address
  5812. // space qualifiers.
  5813. if (R.getAddressSpace() == LangAS::opencl_local ||
  5814. R.getAddressSpace() == LangAS::opencl_global) {
  5815. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5816. }
  5817. // OpenCL v1.2 s6.12.14.1:
  5818. // A global sampler must be declared with either the constant address
  5819. // space qualifier or with the const qualifier.
  5820. if (DC->isTranslationUnit() &&
  5821. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5822. R.isConstQualified())) {
  5823. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5824. D.setInvalidType();
  5825. }
  5826. }
  5827. // OpenCL v1.2 s6.9.r:
  5828. // The event type cannot be used with the __local, __constant and __global
  5829. // address space qualifiers.
  5830. if (R->isEventT()) {
  5831. if (R.getAddressSpace() != LangAS::opencl_private) {
  5832. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5833. D.setInvalidType();
  5834. }
  5835. }
  5836. // C++ for OpenCL does not allow the thread_local storage qualifier.
  5837. // OpenCL C does not support thread_local either, and
  5838. // also reject all other thread storage class specifiers.
  5839. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5840. if (TSC != TSCS_unspecified) {
  5841. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5842. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5843. diag::err_opencl_unknown_type_specifier)
  5844. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5845. << DeclSpec::getSpecifierName(TSC) << 1;
  5846. D.setInvalidType();
  5847. return nullptr;
  5848. }
  5849. }
  5850. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5851. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5852. // dllimport globals without explicit storage class are treated as extern. We
  5853. // have to change the storage class this early to get the right DeclContext.
  5854. if (SC == SC_None && !DC->isRecord() &&
  5855. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5856. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5857. SC = SC_Extern;
  5858. DeclContext *OriginalDC = DC;
  5859. bool IsLocalExternDecl = SC == SC_Extern &&
  5860. adjustContextForLocalExternDecl(DC);
  5861. if (SCSpec == DeclSpec::SCS_mutable) {
  5862. // mutable can only appear on non-static class members, so it's always
  5863. // an error here
  5864. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5865. D.setInvalidType();
  5866. SC = SC_None;
  5867. }
  5868. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5869. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5870. D.getDeclSpec().getStorageClassSpecLoc())) {
  5871. // In C++11, the 'register' storage class specifier is deprecated.
  5872. // Suppress the warning in system macros, it's used in macros in some
  5873. // popular C system headers, such as in glibc's htonl() macro.
  5874. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5875. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5876. : diag::warn_deprecated_register)
  5877. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5878. }
  5879. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5880. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5881. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5882. // appear in the declaration specifiers in an external declaration.
  5883. // Global Register+Asm is a GNU extension we support.
  5884. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5885. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5886. D.setInvalidType();
  5887. }
  5888. }
  5889. bool IsMemberSpecialization = false;
  5890. bool IsVariableTemplateSpecialization = false;
  5891. bool IsPartialSpecialization = false;
  5892. bool IsVariableTemplate = false;
  5893. VarDecl *NewVD = nullptr;
  5894. VarTemplateDecl *NewTemplate = nullptr;
  5895. TemplateParameterList *TemplateParams = nullptr;
  5896. if (!getLangOpts().CPlusPlus) {
  5897. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5898. II, R, TInfo, SC);
  5899. if (R->getContainedDeducedType())
  5900. ParsingInitForAutoVars.insert(NewVD);
  5901. if (D.isInvalidType())
  5902. NewVD->setInvalidDecl();
  5903. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  5904. NewVD->hasLocalStorage())
  5905. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  5906. NTCUC_AutoVar, NTCUK_Destruct);
  5907. } else {
  5908. bool Invalid = false;
  5909. if (DC->isRecord() && !CurContext->isRecord()) {
  5910. // This is an out-of-line definition of a static data member.
  5911. switch (SC) {
  5912. case SC_None:
  5913. break;
  5914. case SC_Static:
  5915. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5916. diag::err_static_out_of_line)
  5917. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5918. break;
  5919. case SC_Auto:
  5920. case SC_Register:
  5921. case SC_Extern:
  5922. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5923. // to names of variables declared in a block or to function parameters.
  5924. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5925. // of class members
  5926. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5927. diag::err_storage_class_for_static_member)
  5928. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5929. break;
  5930. case SC_PrivateExtern:
  5931. llvm_unreachable("C storage class in c++!");
  5932. }
  5933. }
  5934. if (SC == SC_Static && CurContext->isRecord()) {
  5935. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5936. if (RD->isLocalClass())
  5937. Diag(D.getIdentifierLoc(),
  5938. diag::err_static_data_member_not_allowed_in_local_class)
  5939. << Name << RD->getDeclName();
  5940. // C++98 [class.union]p1: If a union contains a static data member,
  5941. // the program is ill-formed. C++11 drops this restriction.
  5942. if (RD->isUnion())
  5943. Diag(D.getIdentifierLoc(),
  5944. getLangOpts().CPlusPlus11
  5945. ? diag::warn_cxx98_compat_static_data_member_in_union
  5946. : diag::ext_static_data_member_in_union) << Name;
  5947. // We conservatively disallow static data members in anonymous structs.
  5948. else if (!RD->getDeclName())
  5949. Diag(D.getIdentifierLoc(),
  5950. diag::err_static_data_member_not_allowed_in_anon_struct)
  5951. << Name << RD->isUnion();
  5952. }
  5953. }
  5954. // Match up the template parameter lists with the scope specifier, then
  5955. // determine whether we have a template or a template specialization.
  5956. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5957. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5958. D.getCXXScopeSpec(),
  5959. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5960. ? D.getName().TemplateId
  5961. : nullptr,
  5962. TemplateParamLists,
  5963. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5964. if (TemplateParams) {
  5965. if (!TemplateParams->size() &&
  5966. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5967. // There is an extraneous 'template<>' for this variable. Complain
  5968. // about it, but allow the declaration of the variable.
  5969. Diag(TemplateParams->getTemplateLoc(),
  5970. diag::err_template_variable_noparams)
  5971. << II
  5972. << SourceRange(TemplateParams->getTemplateLoc(),
  5973. TemplateParams->getRAngleLoc());
  5974. TemplateParams = nullptr;
  5975. } else {
  5976. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5977. // This is an explicit specialization or a partial specialization.
  5978. // FIXME: Check that we can declare a specialization here.
  5979. IsVariableTemplateSpecialization = true;
  5980. IsPartialSpecialization = TemplateParams->size() > 0;
  5981. } else { // if (TemplateParams->size() > 0)
  5982. // This is a template declaration.
  5983. IsVariableTemplate = true;
  5984. // Check that we can declare a template here.
  5985. if (CheckTemplateDeclScope(S, TemplateParams))
  5986. return nullptr;
  5987. // Only C++1y supports variable templates (N3651).
  5988. Diag(D.getIdentifierLoc(),
  5989. getLangOpts().CPlusPlus14
  5990. ? diag::warn_cxx11_compat_variable_template
  5991. : diag::ext_variable_template);
  5992. }
  5993. }
  5994. } else {
  5995. assert((Invalid ||
  5996. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5997. "should have a 'template<>' for this decl");
  5998. }
  5999. if (IsVariableTemplateSpecialization) {
  6000. SourceLocation TemplateKWLoc =
  6001. TemplateParamLists.size() > 0
  6002. ? TemplateParamLists[0]->getTemplateLoc()
  6003. : SourceLocation();
  6004. DeclResult Res = ActOnVarTemplateSpecialization(
  6005. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  6006. IsPartialSpecialization);
  6007. if (Res.isInvalid())
  6008. return nullptr;
  6009. NewVD = cast<VarDecl>(Res.get());
  6010. AddToScope = false;
  6011. } else if (D.isDecompositionDeclarator()) {
  6012. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  6013. D.getIdentifierLoc(), R, TInfo, SC,
  6014. Bindings);
  6015. } else
  6016. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  6017. D.getIdentifierLoc(), II, R, TInfo, SC);
  6018. // If this is supposed to be a variable template, create it as such.
  6019. if (IsVariableTemplate) {
  6020. NewTemplate =
  6021. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  6022. TemplateParams, NewVD);
  6023. NewVD->setDescribedVarTemplate(NewTemplate);
  6024. }
  6025. // If this decl has an auto type in need of deduction, make a note of the
  6026. // Decl so we can diagnose uses of it in its own initializer.
  6027. if (R->getContainedDeducedType())
  6028. ParsingInitForAutoVars.insert(NewVD);
  6029. if (D.isInvalidType() || Invalid) {
  6030. NewVD->setInvalidDecl();
  6031. if (NewTemplate)
  6032. NewTemplate->setInvalidDecl();
  6033. }
  6034. SetNestedNameSpecifier(*this, NewVD, D);
  6035. // If we have any template parameter lists that don't directly belong to
  6036. // the variable (matching the scope specifier), store them.
  6037. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  6038. if (TemplateParamLists.size() > VDTemplateParamLists)
  6039. NewVD->setTemplateParameterListsInfo(
  6040. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  6041. }
  6042. if (D.getDeclSpec().isInlineSpecified()) {
  6043. if (!getLangOpts().CPlusPlus) {
  6044. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  6045. << 0;
  6046. } else if (CurContext->isFunctionOrMethod()) {
  6047. // 'inline' is not allowed on block scope variable declaration.
  6048. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6049. diag::err_inline_declaration_block_scope) << Name
  6050. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6051. } else {
  6052. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6053. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  6054. : diag::ext_inline_variable);
  6055. NewVD->setInlineSpecified();
  6056. }
  6057. }
  6058. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6059. // lexical context will be different from the semantic context.
  6060. NewVD->setLexicalDeclContext(CurContext);
  6061. if (NewTemplate)
  6062. NewTemplate->setLexicalDeclContext(CurContext);
  6063. if (IsLocalExternDecl) {
  6064. if (D.isDecompositionDeclarator())
  6065. for (auto *B : Bindings)
  6066. B->setLocalExternDecl();
  6067. else
  6068. NewVD->setLocalExternDecl();
  6069. }
  6070. bool EmitTLSUnsupportedError = false;
  6071. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6072. // C++11 [dcl.stc]p4:
  6073. // When thread_local is applied to a variable of block scope the
  6074. // storage-class-specifier static is implied if it does not appear
  6075. // explicitly.
  6076. // Core issue: 'static' is not implied if the variable is declared
  6077. // 'extern'.
  6078. if (NewVD->hasLocalStorage() &&
  6079. (SCSpec != DeclSpec::SCS_unspecified ||
  6080. TSCS != DeclSpec::TSCS_thread_local ||
  6081. !DC->isFunctionOrMethod()))
  6082. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6083. diag::err_thread_non_global)
  6084. << DeclSpec::getSpecifierName(TSCS);
  6085. else if (!Context.getTargetInfo().isTLSSupported()) {
  6086. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6087. // Postpone error emission until we've collected attributes required to
  6088. // figure out whether it's a host or device variable and whether the
  6089. // error should be ignored.
  6090. EmitTLSUnsupportedError = true;
  6091. // We still need to mark the variable as TLS so it shows up in AST with
  6092. // proper storage class for other tools to use even if we're not going
  6093. // to emit any code for it.
  6094. NewVD->setTSCSpec(TSCS);
  6095. } else
  6096. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6097. diag::err_thread_unsupported);
  6098. } else
  6099. NewVD->setTSCSpec(TSCS);
  6100. }
  6101. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6102. case CSK_unspecified:
  6103. break;
  6104. case CSK_consteval:
  6105. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6106. diag::err_constexpr_wrong_decl_kind)
  6107. << D.getDeclSpec().getConstexprSpecifier();
  6108. LLVM_FALLTHROUGH;
  6109. case CSK_constexpr:
  6110. NewVD->setConstexpr(true);
  6111. // C++1z [dcl.spec.constexpr]p1:
  6112. // A static data member declared with the constexpr specifier is
  6113. // implicitly an inline variable.
  6114. if (NewVD->isStaticDataMember() &&
  6115. (getLangOpts().CPlusPlus17 ||
  6116. Context.getTargetInfo().getCXXABI().isMicrosoft()))
  6117. NewVD->setImplicitlyInline();
  6118. break;
  6119. case CSK_constinit:
  6120. if (!NewVD->hasGlobalStorage())
  6121. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6122. diag::err_constinit_local_variable);
  6123. else
  6124. NewVD->addAttr(ConstInitAttr::Create(
  6125. Context, D.getDeclSpec().getConstexprSpecLoc(),
  6126. AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
  6127. break;
  6128. }
  6129. // C99 6.7.4p3
  6130. // An inline definition of a function with external linkage shall
  6131. // not contain a definition of a modifiable object with static or
  6132. // thread storage duration...
  6133. // We only apply this when the function is required to be defined
  6134. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6135. // that a local variable with thread storage duration still has to
  6136. // be marked 'static'. Also note that it's possible to get these
  6137. // semantics in C++ using __attribute__((gnu_inline)).
  6138. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6139. !NewVD->getType().isConstQualified()) {
  6140. FunctionDecl *CurFD = getCurFunctionDecl();
  6141. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6142. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6143. diag::warn_static_local_in_extern_inline);
  6144. MaybeSuggestAddingStaticToDecl(CurFD);
  6145. }
  6146. }
  6147. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6148. if (IsVariableTemplateSpecialization)
  6149. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6150. << (IsPartialSpecialization ? 1 : 0)
  6151. << FixItHint::CreateRemoval(
  6152. D.getDeclSpec().getModulePrivateSpecLoc());
  6153. else if (IsMemberSpecialization)
  6154. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6155. << 2
  6156. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6157. else if (NewVD->hasLocalStorage())
  6158. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6159. << 0 << NewVD->getDeclName()
  6160. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6161. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6162. else {
  6163. NewVD->setModulePrivate();
  6164. if (NewTemplate)
  6165. NewTemplate->setModulePrivate();
  6166. for (auto *B : Bindings)
  6167. B->setModulePrivate();
  6168. }
  6169. }
  6170. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6171. ProcessDeclAttributes(S, NewVD, D);
  6172. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  6173. if (EmitTLSUnsupportedError &&
  6174. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6175. (getLangOpts().OpenMPIsDevice &&
  6176. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6177. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6178. diag::err_thread_unsupported);
  6179. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6180. // storage [duration]."
  6181. if (SC == SC_None && S->getFnParent() != nullptr &&
  6182. (NewVD->hasAttr<CUDASharedAttr>() ||
  6183. NewVD->hasAttr<CUDAConstantAttr>())) {
  6184. NewVD->setStorageClass(SC_Static);
  6185. }
  6186. }
  6187. // Ensure that dllimport globals without explicit storage class are treated as
  6188. // extern. The storage class is set above using parsed attributes. Now we can
  6189. // check the VarDecl itself.
  6190. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6191. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6192. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6193. // In auto-retain/release, infer strong retension for variables of
  6194. // retainable type.
  6195. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6196. NewVD->setInvalidDecl();
  6197. // Handle GNU asm-label extension (encoded as an attribute).
  6198. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6199. // The parser guarantees this is a string.
  6200. StringLiteral *SE = cast<StringLiteral>(E);
  6201. StringRef Label = SE->getString();
  6202. if (S->getFnParent() != nullptr) {
  6203. switch (SC) {
  6204. case SC_None:
  6205. case SC_Auto:
  6206. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6207. break;
  6208. case SC_Register:
  6209. // Local Named register
  6210. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6211. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6212. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6213. break;
  6214. case SC_Static:
  6215. case SC_Extern:
  6216. case SC_PrivateExtern:
  6217. break;
  6218. }
  6219. } else if (SC == SC_Register) {
  6220. // Global Named register
  6221. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6222. const auto &TI = Context.getTargetInfo();
  6223. bool HasSizeMismatch;
  6224. if (!TI.isValidGCCRegisterName(Label))
  6225. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6226. else if (!TI.validateGlobalRegisterVariable(Label,
  6227. Context.getTypeSize(R),
  6228. HasSizeMismatch))
  6229. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6230. else if (HasSizeMismatch)
  6231. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6232. }
  6233. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6234. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6235. NewVD->setInvalidDecl(true);
  6236. }
  6237. }
  6238. NewVD->addAttr(::new (Context) AsmLabelAttr(
  6239. Context, SE->getStrTokenLoc(0), Label, /*IsLiteralLabel=*/true));
  6240. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6241. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6242. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6243. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6244. if (isDeclExternC(NewVD)) {
  6245. NewVD->addAttr(I->second);
  6246. ExtnameUndeclaredIdentifiers.erase(I);
  6247. } else
  6248. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6249. << /*Variable*/1 << NewVD;
  6250. }
  6251. }
  6252. // Find the shadowed declaration before filtering for scope.
  6253. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6254. ? getShadowedDeclaration(NewVD, Previous)
  6255. : nullptr;
  6256. // Don't consider existing declarations that are in a different
  6257. // scope and are out-of-semantic-context declarations (if the new
  6258. // declaration has linkage).
  6259. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6260. D.getCXXScopeSpec().isNotEmpty() ||
  6261. IsMemberSpecialization ||
  6262. IsVariableTemplateSpecialization);
  6263. // Check whether the previous declaration is in the same block scope. This
  6264. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6265. if (getLangOpts().CPlusPlus &&
  6266. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6267. NewVD->setPreviousDeclInSameBlockScope(
  6268. Previous.isSingleResult() && !Previous.isShadowed() &&
  6269. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6270. if (!getLangOpts().CPlusPlus) {
  6271. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6272. } else {
  6273. // If this is an explicit specialization of a static data member, check it.
  6274. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6275. CheckMemberSpecialization(NewVD, Previous))
  6276. NewVD->setInvalidDecl();
  6277. // Merge the decl with the existing one if appropriate.
  6278. if (!Previous.empty()) {
  6279. if (Previous.isSingleResult() &&
  6280. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6281. D.getCXXScopeSpec().isSet()) {
  6282. // The user tried to define a non-static data member
  6283. // out-of-line (C++ [dcl.meaning]p1).
  6284. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6285. << D.getCXXScopeSpec().getRange();
  6286. Previous.clear();
  6287. NewVD->setInvalidDecl();
  6288. }
  6289. } else if (D.getCXXScopeSpec().isSet()) {
  6290. // No previous declaration in the qualifying scope.
  6291. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6292. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6293. << D.getCXXScopeSpec().getRange();
  6294. NewVD->setInvalidDecl();
  6295. }
  6296. if (!IsVariableTemplateSpecialization)
  6297. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6298. if (NewTemplate) {
  6299. VarTemplateDecl *PrevVarTemplate =
  6300. NewVD->getPreviousDecl()
  6301. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6302. : nullptr;
  6303. // Check the template parameter list of this declaration, possibly
  6304. // merging in the template parameter list from the previous variable
  6305. // template declaration.
  6306. if (CheckTemplateParameterList(
  6307. TemplateParams,
  6308. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6309. : nullptr,
  6310. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6311. DC->isDependentContext())
  6312. ? TPC_ClassTemplateMember
  6313. : TPC_VarTemplate))
  6314. NewVD->setInvalidDecl();
  6315. // If we are providing an explicit specialization of a static variable
  6316. // template, make a note of that.
  6317. if (PrevVarTemplate &&
  6318. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6319. PrevVarTemplate->setMemberSpecialization();
  6320. }
  6321. }
  6322. // Diagnose shadowed variables iff this isn't a redeclaration.
  6323. if (ShadowedDecl && !D.isRedeclaration())
  6324. CheckShadow(NewVD, ShadowedDecl, Previous);
  6325. ProcessPragmaWeak(S, NewVD);
  6326. // If this is the first declaration of an extern C variable, update
  6327. // the map of such variables.
  6328. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6329. isIncompleteDeclExternC(*this, NewVD))
  6330. RegisterLocallyScopedExternCDecl(NewVD, S);
  6331. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6332. MangleNumberingContext *MCtx;
  6333. Decl *ManglingContextDecl;
  6334. std::tie(MCtx, ManglingContextDecl) =
  6335. getCurrentMangleNumberContext(NewVD->getDeclContext());
  6336. if (MCtx) {
  6337. Context.setManglingNumber(
  6338. NewVD, MCtx->getManglingNumber(
  6339. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6340. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6341. }
  6342. }
  6343. // Special handling of variable named 'main'.
  6344. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6345. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6346. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6347. // C++ [basic.start.main]p3
  6348. // A program that declares a variable main at global scope is ill-formed.
  6349. if (getLangOpts().CPlusPlus)
  6350. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6351. // In C, and external-linkage variable named main results in undefined
  6352. // behavior.
  6353. else if (NewVD->hasExternalFormalLinkage())
  6354. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6355. }
  6356. if (D.isRedeclaration() && !Previous.empty()) {
  6357. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6358. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6359. D.isFunctionDefinition());
  6360. }
  6361. if (NewTemplate) {
  6362. if (NewVD->isInvalidDecl())
  6363. NewTemplate->setInvalidDecl();
  6364. ActOnDocumentableDecl(NewTemplate);
  6365. return NewTemplate;
  6366. }
  6367. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6368. CompleteMemberSpecialization(NewVD, Previous);
  6369. return NewVD;
  6370. }
  6371. /// Enum describing the %select options in diag::warn_decl_shadow.
  6372. enum ShadowedDeclKind {
  6373. SDK_Local,
  6374. SDK_Global,
  6375. SDK_StaticMember,
  6376. SDK_Field,
  6377. SDK_Typedef,
  6378. SDK_Using
  6379. };
  6380. /// Determine what kind of declaration we're shadowing.
  6381. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6382. const DeclContext *OldDC) {
  6383. if (isa<TypeAliasDecl>(ShadowedDecl))
  6384. return SDK_Using;
  6385. else if (isa<TypedefDecl>(ShadowedDecl))
  6386. return SDK_Typedef;
  6387. else if (isa<RecordDecl>(OldDC))
  6388. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6389. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6390. }
  6391. /// Return the location of the capture if the given lambda captures the given
  6392. /// variable \p VD, or an invalid source location otherwise.
  6393. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6394. const VarDecl *VD) {
  6395. for (const Capture &Capture : LSI->Captures) {
  6396. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6397. return Capture.getLocation();
  6398. }
  6399. return SourceLocation();
  6400. }
  6401. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6402. const LookupResult &R) {
  6403. // Only diagnose if we're shadowing an unambiguous field or variable.
  6404. if (R.getResultKind() != LookupResult::Found)
  6405. return false;
  6406. // Return false if warning is ignored.
  6407. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6408. }
  6409. /// Return the declaration shadowed by the given variable \p D, or null
  6410. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6411. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6412. const LookupResult &R) {
  6413. if (!shouldWarnIfShadowedDecl(Diags, R))
  6414. return nullptr;
  6415. // Don't diagnose declarations at file scope.
  6416. if (D->hasGlobalStorage())
  6417. return nullptr;
  6418. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6419. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6420. ? ShadowedDecl
  6421. : nullptr;
  6422. }
  6423. /// Return the declaration shadowed by the given typedef \p D, or null
  6424. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6425. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6426. const LookupResult &R) {
  6427. // Don't warn if typedef declaration is part of a class
  6428. if (D->getDeclContext()->isRecord())
  6429. return nullptr;
  6430. if (!shouldWarnIfShadowedDecl(Diags, R))
  6431. return nullptr;
  6432. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6433. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6434. }
  6435. /// Diagnose variable or built-in function shadowing. Implements
  6436. /// -Wshadow.
  6437. ///
  6438. /// This method is called whenever a VarDecl is added to a "useful"
  6439. /// scope.
  6440. ///
  6441. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6442. /// \param R the lookup of the name
  6443. ///
  6444. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6445. const LookupResult &R) {
  6446. DeclContext *NewDC = D->getDeclContext();
  6447. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6448. // Fields are not shadowed by variables in C++ static methods.
  6449. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6450. if (MD->isStatic())
  6451. return;
  6452. // Fields shadowed by constructor parameters are a special case. Usually
  6453. // the constructor initializes the field with the parameter.
  6454. if (isa<CXXConstructorDecl>(NewDC))
  6455. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6456. // Remember that this was shadowed so we can either warn about its
  6457. // modification or its existence depending on warning settings.
  6458. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6459. return;
  6460. }
  6461. }
  6462. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6463. if (shadowedVar->isExternC()) {
  6464. // For shadowing external vars, make sure that we point to the global
  6465. // declaration, not a locally scoped extern declaration.
  6466. for (auto I : shadowedVar->redecls())
  6467. if (I->isFileVarDecl()) {
  6468. ShadowedDecl = I;
  6469. break;
  6470. }
  6471. }
  6472. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6473. unsigned WarningDiag = diag::warn_decl_shadow;
  6474. SourceLocation CaptureLoc;
  6475. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6476. isa<CXXMethodDecl>(NewDC)) {
  6477. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6478. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6479. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6480. // Try to avoid warnings for lambdas with an explicit capture list.
  6481. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6482. // Warn only when the lambda captures the shadowed decl explicitly.
  6483. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6484. if (CaptureLoc.isInvalid())
  6485. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6486. } else {
  6487. // Remember that this was shadowed so we can avoid the warning if the
  6488. // shadowed decl isn't captured and the warning settings allow it.
  6489. cast<LambdaScopeInfo>(getCurFunction())
  6490. ->ShadowingDecls.push_back(
  6491. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6492. return;
  6493. }
  6494. }
  6495. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6496. // A variable can't shadow a local variable in an enclosing scope, if
  6497. // they are separated by a non-capturing declaration context.
  6498. for (DeclContext *ParentDC = NewDC;
  6499. ParentDC && !ParentDC->Equals(OldDC);
  6500. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6501. // Only block literals, captured statements, and lambda expressions
  6502. // can capture; other scopes don't.
  6503. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6504. !isLambdaCallOperator(ParentDC)) {
  6505. return;
  6506. }
  6507. }
  6508. }
  6509. }
  6510. }
  6511. // Only warn about certain kinds of shadowing for class members.
  6512. if (NewDC && NewDC->isRecord()) {
  6513. // In particular, don't warn about shadowing non-class members.
  6514. if (!OldDC->isRecord())
  6515. return;
  6516. // TODO: should we warn about static data members shadowing
  6517. // static data members from base classes?
  6518. // TODO: don't diagnose for inaccessible shadowed members.
  6519. // This is hard to do perfectly because we might friend the
  6520. // shadowing context, but that's just a false negative.
  6521. }
  6522. DeclarationName Name = R.getLookupName();
  6523. // Emit warning and note.
  6524. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6525. return;
  6526. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6527. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6528. if (!CaptureLoc.isInvalid())
  6529. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6530. << Name << /*explicitly*/ 1;
  6531. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6532. }
  6533. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6534. /// when these variables are captured by the lambda.
  6535. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6536. for (const auto &Shadow : LSI->ShadowingDecls) {
  6537. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6538. // Try to avoid the warning when the shadowed decl isn't captured.
  6539. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6540. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6541. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6542. ? diag::warn_decl_shadow_uncaptured_local
  6543. : diag::warn_decl_shadow)
  6544. << Shadow.VD->getDeclName()
  6545. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6546. if (!CaptureLoc.isInvalid())
  6547. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6548. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6549. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6550. }
  6551. }
  6552. /// Check -Wshadow without the advantage of a previous lookup.
  6553. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6554. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6555. return;
  6556. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6557. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6558. LookupName(R, S);
  6559. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6560. CheckShadow(D, ShadowedDecl, R);
  6561. }
  6562. /// Check if 'E', which is an expression that is about to be modified, refers
  6563. /// to a constructor parameter that shadows a field.
  6564. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6565. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6566. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6567. return;
  6568. E = E->IgnoreParenImpCasts();
  6569. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6570. if (!DRE)
  6571. return;
  6572. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6573. auto I = ShadowingDecls.find(D);
  6574. if (I == ShadowingDecls.end())
  6575. return;
  6576. const NamedDecl *ShadowedDecl = I->second;
  6577. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6578. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6579. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6580. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6581. // Avoid issuing multiple warnings about the same decl.
  6582. ShadowingDecls.erase(I);
  6583. }
  6584. /// Check for conflict between this global or extern "C" declaration and
  6585. /// previous global or extern "C" declarations. This is only used in C++.
  6586. template<typename T>
  6587. static bool checkGlobalOrExternCConflict(
  6588. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6589. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6590. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6591. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6592. // The common case: this global doesn't conflict with any extern "C"
  6593. // declaration.
  6594. return false;
  6595. }
  6596. if (Prev) {
  6597. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6598. // Both the old and new declarations have C language linkage. This is a
  6599. // redeclaration.
  6600. Previous.clear();
  6601. Previous.addDecl(Prev);
  6602. return true;
  6603. }
  6604. // This is a global, non-extern "C" declaration, and there is a previous
  6605. // non-global extern "C" declaration. Diagnose if this is a variable
  6606. // declaration.
  6607. if (!isa<VarDecl>(ND))
  6608. return false;
  6609. } else {
  6610. // The declaration is extern "C". Check for any declaration in the
  6611. // translation unit which might conflict.
  6612. if (IsGlobal) {
  6613. // We have already performed the lookup into the translation unit.
  6614. IsGlobal = false;
  6615. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6616. I != E; ++I) {
  6617. if (isa<VarDecl>(*I)) {
  6618. Prev = *I;
  6619. break;
  6620. }
  6621. }
  6622. } else {
  6623. DeclContext::lookup_result R =
  6624. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6625. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6626. I != E; ++I) {
  6627. if (isa<VarDecl>(*I)) {
  6628. Prev = *I;
  6629. break;
  6630. }
  6631. // FIXME: If we have any other entity with this name in global scope,
  6632. // the declaration is ill-formed, but that is a defect: it breaks the
  6633. // 'stat' hack, for instance. Only variables can have mangled name
  6634. // clashes with extern "C" declarations, so only they deserve a
  6635. // diagnostic.
  6636. }
  6637. }
  6638. if (!Prev)
  6639. return false;
  6640. }
  6641. // Use the first declaration's location to ensure we point at something which
  6642. // is lexically inside an extern "C" linkage-spec.
  6643. assert(Prev && "should have found a previous declaration to diagnose");
  6644. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6645. Prev = FD->getFirstDecl();
  6646. else
  6647. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6648. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6649. << IsGlobal << ND;
  6650. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6651. << IsGlobal;
  6652. return false;
  6653. }
  6654. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6655. /// if we have found that this is a redeclaration of some prior entity.
  6656. ///
  6657. /// Per C++ [dcl.link]p6:
  6658. /// Two declarations [for a function or variable] with C language linkage
  6659. /// with the same name that appear in different scopes refer to the same
  6660. /// [entity]. An entity with C language linkage shall not be declared with
  6661. /// the same name as an entity in global scope.
  6662. template<typename T>
  6663. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6664. LookupResult &Previous) {
  6665. if (!S.getLangOpts().CPlusPlus) {
  6666. // In C, when declaring a global variable, look for a corresponding 'extern'
  6667. // variable declared in function scope. We don't need this in C++, because
  6668. // we find local extern decls in the surrounding file-scope DeclContext.
  6669. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6670. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6671. Previous.clear();
  6672. Previous.addDecl(Prev);
  6673. return true;
  6674. }
  6675. }
  6676. return false;
  6677. }
  6678. // A declaration in the translation unit can conflict with an extern "C"
  6679. // declaration.
  6680. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6681. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6682. // An extern "C" declaration can conflict with a declaration in the
  6683. // translation unit or can be a redeclaration of an extern "C" declaration
  6684. // in another scope.
  6685. if (isIncompleteDeclExternC(S,ND))
  6686. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6687. // Neither global nor extern "C": nothing to do.
  6688. return false;
  6689. }
  6690. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6691. // If the decl is already known invalid, don't check it.
  6692. if (NewVD->isInvalidDecl())
  6693. return;
  6694. QualType T = NewVD->getType();
  6695. // Defer checking an 'auto' type until its initializer is attached.
  6696. if (T->isUndeducedType())
  6697. return;
  6698. if (NewVD->hasAttrs())
  6699. CheckAlignasUnderalignment(NewVD);
  6700. if (T->isObjCObjectType()) {
  6701. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6702. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6703. T = Context.getObjCObjectPointerType(T);
  6704. NewVD->setType(T);
  6705. }
  6706. // Emit an error if an address space was applied to decl with local storage.
  6707. // This includes arrays of objects with address space qualifiers, but not
  6708. // automatic variables that point to other address spaces.
  6709. // ISO/IEC TR 18037 S5.1.2
  6710. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6711. T.getAddressSpace() != LangAS::Default) {
  6712. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6713. NewVD->setInvalidDecl();
  6714. return;
  6715. }
  6716. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6717. // scope.
  6718. if (getLangOpts().OpenCLVersion == 120 &&
  6719. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6720. NewVD->isStaticLocal()) {
  6721. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6722. NewVD->setInvalidDecl();
  6723. return;
  6724. }
  6725. if (getLangOpts().OpenCL) {
  6726. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6727. if (NewVD->hasAttr<BlocksAttr>()) {
  6728. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6729. return;
  6730. }
  6731. if (T->isBlockPointerType()) {
  6732. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6733. // can't use 'extern' storage class.
  6734. if (!T.isConstQualified()) {
  6735. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6736. << 0 /*const*/;
  6737. NewVD->setInvalidDecl();
  6738. return;
  6739. }
  6740. if (NewVD->hasExternalStorage()) {
  6741. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6742. NewVD->setInvalidDecl();
  6743. return;
  6744. }
  6745. }
  6746. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6747. // __constant address space.
  6748. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6749. // variables inside a function can also be declared in the global
  6750. // address space.
  6751. // C++ for OpenCL inherits rule from OpenCL C v2.0.
  6752. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  6753. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6754. NewVD->hasExternalStorage()) {
  6755. if (!T->isSamplerT() &&
  6756. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6757. (T.getAddressSpace() == LangAS::opencl_global &&
  6758. (getLangOpts().OpenCLVersion == 200 ||
  6759. getLangOpts().OpenCLCPlusPlus)))) {
  6760. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6761. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6762. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6763. << Scope << "global or constant";
  6764. else
  6765. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6766. << Scope << "constant";
  6767. NewVD->setInvalidDecl();
  6768. return;
  6769. }
  6770. } else {
  6771. if (T.getAddressSpace() == LangAS::opencl_global) {
  6772. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6773. << 1 /*is any function*/ << "global";
  6774. NewVD->setInvalidDecl();
  6775. return;
  6776. }
  6777. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6778. T.getAddressSpace() == LangAS::opencl_local) {
  6779. FunctionDecl *FD = getCurFunctionDecl();
  6780. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6781. // in functions.
  6782. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6783. if (T.getAddressSpace() == LangAS::opencl_constant)
  6784. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6785. << 0 /*non-kernel only*/ << "constant";
  6786. else
  6787. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6788. << 0 /*non-kernel only*/ << "local";
  6789. NewVD->setInvalidDecl();
  6790. return;
  6791. }
  6792. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6793. // in the outermost scope of a kernel function.
  6794. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6795. if (!getCurScope()->isFunctionScope()) {
  6796. if (T.getAddressSpace() == LangAS::opencl_constant)
  6797. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6798. << "constant";
  6799. else
  6800. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6801. << "local";
  6802. NewVD->setInvalidDecl();
  6803. return;
  6804. }
  6805. }
  6806. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  6807. // If we are parsing a template we didn't deduce an addr
  6808. // space yet.
  6809. T.getAddressSpace() != LangAS::Default) {
  6810. // Do not allow other address spaces on automatic variable.
  6811. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6812. NewVD->setInvalidDecl();
  6813. return;
  6814. }
  6815. }
  6816. }
  6817. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6818. && !NewVD->hasAttr<BlocksAttr>()) {
  6819. if (getLangOpts().getGC() != LangOptions::NonGC)
  6820. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6821. else {
  6822. assert(!getLangOpts().ObjCAutoRefCount);
  6823. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6824. }
  6825. }
  6826. bool isVM = T->isVariablyModifiedType();
  6827. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6828. NewVD->hasAttr<BlocksAttr>())
  6829. setFunctionHasBranchProtectedScope();
  6830. if ((isVM && NewVD->hasLinkage()) ||
  6831. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6832. bool SizeIsNegative;
  6833. llvm::APSInt Oversized;
  6834. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6835. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6836. QualType FixedT;
  6837. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6838. FixedT = FixedTInfo->getType();
  6839. else if (FixedTInfo) {
  6840. // Type and type-as-written are canonically different. We need to fix up
  6841. // both types separately.
  6842. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6843. Oversized);
  6844. }
  6845. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6846. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6847. // FIXME: This won't give the correct result for
  6848. // int a[10][n];
  6849. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6850. if (NewVD->isFileVarDecl())
  6851. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6852. << SizeRange;
  6853. else if (NewVD->isStaticLocal())
  6854. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6855. << SizeRange;
  6856. else
  6857. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6858. << SizeRange;
  6859. NewVD->setInvalidDecl();
  6860. return;
  6861. }
  6862. if (!FixedTInfo) {
  6863. if (NewVD->isFileVarDecl())
  6864. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6865. else
  6866. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6867. NewVD->setInvalidDecl();
  6868. return;
  6869. }
  6870. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6871. NewVD->setType(FixedT);
  6872. NewVD->setTypeSourceInfo(FixedTInfo);
  6873. }
  6874. if (T->isVoidType()) {
  6875. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6876. // of objects and functions.
  6877. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6878. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6879. << T;
  6880. NewVD->setInvalidDecl();
  6881. return;
  6882. }
  6883. }
  6884. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6885. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6886. NewVD->setInvalidDecl();
  6887. return;
  6888. }
  6889. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6890. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6891. NewVD->setInvalidDecl();
  6892. return;
  6893. }
  6894. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6895. RequireLiteralType(NewVD->getLocation(), T,
  6896. diag::err_constexpr_var_non_literal)) {
  6897. NewVD->setInvalidDecl();
  6898. return;
  6899. }
  6900. }
  6901. /// Perform semantic checking on a newly-created variable
  6902. /// declaration.
  6903. ///
  6904. /// This routine performs all of the type-checking required for a
  6905. /// variable declaration once it has been built. It is used both to
  6906. /// check variables after they have been parsed and their declarators
  6907. /// have been translated into a declaration, and to check variables
  6908. /// that have been instantiated from a template.
  6909. ///
  6910. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6911. ///
  6912. /// Returns true if the variable declaration is a redeclaration.
  6913. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6914. CheckVariableDeclarationType(NewVD);
  6915. // If the decl is already known invalid, don't check it.
  6916. if (NewVD->isInvalidDecl())
  6917. return false;
  6918. // If we did not find anything by this name, look for a non-visible
  6919. // extern "C" declaration with the same name.
  6920. if (Previous.empty() &&
  6921. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6922. Previous.setShadowed();
  6923. if (!Previous.empty()) {
  6924. MergeVarDecl(NewVD, Previous);
  6925. return true;
  6926. }
  6927. return false;
  6928. }
  6929. namespace {
  6930. struct FindOverriddenMethod {
  6931. Sema *S;
  6932. CXXMethodDecl *Method;
  6933. /// Member lookup function that determines whether a given C++
  6934. /// method overrides a method in a base class, to be used with
  6935. /// CXXRecordDecl::lookupInBases().
  6936. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6937. RecordDecl *BaseRecord =
  6938. Specifier->getType()->castAs<RecordType>()->getDecl();
  6939. DeclarationName Name = Method->getDeclName();
  6940. // FIXME: Do we care about other names here too?
  6941. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6942. // We really want to find the base class destructor here.
  6943. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6944. CanQualType CT = S->Context.getCanonicalType(T);
  6945. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6946. }
  6947. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6948. Path.Decls = Path.Decls.slice(1)) {
  6949. NamedDecl *D = Path.Decls.front();
  6950. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6951. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6952. return true;
  6953. }
  6954. }
  6955. return false;
  6956. }
  6957. };
  6958. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6959. } // end anonymous namespace
  6960. /// Report an error regarding overriding, along with any relevant
  6961. /// overridden methods.
  6962. ///
  6963. /// \param DiagID the primary error to report.
  6964. /// \param MD the overriding method.
  6965. /// \param OEK which overrides to include as notes.
  6966. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6967. OverrideErrorKind OEK = OEK_All) {
  6968. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6969. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6970. // This check (& the OEK parameter) could be replaced by a predicate, but
  6971. // without lambdas that would be overkill. This is still nicer than writing
  6972. // out the diag loop 3 times.
  6973. if ((OEK == OEK_All) ||
  6974. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6975. (OEK == OEK_Deleted && O->isDeleted()))
  6976. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6977. }
  6978. }
  6979. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6980. /// and if so, check that it's a valid override and remember it.
  6981. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6982. // Look for methods in base classes that this method might override.
  6983. CXXBasePaths Paths;
  6984. FindOverriddenMethod FOM;
  6985. FOM.Method = MD;
  6986. FOM.S = this;
  6987. bool hasDeletedOverridenMethods = false;
  6988. bool hasNonDeletedOverridenMethods = false;
  6989. bool AddedAny = false;
  6990. if (DC->lookupInBases(FOM, Paths)) {
  6991. for (auto *I : Paths.found_decls()) {
  6992. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6993. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6994. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6995. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6996. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6997. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6998. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6999. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  7000. AddedAny = true;
  7001. }
  7002. }
  7003. }
  7004. }
  7005. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  7006. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  7007. }
  7008. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  7009. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  7010. }
  7011. return AddedAny;
  7012. }
  7013. namespace {
  7014. // Struct for holding all of the extra arguments needed by
  7015. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  7016. struct ActOnFDArgs {
  7017. Scope *S;
  7018. Declarator &D;
  7019. MultiTemplateParamsArg TemplateParamLists;
  7020. bool AddToScope;
  7021. };
  7022. } // end anonymous namespace
  7023. namespace {
  7024. // Callback to only accept typo corrections that have a non-zero edit distance.
  7025. // Also only accept corrections that have the same parent decl.
  7026. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  7027. public:
  7028. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  7029. CXXRecordDecl *Parent)
  7030. : Context(Context), OriginalFD(TypoFD),
  7031. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  7032. bool ValidateCandidate(const TypoCorrection &candidate) override {
  7033. if (candidate.getEditDistance() == 0)
  7034. return false;
  7035. SmallVector<unsigned, 1> MismatchedParams;
  7036. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  7037. CDeclEnd = candidate.end();
  7038. CDecl != CDeclEnd; ++CDecl) {
  7039. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7040. if (FD && !FD->hasBody() &&
  7041. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  7042. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  7043. CXXRecordDecl *Parent = MD->getParent();
  7044. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  7045. return true;
  7046. } else if (!ExpectedParent) {
  7047. return true;
  7048. }
  7049. }
  7050. }
  7051. return false;
  7052. }
  7053. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  7054. return std::make_unique<DifferentNameValidatorCCC>(*this);
  7055. }
  7056. private:
  7057. ASTContext &Context;
  7058. FunctionDecl *OriginalFD;
  7059. CXXRecordDecl *ExpectedParent;
  7060. };
  7061. } // end anonymous namespace
  7062. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7063. TypoCorrectedFunctionDefinitions.insert(F);
  7064. }
  7065. /// Generate diagnostics for an invalid function redeclaration.
  7066. ///
  7067. /// This routine handles generating the diagnostic messages for an invalid
  7068. /// function redeclaration, including finding possible similar declarations
  7069. /// or performing typo correction if there are no previous declarations with
  7070. /// the same name.
  7071. ///
  7072. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7073. /// the new declaration name does not cause new errors.
  7074. static NamedDecl *DiagnoseInvalidRedeclaration(
  7075. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7076. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7077. DeclarationName Name = NewFD->getDeclName();
  7078. DeclContext *NewDC = NewFD->getDeclContext();
  7079. SmallVector<unsigned, 1> MismatchedParams;
  7080. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7081. TypoCorrection Correction;
  7082. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7083. unsigned DiagMsg =
  7084. IsLocalFriend ? diag::err_no_matching_local_friend :
  7085. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7086. diag::err_member_decl_does_not_match;
  7087. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7088. IsLocalFriend ? Sema::LookupLocalFriendName
  7089. : Sema::LookupOrdinaryName,
  7090. Sema::ForVisibleRedeclaration);
  7091. NewFD->setInvalidDecl();
  7092. if (IsLocalFriend)
  7093. SemaRef.LookupName(Prev, S);
  7094. else
  7095. SemaRef.LookupQualifiedName(Prev, NewDC);
  7096. assert(!Prev.isAmbiguous() &&
  7097. "Cannot have an ambiguity in previous-declaration lookup");
  7098. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7099. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7100. MD ? MD->getParent() : nullptr);
  7101. if (!Prev.empty()) {
  7102. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7103. Func != FuncEnd; ++Func) {
  7104. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7105. if (FD &&
  7106. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7107. // Add 1 to the index so that 0 can mean the mismatch didn't
  7108. // involve a parameter
  7109. unsigned ParamNum =
  7110. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7111. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7112. }
  7113. }
  7114. // If the qualified name lookup yielded nothing, try typo correction
  7115. } else if ((Correction = SemaRef.CorrectTypo(
  7116. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7117. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7118. IsLocalFriend ? nullptr : NewDC))) {
  7119. // Set up everything for the call to ActOnFunctionDeclarator
  7120. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7121. ExtraArgs.D.getIdentifierLoc());
  7122. Previous.clear();
  7123. Previous.setLookupName(Correction.getCorrection());
  7124. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7125. CDeclEnd = Correction.end();
  7126. CDecl != CDeclEnd; ++CDecl) {
  7127. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7128. if (FD && !FD->hasBody() &&
  7129. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7130. Previous.addDecl(FD);
  7131. }
  7132. }
  7133. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7134. NamedDecl *Result;
  7135. // Retry building the function declaration with the new previous
  7136. // declarations, and with errors suppressed.
  7137. {
  7138. // Trap errors.
  7139. Sema::SFINAETrap Trap(SemaRef);
  7140. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7141. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7142. // eliminate the need for the parameter pack ExtraArgs.
  7143. Result = SemaRef.ActOnFunctionDeclarator(
  7144. ExtraArgs.S, ExtraArgs.D,
  7145. Correction.getCorrectionDecl()->getDeclContext(),
  7146. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7147. ExtraArgs.AddToScope);
  7148. if (Trap.hasErrorOccurred())
  7149. Result = nullptr;
  7150. }
  7151. if (Result) {
  7152. // Determine which correction we picked.
  7153. Decl *Canonical = Result->getCanonicalDecl();
  7154. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7155. I != E; ++I)
  7156. if ((*I)->getCanonicalDecl() == Canonical)
  7157. Correction.setCorrectionDecl(*I);
  7158. // Let Sema know about the correction.
  7159. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7160. SemaRef.diagnoseTypo(
  7161. Correction,
  7162. SemaRef.PDiag(IsLocalFriend
  7163. ? diag::err_no_matching_local_friend_suggest
  7164. : diag::err_member_decl_does_not_match_suggest)
  7165. << Name << NewDC << IsDefinition);
  7166. return Result;
  7167. }
  7168. // Pretend the typo correction never occurred
  7169. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7170. ExtraArgs.D.getIdentifierLoc());
  7171. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7172. Previous.clear();
  7173. Previous.setLookupName(Name);
  7174. }
  7175. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7176. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7177. bool NewFDisConst = false;
  7178. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7179. NewFDisConst = NewMD->isConst();
  7180. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7181. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7182. NearMatch != NearMatchEnd; ++NearMatch) {
  7183. FunctionDecl *FD = NearMatch->first;
  7184. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7185. bool FDisConst = MD && MD->isConst();
  7186. bool IsMember = MD || !IsLocalFriend;
  7187. // FIXME: These notes are poorly worded for the local friend case.
  7188. if (unsigned Idx = NearMatch->second) {
  7189. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7190. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7191. if (Loc.isInvalid()) Loc = FD->getLocation();
  7192. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7193. : diag::note_local_decl_close_param_match)
  7194. << Idx << FDParam->getType()
  7195. << NewFD->getParamDecl(Idx - 1)->getType();
  7196. } else if (FDisConst != NewFDisConst) {
  7197. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7198. << NewFDisConst << FD->getSourceRange().getEnd();
  7199. } else
  7200. SemaRef.Diag(FD->getLocation(),
  7201. IsMember ? diag::note_member_def_close_match
  7202. : diag::note_local_decl_close_match);
  7203. }
  7204. return nullptr;
  7205. }
  7206. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7207. switch (D.getDeclSpec().getStorageClassSpec()) {
  7208. default: llvm_unreachable("Unknown storage class!");
  7209. case DeclSpec::SCS_auto:
  7210. case DeclSpec::SCS_register:
  7211. case DeclSpec::SCS_mutable:
  7212. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7213. diag::err_typecheck_sclass_func);
  7214. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7215. D.setInvalidType();
  7216. break;
  7217. case DeclSpec::SCS_unspecified: break;
  7218. case DeclSpec::SCS_extern:
  7219. if (D.getDeclSpec().isExternInLinkageSpec())
  7220. return SC_None;
  7221. return SC_Extern;
  7222. case DeclSpec::SCS_static: {
  7223. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7224. // C99 6.7.1p5:
  7225. // The declaration of an identifier for a function that has
  7226. // block scope shall have no explicit storage-class specifier
  7227. // other than extern
  7228. // See also (C++ [dcl.stc]p4).
  7229. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7230. diag::err_static_block_func);
  7231. break;
  7232. } else
  7233. return SC_Static;
  7234. }
  7235. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7236. }
  7237. // No explicit storage class has already been returned
  7238. return SC_None;
  7239. }
  7240. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7241. DeclContext *DC, QualType &R,
  7242. TypeSourceInfo *TInfo,
  7243. StorageClass SC,
  7244. bool &IsVirtualOkay) {
  7245. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7246. DeclarationName Name = NameInfo.getName();
  7247. FunctionDecl *NewFD = nullptr;
  7248. bool isInline = D.getDeclSpec().isInlineSpecified();
  7249. if (!SemaRef.getLangOpts().CPlusPlus) {
  7250. // Determine whether the function was written with a
  7251. // prototype. This true when:
  7252. // - there is a prototype in the declarator, or
  7253. // - the type R of the function is some kind of typedef or other non-
  7254. // attributed reference to a type name (which eventually refers to a
  7255. // function type).
  7256. bool HasPrototype =
  7257. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7258. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7259. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7260. R, TInfo, SC, isInline, HasPrototype,
  7261. CSK_unspecified);
  7262. if (D.isInvalidType())
  7263. NewFD->setInvalidDecl();
  7264. return NewFD;
  7265. }
  7266. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7267. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7268. if (ConstexprKind == CSK_constinit) {
  7269. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7270. diag::err_constexpr_wrong_decl_kind)
  7271. << ConstexprKind;
  7272. ConstexprKind = CSK_unspecified;
  7273. D.getMutableDeclSpec().ClearConstexprSpec();
  7274. }
  7275. // Check that the return type is not an abstract class type.
  7276. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7277. // the class has been completely parsed.
  7278. if (!DC->isRecord() &&
  7279. SemaRef.RequireNonAbstractType(
  7280. D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
  7281. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7282. D.setInvalidType();
  7283. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7284. // This is a C++ constructor declaration.
  7285. assert(DC->isRecord() &&
  7286. "Constructors can only be declared in a member context");
  7287. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7288. return CXXConstructorDecl::Create(
  7289. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7290. TInfo, ExplicitSpecifier, isInline,
  7291. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7292. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7293. // This is a C++ destructor declaration.
  7294. if (DC->isRecord()) {
  7295. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7296. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7297. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7298. SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
  7299. isInline,
  7300. /*isImplicitlyDeclared=*/false, ConstexprKind);
  7301. // If the destructor needs an implicit exception specification, set it
  7302. // now. FIXME: It'd be nice to be able to create the right type to start
  7303. // with, but the type needs to reference the destructor declaration.
  7304. if (SemaRef.getLangOpts().CPlusPlus11)
  7305. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7306. IsVirtualOkay = true;
  7307. return NewDD;
  7308. } else {
  7309. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7310. D.setInvalidType();
  7311. // Create a FunctionDecl to satisfy the function definition parsing
  7312. // code path.
  7313. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7314. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7315. isInline,
  7316. /*hasPrototype=*/true, ConstexprKind);
  7317. }
  7318. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7319. if (!DC->isRecord()) {
  7320. SemaRef.Diag(D.getIdentifierLoc(),
  7321. diag::err_conv_function_not_member);
  7322. return nullptr;
  7323. }
  7324. SemaRef.CheckConversionDeclarator(D, R, SC);
  7325. if (D.isInvalidType())
  7326. return nullptr;
  7327. IsVirtualOkay = true;
  7328. return CXXConversionDecl::Create(
  7329. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7330. TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation());
  7331. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7332. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7333. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7334. ExplicitSpecifier, NameInfo, R, TInfo,
  7335. D.getEndLoc());
  7336. } else if (DC->isRecord()) {
  7337. // If the name of the function is the same as the name of the record,
  7338. // then this must be an invalid constructor that has a return type.
  7339. // (The parser checks for a return type and makes the declarator a
  7340. // constructor if it has no return type).
  7341. if (Name.getAsIdentifierInfo() &&
  7342. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7343. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7344. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7345. << SourceRange(D.getIdentifierLoc());
  7346. return nullptr;
  7347. }
  7348. // This is a C++ method declaration.
  7349. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7350. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7351. TInfo, SC, isInline, ConstexprKind, SourceLocation());
  7352. IsVirtualOkay = !Ret->isStatic();
  7353. return Ret;
  7354. } else {
  7355. bool isFriend =
  7356. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7357. if (!isFriend && SemaRef.CurContext->isRecord())
  7358. return nullptr;
  7359. // Determine whether the function was written with a
  7360. // prototype. This true when:
  7361. // - we're in C++ (where every function has a prototype),
  7362. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7363. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7364. ConstexprKind);
  7365. }
  7366. }
  7367. enum OpenCLParamType {
  7368. ValidKernelParam,
  7369. PtrPtrKernelParam,
  7370. PtrKernelParam,
  7371. InvalidAddrSpacePtrKernelParam,
  7372. InvalidKernelParam,
  7373. RecordKernelParam
  7374. };
  7375. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7376. // Size dependent types are just typedefs to normal integer types
  7377. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7378. // integers other than by their names.
  7379. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7380. // Remove typedefs one by one until we reach a typedef
  7381. // for a size dependent type.
  7382. QualType DesugaredTy = Ty;
  7383. do {
  7384. ArrayRef<StringRef> Names(SizeTypeNames);
  7385. auto Match = llvm::find(Names, DesugaredTy.getAsString());
  7386. if (Names.end() != Match)
  7387. return true;
  7388. Ty = DesugaredTy;
  7389. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7390. } while (DesugaredTy != Ty);
  7391. return false;
  7392. }
  7393. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7394. if (PT->isPointerType()) {
  7395. QualType PointeeType = PT->getPointeeType();
  7396. if (PointeeType->isPointerType())
  7397. return PtrPtrKernelParam;
  7398. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7399. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7400. PointeeType.getAddressSpace() == LangAS::Default)
  7401. return InvalidAddrSpacePtrKernelParam;
  7402. return PtrKernelParam;
  7403. }
  7404. // OpenCL v1.2 s6.9.k:
  7405. // Arguments to kernel functions in a program cannot be declared with the
  7406. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7407. // uintptr_t or a struct and/or union that contain fields declared to be one
  7408. // of these built-in scalar types.
  7409. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7410. return InvalidKernelParam;
  7411. if (PT->isImageType())
  7412. return PtrKernelParam;
  7413. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7414. return InvalidKernelParam;
  7415. // OpenCL extension spec v1.2 s9.5:
  7416. // This extension adds support for half scalar and vector types as built-in
  7417. // types that can be used for arithmetic operations, conversions etc.
  7418. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7419. return InvalidKernelParam;
  7420. if (PT->isRecordType())
  7421. return RecordKernelParam;
  7422. // Look into an array argument to check if it has a forbidden type.
  7423. if (PT->isArrayType()) {
  7424. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7425. // Call ourself to check an underlying type of an array. Since the
  7426. // getPointeeOrArrayElementType returns an innermost type which is not an
  7427. // array, this recursive call only happens once.
  7428. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7429. }
  7430. return ValidKernelParam;
  7431. }
  7432. static void checkIsValidOpenCLKernelParameter(
  7433. Sema &S,
  7434. Declarator &D,
  7435. ParmVarDecl *Param,
  7436. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7437. QualType PT = Param->getType();
  7438. // Cache the valid types we encounter to avoid rechecking structs that are
  7439. // used again
  7440. if (ValidTypes.count(PT.getTypePtr()))
  7441. return;
  7442. switch (getOpenCLKernelParameterType(S, PT)) {
  7443. case PtrPtrKernelParam:
  7444. // OpenCL v1.2 s6.9.a:
  7445. // A kernel function argument cannot be declared as a
  7446. // pointer to a pointer type.
  7447. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7448. D.setInvalidType();
  7449. return;
  7450. case InvalidAddrSpacePtrKernelParam:
  7451. // OpenCL v1.0 s6.5:
  7452. // __kernel function arguments declared to be a pointer of a type can point
  7453. // to one of the following address spaces only : __global, __local or
  7454. // __constant.
  7455. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7456. D.setInvalidType();
  7457. return;
  7458. // OpenCL v1.2 s6.9.k:
  7459. // Arguments to kernel functions in a program cannot be declared with the
  7460. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7461. // uintptr_t or a struct and/or union that contain fields declared to be
  7462. // one of these built-in scalar types.
  7463. case InvalidKernelParam:
  7464. // OpenCL v1.2 s6.8 n:
  7465. // A kernel function argument cannot be declared
  7466. // of event_t type.
  7467. // Do not diagnose half type since it is diagnosed as invalid argument
  7468. // type for any function elsewhere.
  7469. if (!PT->isHalfType()) {
  7470. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7471. // Explain what typedefs are involved.
  7472. const TypedefType *Typedef = nullptr;
  7473. while ((Typedef = PT->getAs<TypedefType>())) {
  7474. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7475. // SourceLocation may be invalid for a built-in type.
  7476. if (Loc.isValid())
  7477. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7478. PT = Typedef->desugar();
  7479. }
  7480. }
  7481. D.setInvalidType();
  7482. return;
  7483. case PtrKernelParam:
  7484. case ValidKernelParam:
  7485. ValidTypes.insert(PT.getTypePtr());
  7486. return;
  7487. case RecordKernelParam:
  7488. break;
  7489. }
  7490. // Track nested structs we will inspect
  7491. SmallVector<const Decl *, 4> VisitStack;
  7492. // Track where we are in the nested structs. Items will migrate from
  7493. // VisitStack to HistoryStack as we do the DFS for bad field.
  7494. SmallVector<const FieldDecl *, 4> HistoryStack;
  7495. HistoryStack.push_back(nullptr);
  7496. // At this point we already handled everything except of a RecordType or
  7497. // an ArrayType of a RecordType.
  7498. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7499. const RecordType *RecTy =
  7500. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7501. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7502. VisitStack.push_back(RecTy->getDecl());
  7503. assert(VisitStack.back() && "First decl null?");
  7504. do {
  7505. const Decl *Next = VisitStack.pop_back_val();
  7506. if (!Next) {
  7507. assert(!HistoryStack.empty());
  7508. // Found a marker, we have gone up a level
  7509. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7510. ValidTypes.insert(Hist->getType().getTypePtr());
  7511. continue;
  7512. }
  7513. // Adds everything except the original parameter declaration (which is not a
  7514. // field itself) to the history stack.
  7515. const RecordDecl *RD;
  7516. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7517. HistoryStack.push_back(Field);
  7518. QualType FieldTy = Field->getType();
  7519. // Other field types (known to be valid or invalid) are handled while we
  7520. // walk around RecordDecl::fields().
  7521. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7522. "Unexpected type.");
  7523. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7524. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7525. } else {
  7526. RD = cast<RecordDecl>(Next);
  7527. }
  7528. // Add a null marker so we know when we've gone back up a level
  7529. VisitStack.push_back(nullptr);
  7530. for (const auto *FD : RD->fields()) {
  7531. QualType QT = FD->getType();
  7532. if (ValidTypes.count(QT.getTypePtr()))
  7533. continue;
  7534. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7535. if (ParamType == ValidKernelParam)
  7536. continue;
  7537. if (ParamType == RecordKernelParam) {
  7538. VisitStack.push_back(FD);
  7539. continue;
  7540. }
  7541. // OpenCL v1.2 s6.9.p:
  7542. // Arguments to kernel functions that are declared to be a struct or union
  7543. // do not allow OpenCL objects to be passed as elements of the struct or
  7544. // union.
  7545. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7546. ParamType == InvalidAddrSpacePtrKernelParam) {
  7547. S.Diag(Param->getLocation(),
  7548. diag::err_record_with_pointers_kernel_param)
  7549. << PT->isUnionType()
  7550. << PT;
  7551. } else {
  7552. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7553. }
  7554. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7555. << OrigRecDecl->getDeclName();
  7556. // We have an error, now let's go back up through history and show where
  7557. // the offending field came from
  7558. for (ArrayRef<const FieldDecl *>::const_iterator
  7559. I = HistoryStack.begin() + 1,
  7560. E = HistoryStack.end();
  7561. I != E; ++I) {
  7562. const FieldDecl *OuterField = *I;
  7563. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7564. << OuterField->getType();
  7565. }
  7566. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7567. << QT->isPointerType()
  7568. << QT;
  7569. D.setInvalidType();
  7570. return;
  7571. }
  7572. } while (!VisitStack.empty());
  7573. }
  7574. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7575. /// elaborated type specifier in the specified context, and lookup finds
  7576. /// nothing.
  7577. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7578. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7579. DC = DC->getParent();
  7580. return DC;
  7581. }
  7582. /// Find the Scope in which a tag is implicitly declared if we see an
  7583. /// elaborated type specifier in the specified context, and lookup finds
  7584. /// nothing.
  7585. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7586. while (S->isClassScope() ||
  7587. (LangOpts.CPlusPlus &&
  7588. S->isFunctionPrototypeScope()) ||
  7589. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7590. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7591. S = S->getParent();
  7592. return S;
  7593. }
  7594. NamedDecl*
  7595. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7596. TypeSourceInfo *TInfo, LookupResult &Previous,
  7597. MultiTemplateParamsArg TemplateParamLists,
  7598. bool &AddToScope) {
  7599. QualType R = TInfo->getType();
  7600. assert(R->isFunctionType());
  7601. // TODO: consider using NameInfo for diagnostic.
  7602. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7603. DeclarationName Name = NameInfo.getName();
  7604. StorageClass SC = getFunctionStorageClass(*this, D);
  7605. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7606. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7607. diag::err_invalid_thread)
  7608. << DeclSpec::getSpecifierName(TSCS);
  7609. if (D.isFirstDeclarationOfMember())
  7610. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7611. D.getIdentifierLoc());
  7612. bool isFriend = false;
  7613. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7614. bool isMemberSpecialization = false;
  7615. bool isFunctionTemplateSpecialization = false;
  7616. bool isDependentClassScopeExplicitSpecialization = false;
  7617. bool HasExplicitTemplateArgs = false;
  7618. TemplateArgumentListInfo TemplateArgs;
  7619. bool isVirtualOkay = false;
  7620. DeclContext *OriginalDC = DC;
  7621. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7622. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7623. isVirtualOkay);
  7624. if (!NewFD) return nullptr;
  7625. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7626. NewFD->setTopLevelDeclInObjCContainer();
  7627. // Set the lexical context. If this is a function-scope declaration, or has a
  7628. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7629. // context will be different from the semantic context.
  7630. NewFD->setLexicalDeclContext(CurContext);
  7631. if (IsLocalExternDecl)
  7632. NewFD->setLocalExternDecl();
  7633. if (getLangOpts().CPlusPlus) {
  7634. bool isInline = D.getDeclSpec().isInlineSpecified();
  7635. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7636. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  7637. isFriend = D.getDeclSpec().isFriendSpecified();
  7638. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7639. // C++ [class.friend]p5
  7640. // A function can be defined in a friend declaration of a
  7641. // class . . . . Such a function is implicitly inline.
  7642. NewFD->setImplicitlyInline();
  7643. }
  7644. // If this is a method defined in an __interface, and is not a constructor
  7645. // or an overloaded operator, then set the pure flag (isVirtual will already
  7646. // return true).
  7647. if (const CXXRecordDecl *Parent =
  7648. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7649. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7650. NewFD->setPure(true);
  7651. // C++ [class.union]p2
  7652. // A union can have member functions, but not virtual functions.
  7653. if (isVirtual && Parent->isUnion())
  7654. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7655. }
  7656. SetNestedNameSpecifier(*this, NewFD, D);
  7657. isMemberSpecialization = false;
  7658. isFunctionTemplateSpecialization = false;
  7659. if (D.isInvalidType())
  7660. NewFD->setInvalidDecl();
  7661. // Match up the template parameter lists with the scope specifier, then
  7662. // determine whether we have a template or a template specialization.
  7663. bool Invalid = false;
  7664. if (TemplateParameterList *TemplateParams =
  7665. MatchTemplateParametersToScopeSpecifier(
  7666. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7667. D.getCXXScopeSpec(),
  7668. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7669. ? D.getName().TemplateId
  7670. : nullptr,
  7671. TemplateParamLists, isFriend, isMemberSpecialization,
  7672. Invalid)) {
  7673. if (TemplateParams->size() > 0) {
  7674. // This is a function template
  7675. // Check that we can declare a template here.
  7676. if (CheckTemplateDeclScope(S, TemplateParams))
  7677. NewFD->setInvalidDecl();
  7678. // A destructor cannot be a template.
  7679. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7680. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7681. NewFD->setInvalidDecl();
  7682. }
  7683. // If we're adding a template to a dependent context, we may need to
  7684. // rebuilding some of the types used within the template parameter list,
  7685. // now that we know what the current instantiation is.
  7686. if (DC->isDependentContext()) {
  7687. ContextRAII SavedContext(*this, DC);
  7688. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7689. Invalid = true;
  7690. }
  7691. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7692. NewFD->getLocation(),
  7693. Name, TemplateParams,
  7694. NewFD);
  7695. FunctionTemplate->setLexicalDeclContext(CurContext);
  7696. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7697. // For source fidelity, store the other template param lists.
  7698. if (TemplateParamLists.size() > 1) {
  7699. NewFD->setTemplateParameterListsInfo(Context,
  7700. TemplateParamLists.drop_back(1));
  7701. }
  7702. } else {
  7703. // This is a function template specialization.
  7704. isFunctionTemplateSpecialization = true;
  7705. // For source fidelity, store all the template param lists.
  7706. if (TemplateParamLists.size() > 0)
  7707. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7708. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7709. if (isFriend) {
  7710. // We want to remove the "template<>", found here.
  7711. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7712. // If we remove the template<> and the name is not a
  7713. // template-id, we're actually silently creating a problem:
  7714. // the friend declaration will refer to an untemplated decl,
  7715. // and clearly the user wants a template specialization. So
  7716. // we need to insert '<>' after the name.
  7717. SourceLocation InsertLoc;
  7718. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7719. InsertLoc = D.getName().getSourceRange().getEnd();
  7720. InsertLoc = getLocForEndOfToken(InsertLoc);
  7721. }
  7722. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7723. << Name << RemoveRange
  7724. << FixItHint::CreateRemoval(RemoveRange)
  7725. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7726. }
  7727. }
  7728. } else {
  7729. // All template param lists were matched against the scope specifier:
  7730. // this is NOT (an explicit specialization of) a template.
  7731. if (TemplateParamLists.size() > 0)
  7732. // For source fidelity, store all the template param lists.
  7733. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7734. }
  7735. if (Invalid) {
  7736. NewFD->setInvalidDecl();
  7737. if (FunctionTemplate)
  7738. FunctionTemplate->setInvalidDecl();
  7739. }
  7740. // C++ [dcl.fct.spec]p5:
  7741. // The virtual specifier shall only be used in declarations of
  7742. // nonstatic class member functions that appear within a
  7743. // member-specification of a class declaration; see 10.3.
  7744. //
  7745. if (isVirtual && !NewFD->isInvalidDecl()) {
  7746. if (!isVirtualOkay) {
  7747. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7748. diag::err_virtual_non_function);
  7749. } else if (!CurContext->isRecord()) {
  7750. // 'virtual' was specified outside of the class.
  7751. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7752. diag::err_virtual_out_of_class)
  7753. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7754. } else if (NewFD->getDescribedFunctionTemplate()) {
  7755. // C++ [temp.mem]p3:
  7756. // A member function template shall not be virtual.
  7757. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7758. diag::err_virtual_member_function_template)
  7759. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7760. } else {
  7761. // Okay: Add virtual to the method.
  7762. NewFD->setVirtualAsWritten(true);
  7763. }
  7764. if (getLangOpts().CPlusPlus14 &&
  7765. NewFD->getReturnType()->isUndeducedType())
  7766. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7767. }
  7768. if (getLangOpts().CPlusPlus14 &&
  7769. (NewFD->isDependentContext() ||
  7770. (isFriend && CurContext->isDependentContext())) &&
  7771. NewFD->getReturnType()->isUndeducedType()) {
  7772. // If the function template is referenced directly (for instance, as a
  7773. // member of the current instantiation), pretend it has a dependent type.
  7774. // This is not really justified by the standard, but is the only sane
  7775. // thing to do.
  7776. // FIXME: For a friend function, we have not marked the function as being
  7777. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7778. const FunctionProtoType *FPT =
  7779. NewFD->getType()->castAs<FunctionProtoType>();
  7780. QualType Result =
  7781. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7782. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7783. FPT->getExtProtoInfo()));
  7784. }
  7785. // C++ [dcl.fct.spec]p3:
  7786. // The inline specifier shall not appear on a block scope function
  7787. // declaration.
  7788. if (isInline && !NewFD->isInvalidDecl()) {
  7789. if (CurContext->isFunctionOrMethod()) {
  7790. // 'inline' is not allowed on block scope function declaration.
  7791. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7792. diag::err_inline_declaration_block_scope) << Name
  7793. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7794. }
  7795. }
  7796. // C++ [dcl.fct.spec]p6:
  7797. // The explicit specifier shall be used only in the declaration of a
  7798. // constructor or conversion function within its class definition;
  7799. // see 12.3.1 and 12.3.2.
  7800. if (hasExplicit && !NewFD->isInvalidDecl() &&
  7801. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7802. if (!CurContext->isRecord()) {
  7803. // 'explicit' was specified outside of the class.
  7804. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7805. diag::err_explicit_out_of_class)
  7806. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7807. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7808. !isa<CXXConversionDecl>(NewFD)) {
  7809. // 'explicit' was specified on a function that wasn't a constructor
  7810. // or conversion function.
  7811. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7812. diag::err_explicit_non_ctor_or_conv_function)
  7813. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  7814. }
  7815. }
  7816. if (ConstexprSpecKind ConstexprKind =
  7817. D.getDeclSpec().getConstexprSpecifier()) {
  7818. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7819. // are implicitly inline.
  7820. NewFD->setImplicitlyInline();
  7821. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7822. // be either constructors or to return a literal type. Therefore,
  7823. // destructors cannot be declared constexpr.
  7824. if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) {
  7825. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  7826. << ConstexprKind;
  7827. }
  7828. }
  7829. // If __module_private__ was specified, mark the function accordingly.
  7830. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7831. if (isFunctionTemplateSpecialization) {
  7832. SourceLocation ModulePrivateLoc
  7833. = D.getDeclSpec().getModulePrivateSpecLoc();
  7834. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7835. << 0
  7836. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7837. } else {
  7838. NewFD->setModulePrivate();
  7839. if (FunctionTemplate)
  7840. FunctionTemplate->setModulePrivate();
  7841. }
  7842. }
  7843. if (isFriend) {
  7844. if (FunctionTemplate) {
  7845. FunctionTemplate->setObjectOfFriendDecl();
  7846. FunctionTemplate->setAccess(AS_public);
  7847. }
  7848. NewFD->setObjectOfFriendDecl();
  7849. NewFD->setAccess(AS_public);
  7850. }
  7851. // If a function is defined as defaulted or deleted, mark it as such now.
  7852. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7853. // definition kind to FDK_Definition.
  7854. switch (D.getFunctionDefinitionKind()) {
  7855. case FDK_Declaration:
  7856. case FDK_Definition:
  7857. break;
  7858. case FDK_Defaulted:
  7859. NewFD->setDefaulted();
  7860. break;
  7861. case FDK_Deleted:
  7862. NewFD->setDeletedAsWritten();
  7863. break;
  7864. }
  7865. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7866. D.isFunctionDefinition()) {
  7867. // C++ [class.mfct]p2:
  7868. // A member function may be defined (8.4) in its class definition, in
  7869. // which case it is an inline member function (7.1.2)
  7870. NewFD->setImplicitlyInline();
  7871. }
  7872. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7873. !CurContext->isRecord()) {
  7874. // C++ [class.static]p1:
  7875. // A data or function member of a class may be declared static
  7876. // in a class definition, in which case it is a static member of
  7877. // the class.
  7878. // Complain about the 'static' specifier if it's on an out-of-line
  7879. // member function definition.
  7880. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7881. // member function template declaration and class member template
  7882. // declaration (MSVC versions before 2015), warn about this.
  7883. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7884. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  7885. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  7886. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  7887. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7888. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7889. }
  7890. // C++11 [except.spec]p15:
  7891. // A deallocation function with no exception-specification is treated
  7892. // as if it were specified with noexcept(true).
  7893. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7894. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7895. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7896. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7897. NewFD->setType(Context.getFunctionType(
  7898. FPT->getReturnType(), FPT->getParamTypes(),
  7899. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7900. }
  7901. // Filter out previous declarations that don't match the scope.
  7902. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7903. D.getCXXScopeSpec().isNotEmpty() ||
  7904. isMemberSpecialization ||
  7905. isFunctionTemplateSpecialization);
  7906. // Handle GNU asm-label extension (encoded as an attribute).
  7907. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7908. // The parser guarantees this is a string.
  7909. StringLiteral *SE = cast<StringLiteral>(E);
  7910. NewFD->addAttr(::new (Context)
  7911. AsmLabelAttr(Context, SE->getStrTokenLoc(0),
  7912. SE->getString(), /*IsLiteralLabel=*/true));
  7913. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7914. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7915. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7916. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7917. if (isDeclExternC(NewFD)) {
  7918. NewFD->addAttr(I->second);
  7919. ExtnameUndeclaredIdentifiers.erase(I);
  7920. } else
  7921. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7922. << /*Variable*/0 << NewFD;
  7923. }
  7924. }
  7925. // Copy the parameter declarations from the declarator D to the function
  7926. // declaration NewFD, if they are available. First scavenge them into Params.
  7927. SmallVector<ParmVarDecl*, 16> Params;
  7928. unsigned FTIIdx;
  7929. if (D.isFunctionDeclarator(FTIIdx)) {
  7930. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7931. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7932. // function that takes no arguments, not a function that takes a
  7933. // single void argument.
  7934. // We let through "const void" here because Sema::GetTypeForDeclarator
  7935. // already checks for that case.
  7936. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7937. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7938. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7939. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7940. Param->setDeclContext(NewFD);
  7941. Params.push_back(Param);
  7942. if (Param->isInvalidDecl())
  7943. NewFD->setInvalidDecl();
  7944. }
  7945. }
  7946. if (!getLangOpts().CPlusPlus) {
  7947. // In C, find all the tag declarations from the prototype and move them
  7948. // into the function DeclContext. Remove them from the surrounding tag
  7949. // injection context of the function, which is typically but not always
  7950. // the TU.
  7951. DeclContext *PrototypeTagContext =
  7952. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7953. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7954. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7955. // We don't want to reparent enumerators. Look at their parent enum
  7956. // instead.
  7957. if (!TD) {
  7958. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7959. TD = cast<EnumDecl>(ECD->getDeclContext());
  7960. }
  7961. if (!TD)
  7962. continue;
  7963. DeclContext *TagDC = TD->getLexicalDeclContext();
  7964. if (!TagDC->containsDecl(TD))
  7965. continue;
  7966. TagDC->removeDecl(TD);
  7967. TD->setDeclContext(NewFD);
  7968. NewFD->addDecl(TD);
  7969. // Preserve the lexical DeclContext if it is not the surrounding tag
  7970. // injection context of the FD. In this example, the semantic context of
  7971. // E will be f and the lexical context will be S, while both the
  7972. // semantic and lexical contexts of S will be f:
  7973. // void f(struct S { enum E { a } f; } s);
  7974. if (TagDC != PrototypeTagContext)
  7975. TD->setLexicalDeclContext(TagDC);
  7976. }
  7977. }
  7978. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7979. // When we're declaring a function with a typedef, typeof, etc as in the
  7980. // following example, we'll need to synthesize (unnamed)
  7981. // parameters for use in the declaration.
  7982. //
  7983. // @code
  7984. // typedef void fn(int);
  7985. // fn f;
  7986. // @endcode
  7987. // Synthesize a parameter for each argument type.
  7988. for (const auto &AI : FT->param_types()) {
  7989. ParmVarDecl *Param =
  7990. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7991. Param->setScopeInfo(0, Params.size());
  7992. Params.push_back(Param);
  7993. }
  7994. } else {
  7995. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7996. "Should not need args for typedef of non-prototype fn");
  7997. }
  7998. // Finally, we know we have the right number of parameters, install them.
  7999. NewFD->setParams(Params);
  8000. if (D.getDeclSpec().isNoreturnSpecified())
  8001. NewFD->addAttr(C11NoReturnAttr::Create(Context,
  8002. D.getDeclSpec().getNoreturnSpecLoc(),
  8003. AttributeCommonInfo::AS_Keyword));
  8004. // Functions returning a variably modified type violate C99 6.7.5.2p2
  8005. // because all functions have linkage.
  8006. if (!NewFD->isInvalidDecl() &&
  8007. NewFD->getReturnType()->isVariablyModifiedType()) {
  8008. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  8009. NewFD->setInvalidDecl();
  8010. }
  8011. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  8012. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  8013. !NewFD->hasAttr<SectionAttr>())
  8014. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
  8015. Context, PragmaClangTextSection.SectionName,
  8016. PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
  8017. // Apply an implicit SectionAttr if #pragma code_seg is active.
  8018. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  8019. !NewFD->hasAttr<SectionAttr>()) {
  8020. NewFD->addAttr(SectionAttr::CreateImplicit(
  8021. Context, CodeSegStack.CurrentValue->getString(),
  8022. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8023. SectionAttr::Declspec_allocate));
  8024. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  8025. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  8026. ASTContext::PSF_Read,
  8027. NewFD))
  8028. NewFD->dropAttr<SectionAttr>();
  8029. }
  8030. // Apply an implicit CodeSegAttr from class declspec or
  8031. // apply an implicit SectionAttr from #pragma code_seg if active.
  8032. if (!NewFD->hasAttr<CodeSegAttr>()) {
  8033. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  8034. D.isFunctionDefinition())) {
  8035. NewFD->addAttr(SAttr);
  8036. }
  8037. }
  8038. // Handle attributes.
  8039. ProcessDeclAttributes(S, NewFD, D);
  8040. if (getLangOpts().OpenCL) {
  8041. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  8042. // type declaration will generate a compilation error.
  8043. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  8044. if (AddressSpace != LangAS::Default) {
  8045. Diag(NewFD->getLocation(),
  8046. diag::err_opencl_return_value_with_address_space);
  8047. NewFD->setInvalidDecl();
  8048. }
  8049. }
  8050. if (!getLangOpts().CPlusPlus) {
  8051. // Perform semantic checking on the function declaration.
  8052. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8053. CheckMain(NewFD, D.getDeclSpec());
  8054. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8055. CheckMSVCRTEntryPoint(NewFD);
  8056. if (!NewFD->isInvalidDecl())
  8057. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8058. isMemberSpecialization));
  8059. else if (!Previous.empty())
  8060. // Recover gracefully from an invalid redeclaration.
  8061. D.setRedeclaration(true);
  8062. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8063. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8064. "previous declaration set still overloaded");
  8065. // Diagnose no-prototype function declarations with calling conventions that
  8066. // don't support variadic calls. Only do this in C and do it after merging
  8067. // possibly prototyped redeclarations.
  8068. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  8069. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  8070. CallingConv CC = FT->getExtInfo().getCC();
  8071. if (!supportsVariadicCall(CC)) {
  8072. // Windows system headers sometimes accidentally use stdcall without
  8073. // (void) parameters, so we relax this to a warning.
  8074. int DiagID =
  8075. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  8076. Diag(NewFD->getLocation(), DiagID)
  8077. << FunctionType::getNameForCallConv(CC);
  8078. }
  8079. }
  8080. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  8081. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  8082. checkNonTrivialCUnion(NewFD->getReturnType(),
  8083. NewFD->getReturnTypeSourceRange().getBegin(),
  8084. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  8085. } else {
  8086. // C++11 [replacement.functions]p3:
  8087. // The program's definitions shall not be specified as inline.
  8088. //
  8089. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  8090. //
  8091. // Suppress the diagnostic if the function is __attribute__((used)), since
  8092. // that forces an external definition to be emitted.
  8093. if (D.getDeclSpec().isInlineSpecified() &&
  8094. NewFD->isReplaceableGlobalAllocationFunction() &&
  8095. !NewFD->hasAttr<UsedAttr>())
  8096. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8097. diag::ext_operator_new_delete_declared_inline)
  8098. << NewFD->getDeclName();
  8099. // If the declarator is a template-id, translate the parser's template
  8100. // argument list into our AST format.
  8101. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8102. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  8103. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  8104. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  8105. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  8106. TemplateId->NumArgs);
  8107. translateTemplateArguments(TemplateArgsPtr,
  8108. TemplateArgs);
  8109. HasExplicitTemplateArgs = true;
  8110. if (NewFD->isInvalidDecl()) {
  8111. HasExplicitTemplateArgs = false;
  8112. } else if (FunctionTemplate) {
  8113. // Function template with explicit template arguments.
  8114. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  8115. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  8116. HasExplicitTemplateArgs = false;
  8117. } else {
  8118. assert((isFunctionTemplateSpecialization ||
  8119. D.getDeclSpec().isFriendSpecified()) &&
  8120. "should have a 'template<>' for this decl");
  8121. // "friend void foo<>(int);" is an implicit specialization decl.
  8122. isFunctionTemplateSpecialization = true;
  8123. }
  8124. } else if (isFriend && isFunctionTemplateSpecialization) {
  8125. // This combination is only possible in a recovery case; the user
  8126. // wrote something like:
  8127. // template <> friend void foo(int);
  8128. // which we're recovering from as if the user had written:
  8129. // friend void foo<>(int);
  8130. // Go ahead and fake up a template id.
  8131. HasExplicitTemplateArgs = true;
  8132. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  8133. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  8134. }
  8135. // We do not add HD attributes to specializations here because
  8136. // they may have different constexpr-ness compared to their
  8137. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  8138. // may end up with different effective targets. Instead, a
  8139. // specialization inherits its target attributes from its template
  8140. // in the CheckFunctionTemplateSpecialization() call below.
  8141. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  8142. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  8143. // If it's a friend (and only if it's a friend), it's possible
  8144. // that either the specialized function type or the specialized
  8145. // template is dependent, and therefore matching will fail. In
  8146. // this case, don't check the specialization yet.
  8147. bool InstantiationDependent = false;
  8148. if (isFunctionTemplateSpecialization && isFriend &&
  8149. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  8150. TemplateSpecializationType::anyDependentTemplateArguments(
  8151. TemplateArgs,
  8152. InstantiationDependent))) {
  8153. assert(HasExplicitTemplateArgs &&
  8154. "friend function specialization without template args");
  8155. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  8156. Previous))
  8157. NewFD->setInvalidDecl();
  8158. } else if (isFunctionTemplateSpecialization) {
  8159. if (CurContext->isDependentContext() && CurContext->isRecord()
  8160. && !isFriend) {
  8161. isDependentClassScopeExplicitSpecialization = true;
  8162. } else if (!NewFD->isInvalidDecl() &&
  8163. CheckFunctionTemplateSpecialization(
  8164. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  8165. Previous))
  8166. NewFD->setInvalidDecl();
  8167. // C++ [dcl.stc]p1:
  8168. // A storage-class-specifier shall not be specified in an explicit
  8169. // specialization (14.7.3)
  8170. FunctionTemplateSpecializationInfo *Info =
  8171. NewFD->getTemplateSpecializationInfo();
  8172. if (Info && SC != SC_None) {
  8173. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  8174. Diag(NewFD->getLocation(),
  8175. diag::err_explicit_specialization_inconsistent_storage_class)
  8176. << SC
  8177. << FixItHint::CreateRemoval(
  8178. D.getDeclSpec().getStorageClassSpecLoc());
  8179. else
  8180. Diag(NewFD->getLocation(),
  8181. diag::ext_explicit_specialization_storage_class)
  8182. << FixItHint::CreateRemoval(
  8183. D.getDeclSpec().getStorageClassSpecLoc());
  8184. }
  8185. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8186. if (CheckMemberSpecialization(NewFD, Previous))
  8187. NewFD->setInvalidDecl();
  8188. }
  8189. // Perform semantic checking on the function declaration.
  8190. if (!isDependentClassScopeExplicitSpecialization) {
  8191. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8192. CheckMain(NewFD, D.getDeclSpec());
  8193. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8194. CheckMSVCRTEntryPoint(NewFD);
  8195. if (!NewFD->isInvalidDecl())
  8196. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8197. isMemberSpecialization));
  8198. else if (!Previous.empty())
  8199. // Recover gracefully from an invalid redeclaration.
  8200. D.setRedeclaration(true);
  8201. }
  8202. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8203. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8204. "previous declaration set still overloaded");
  8205. NamedDecl *PrincipalDecl = (FunctionTemplate
  8206. ? cast<NamedDecl>(FunctionTemplate)
  8207. : NewFD);
  8208. if (isFriend && NewFD->getPreviousDecl()) {
  8209. AccessSpecifier Access = AS_public;
  8210. if (!NewFD->isInvalidDecl())
  8211. Access = NewFD->getPreviousDecl()->getAccess();
  8212. NewFD->setAccess(Access);
  8213. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8214. }
  8215. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8216. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8217. PrincipalDecl->setNonMemberOperator();
  8218. // If we have a function template, check the template parameter
  8219. // list. This will check and merge default template arguments.
  8220. if (FunctionTemplate) {
  8221. FunctionTemplateDecl *PrevTemplate =
  8222. FunctionTemplate->getPreviousDecl();
  8223. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8224. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8225. : nullptr,
  8226. D.getDeclSpec().isFriendSpecified()
  8227. ? (D.isFunctionDefinition()
  8228. ? TPC_FriendFunctionTemplateDefinition
  8229. : TPC_FriendFunctionTemplate)
  8230. : (D.getCXXScopeSpec().isSet() &&
  8231. DC && DC->isRecord() &&
  8232. DC->isDependentContext())
  8233. ? TPC_ClassTemplateMember
  8234. : TPC_FunctionTemplate);
  8235. }
  8236. if (NewFD->isInvalidDecl()) {
  8237. // Ignore all the rest of this.
  8238. } else if (!D.isRedeclaration()) {
  8239. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8240. AddToScope };
  8241. // Fake up an access specifier if it's supposed to be a class member.
  8242. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8243. NewFD->setAccess(AS_public);
  8244. // Qualified decls generally require a previous declaration.
  8245. if (D.getCXXScopeSpec().isSet()) {
  8246. // ...with the major exception of templated-scope or
  8247. // dependent-scope friend declarations.
  8248. // TODO: we currently also suppress this check in dependent
  8249. // contexts because (1) the parameter depth will be off when
  8250. // matching friend templates and (2) we might actually be
  8251. // selecting a friend based on a dependent factor. But there
  8252. // are situations where these conditions don't apply and we
  8253. // can actually do this check immediately.
  8254. //
  8255. // Unless the scope is dependent, it's always an error if qualified
  8256. // redeclaration lookup found nothing at all. Diagnose that now;
  8257. // nothing will diagnose that error later.
  8258. if (isFriend &&
  8259. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8260. (!Previous.empty() && CurContext->isDependentContext()))) {
  8261. // ignore these
  8262. } else {
  8263. // The user tried to provide an out-of-line definition for a
  8264. // function that is a member of a class or namespace, but there
  8265. // was no such member function declared (C++ [class.mfct]p2,
  8266. // C++ [namespace.memdef]p2). For example:
  8267. //
  8268. // class X {
  8269. // void f() const;
  8270. // };
  8271. //
  8272. // void X::f() { } // ill-formed
  8273. //
  8274. // Complain about this problem, and attempt to suggest close
  8275. // matches (e.g., those that differ only in cv-qualifiers and
  8276. // whether the parameter types are references).
  8277. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8278. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8279. AddToScope = ExtraArgs.AddToScope;
  8280. return Result;
  8281. }
  8282. }
  8283. // Unqualified local friend declarations are required to resolve
  8284. // to something.
  8285. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8286. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8287. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8288. AddToScope = ExtraArgs.AddToScope;
  8289. return Result;
  8290. }
  8291. }
  8292. } else if (!D.isFunctionDefinition() &&
  8293. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8294. !isFriend && !isFunctionTemplateSpecialization &&
  8295. !isMemberSpecialization) {
  8296. // An out-of-line member function declaration must also be a
  8297. // definition (C++ [class.mfct]p2).
  8298. // Note that this is not the case for explicit specializations of
  8299. // function templates or member functions of class templates, per
  8300. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8301. // extension for compatibility with old SWIG code which likes to
  8302. // generate them.
  8303. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8304. << D.getCXXScopeSpec().getRange();
  8305. }
  8306. }
  8307. ProcessPragmaWeak(S, NewFD);
  8308. checkAttributesAfterMerging(*this, *NewFD);
  8309. AddKnownFunctionAttributes(NewFD);
  8310. if (NewFD->hasAttr<OverloadableAttr>() &&
  8311. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8312. Diag(NewFD->getLocation(),
  8313. diag::err_attribute_overloadable_no_prototype)
  8314. << NewFD;
  8315. // Turn this into a variadic function with no parameters.
  8316. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8317. FunctionProtoType::ExtProtoInfo EPI(
  8318. Context.getDefaultCallingConvention(true, false));
  8319. EPI.Variadic = true;
  8320. EPI.ExtInfo = FT->getExtInfo();
  8321. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8322. NewFD->setType(R);
  8323. }
  8324. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8325. // member, set the visibility of this function.
  8326. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8327. AddPushedVisibilityAttribute(NewFD);
  8328. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8329. // marking the function.
  8330. AddCFAuditedAttribute(NewFD);
  8331. // If this is a function definition, check if we have to apply optnone due to
  8332. // a pragma.
  8333. if(D.isFunctionDefinition())
  8334. AddRangeBasedOptnone(NewFD);
  8335. // If this is the first declaration of an extern C variable, update
  8336. // the map of such variables.
  8337. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8338. isIncompleteDeclExternC(*this, NewFD))
  8339. RegisterLocallyScopedExternCDecl(NewFD, S);
  8340. // Set this FunctionDecl's range up to the right paren.
  8341. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8342. if (D.isRedeclaration() && !Previous.empty()) {
  8343. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8344. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8345. isMemberSpecialization ||
  8346. isFunctionTemplateSpecialization,
  8347. D.isFunctionDefinition());
  8348. }
  8349. if (getLangOpts().CUDA) {
  8350. IdentifierInfo *II = NewFD->getIdentifier();
  8351. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8352. !NewFD->isInvalidDecl() &&
  8353. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8354. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8355. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8356. << getCudaConfigureFuncName();
  8357. Context.setcudaConfigureCallDecl(NewFD);
  8358. }
  8359. // Variadic functions, other than a *declaration* of printf, are not allowed
  8360. // in device-side CUDA code, unless someone passed
  8361. // -fcuda-allow-variadic-functions.
  8362. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8363. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8364. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8365. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8366. !D.isFunctionDefinition())) {
  8367. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8368. }
  8369. }
  8370. MarkUnusedFileScopedDecl(NewFD);
  8371. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8372. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8373. if ((getLangOpts().OpenCLVersion >= 120)
  8374. && (SC == SC_Static)) {
  8375. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8376. D.setInvalidType();
  8377. }
  8378. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8379. if (!NewFD->getReturnType()->isVoidType()) {
  8380. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8381. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8382. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8383. : FixItHint());
  8384. D.setInvalidType();
  8385. }
  8386. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8387. for (auto Param : NewFD->parameters())
  8388. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8389. if (getLangOpts().OpenCLCPlusPlus) {
  8390. if (DC->isRecord()) {
  8391. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8392. D.setInvalidType();
  8393. }
  8394. if (FunctionTemplate) {
  8395. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8396. D.setInvalidType();
  8397. }
  8398. }
  8399. }
  8400. if (getLangOpts().CPlusPlus) {
  8401. if (FunctionTemplate) {
  8402. if (NewFD->isInvalidDecl())
  8403. FunctionTemplate->setInvalidDecl();
  8404. return FunctionTemplate;
  8405. }
  8406. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8407. CompleteMemberSpecialization(NewFD, Previous);
  8408. }
  8409. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8410. QualType PT = Param->getType();
  8411. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8412. // types.
  8413. if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
  8414. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8415. QualType ElemTy = PipeTy->getElementType();
  8416. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8417. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8418. D.setInvalidType();
  8419. }
  8420. }
  8421. }
  8422. }
  8423. // Here we have an function template explicit specialization at class scope.
  8424. // The actual specialization will be postponed to template instatiation
  8425. // time via the ClassScopeFunctionSpecializationDecl node.
  8426. if (isDependentClassScopeExplicitSpecialization) {
  8427. ClassScopeFunctionSpecializationDecl *NewSpec =
  8428. ClassScopeFunctionSpecializationDecl::Create(
  8429. Context, CurContext, NewFD->getLocation(),
  8430. cast<CXXMethodDecl>(NewFD),
  8431. HasExplicitTemplateArgs, TemplateArgs);
  8432. CurContext->addDecl(NewSpec);
  8433. AddToScope = false;
  8434. }
  8435. // Diagnose availability attributes. Availability cannot be used on functions
  8436. // that are run during load/unload.
  8437. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8438. if (NewFD->hasAttr<ConstructorAttr>()) {
  8439. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8440. << 1;
  8441. NewFD->dropAttr<AvailabilityAttr>();
  8442. }
  8443. if (NewFD->hasAttr<DestructorAttr>()) {
  8444. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8445. << 2;
  8446. NewFD->dropAttr<AvailabilityAttr>();
  8447. }
  8448. }
  8449. return NewFD;
  8450. }
  8451. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8452. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8453. /// the class and nested classes -- this includes compiler-generated special
  8454. /// member functions -- are put in the specified segment."
  8455. /// The actual behavior is a little more complicated. The Microsoft compiler
  8456. /// won't check outer classes if there is an active value from #pragma code_seg.
  8457. /// The CodeSeg is always applied from the direct parent but only from outer
  8458. /// classes when the #pragma code_seg stack is empty. See:
  8459. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8460. /// available since MS has removed the page.
  8461. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8462. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8463. if (!Method)
  8464. return nullptr;
  8465. const CXXRecordDecl *Parent = Method->getParent();
  8466. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8467. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8468. NewAttr->setImplicit(true);
  8469. return NewAttr;
  8470. }
  8471. // The Microsoft compiler won't check outer classes for the CodeSeg
  8472. // when the #pragma code_seg stack is active.
  8473. if (S.CodeSegStack.CurrentValue)
  8474. return nullptr;
  8475. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8476. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8477. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8478. NewAttr->setImplicit(true);
  8479. return NewAttr;
  8480. }
  8481. }
  8482. return nullptr;
  8483. }
  8484. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8485. /// containing class. Otherwise it will return implicit SectionAttr if the
  8486. /// function is a definition and there is an active value on CodeSegStack
  8487. /// (from the current #pragma code-seg value).
  8488. ///
  8489. /// \param FD Function being declared.
  8490. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8491. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8492. /// nullptr if no attribute should be added.
  8493. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8494. bool IsDefinition) {
  8495. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8496. return A;
  8497. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8498. CodeSegStack.CurrentValue)
  8499. return SectionAttr::CreateImplicit(
  8500. getASTContext(), CodeSegStack.CurrentValue->getString(),
  8501. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8502. SectionAttr::Declspec_allocate);
  8503. return nullptr;
  8504. }
  8505. /// Determines if we can perform a correct type check for \p D as a
  8506. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8507. /// best-effort check.
  8508. ///
  8509. /// \param NewD The new declaration.
  8510. /// \param OldD The old declaration.
  8511. /// \param NewT The portion of the type of the new declaration to check.
  8512. /// \param OldT The portion of the type of the old declaration to check.
  8513. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8514. QualType NewT, QualType OldT) {
  8515. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8516. return true;
  8517. // For dependently-typed local extern declarations and friends, we can't
  8518. // perform a correct type check in general until instantiation:
  8519. //
  8520. // int f();
  8521. // template<typename T> void g() { T f(); }
  8522. //
  8523. // (valid if g() is only instantiated with T = int).
  8524. if (NewT->isDependentType() &&
  8525. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8526. return false;
  8527. // Similarly, if the previous declaration was a dependent local extern
  8528. // declaration, we don't really know its type yet.
  8529. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8530. return false;
  8531. return true;
  8532. }
  8533. /// Checks if the new declaration declared in dependent context must be
  8534. /// put in the same redeclaration chain as the specified declaration.
  8535. ///
  8536. /// \param D Declaration that is checked.
  8537. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8538. /// same declaration name.
  8539. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8540. /// belongs to.
  8541. ///
  8542. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8543. if (!D->getLexicalDeclContext()->isDependentContext())
  8544. return true;
  8545. // Don't chain dependent friend function definitions until instantiation, to
  8546. // permit cases like
  8547. //
  8548. // void func();
  8549. // template<typename T> class C1 { friend void func() {} };
  8550. // template<typename T> class C2 { friend void func() {} };
  8551. //
  8552. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8553. //
  8554. // FIXME: This need only apply to function definitions. For now, we proxy
  8555. // this by checking for a file-scope function. We do not want this to apply
  8556. // to friend declarations nominating member functions, because that gets in
  8557. // the way of access checks.
  8558. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8559. return false;
  8560. auto *VD = dyn_cast<ValueDecl>(D);
  8561. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8562. return !VD || !PrevVD ||
  8563. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8564. PrevVD->getType());
  8565. }
  8566. /// Check the target attribute of the function for MultiVersion
  8567. /// validity.
  8568. ///
  8569. /// Returns true if there was an error, false otherwise.
  8570. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8571. const auto *TA = FD->getAttr<TargetAttr>();
  8572. assert(TA && "MultiVersion Candidate requires a target attribute");
  8573. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8574. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8575. enum ErrType { Feature = 0, Architecture = 1 };
  8576. if (!ParseInfo.Architecture.empty() &&
  8577. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8578. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8579. << Architecture << ParseInfo.Architecture;
  8580. return true;
  8581. }
  8582. for (const auto &Feat : ParseInfo.Features) {
  8583. auto BareFeat = StringRef{Feat}.substr(1);
  8584. if (Feat[0] == '-') {
  8585. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8586. << Feature << ("no-" + BareFeat).str();
  8587. return true;
  8588. }
  8589. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8590. !TargetInfo.isValidFeatureName(BareFeat)) {
  8591. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8592. << Feature << BareFeat;
  8593. return true;
  8594. }
  8595. }
  8596. return false;
  8597. }
  8598. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8599. MultiVersionKind MVType) {
  8600. for (const Attr *A : FD->attrs()) {
  8601. switch (A->getKind()) {
  8602. case attr::CPUDispatch:
  8603. case attr::CPUSpecific:
  8604. if (MVType != MultiVersionKind::CPUDispatch &&
  8605. MVType != MultiVersionKind::CPUSpecific)
  8606. return true;
  8607. break;
  8608. case attr::Target:
  8609. if (MVType != MultiVersionKind::Target)
  8610. return true;
  8611. break;
  8612. default:
  8613. return true;
  8614. }
  8615. }
  8616. return false;
  8617. }
  8618. bool Sema::areMultiversionVariantFunctionsCompatible(
  8619. const FunctionDecl *OldFD, const FunctionDecl *NewFD,
  8620. const PartialDiagnostic &NoProtoDiagID,
  8621. const PartialDiagnosticAt &NoteCausedDiagIDAt,
  8622. const PartialDiagnosticAt &NoSupportDiagIDAt,
  8623. const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
  8624. bool ConstexprSupported, bool CLinkageMayDiffer) {
  8625. enum DoesntSupport {
  8626. FuncTemplates = 0,
  8627. VirtFuncs = 1,
  8628. DeducedReturn = 2,
  8629. Constructors = 3,
  8630. Destructors = 4,
  8631. DeletedFuncs = 5,
  8632. DefaultedFuncs = 6,
  8633. ConstexprFuncs = 7,
  8634. ConstevalFuncs = 8,
  8635. };
  8636. enum Different {
  8637. CallingConv = 0,
  8638. ReturnType = 1,
  8639. ConstexprSpec = 2,
  8640. InlineSpec = 3,
  8641. StorageClass = 4,
  8642. Linkage = 5,
  8643. };
  8644. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8645. Diag(OldFD->getLocation(), NoProtoDiagID);
  8646. Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
  8647. return true;
  8648. }
  8649. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8650. return Diag(NewFD->getLocation(), NoProtoDiagID);
  8651. if (!TemplatesSupported &&
  8652. NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8653. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8654. << FuncTemplates;
  8655. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8656. if (NewCXXFD->isVirtual())
  8657. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8658. << VirtFuncs;
  8659. if (isa<CXXConstructorDecl>(NewCXXFD))
  8660. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8661. << Constructors;
  8662. if (isa<CXXDestructorDecl>(NewCXXFD))
  8663. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8664. << Destructors;
  8665. }
  8666. if (NewFD->isDeleted())
  8667. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8668. << DeletedFuncs;
  8669. if (NewFD->isDefaulted())
  8670. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8671. << DefaultedFuncs;
  8672. if (!ConstexprSupported && NewFD->isConstexpr())
  8673. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8674. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  8675. QualType NewQType = Context.getCanonicalType(NewFD->getType());
  8676. const auto *NewType = cast<FunctionType>(NewQType);
  8677. QualType NewReturnType = NewType->getReturnType();
  8678. if (NewReturnType->isUndeducedType())
  8679. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  8680. << DeducedReturn;
  8681. // Ensure the return type is identical.
  8682. if (OldFD) {
  8683. QualType OldQType = Context.getCanonicalType(OldFD->getType());
  8684. const auto *OldType = cast<FunctionType>(OldQType);
  8685. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8686. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8687. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8688. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
  8689. QualType OldReturnType = OldType->getReturnType();
  8690. if (OldReturnType != NewReturnType)
  8691. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
  8692. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  8693. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
  8694. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8695. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
  8696. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8697. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
  8698. if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
  8699. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
  8700. if (CheckEquivalentExceptionSpec(
  8701. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8702. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8703. return true;
  8704. }
  8705. return false;
  8706. }
  8707. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8708. const FunctionDecl *NewFD,
  8709. bool CausesMV,
  8710. MultiVersionKind MVType) {
  8711. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8712. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8713. if (OldFD)
  8714. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8715. return true;
  8716. }
  8717. bool IsCPUSpecificCPUDispatchMVType =
  8718. MVType == MultiVersionKind::CPUDispatch ||
  8719. MVType == MultiVersionKind::CPUSpecific;
  8720. // For now, disallow all other attributes. These should be opt-in, but
  8721. // an analysis of all of them is a future FIXME.
  8722. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8723. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8724. << IsCPUSpecificCPUDispatchMVType;
  8725. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8726. return true;
  8727. }
  8728. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8729. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8730. << IsCPUSpecificCPUDispatchMVType;
  8731. // Only allow transition to MultiVersion if it hasn't been used.
  8732. if (OldFD && CausesMV && OldFD->isUsed(false))
  8733. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8734. return S.areMultiversionVariantFunctionsCompatible(
  8735. OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
  8736. PartialDiagnosticAt(NewFD->getLocation(),
  8737. S.PDiag(diag::note_multiversioning_caused_here)),
  8738. PartialDiagnosticAt(NewFD->getLocation(),
  8739. S.PDiag(diag::err_multiversion_doesnt_support)
  8740. << IsCPUSpecificCPUDispatchMVType),
  8741. PartialDiagnosticAt(NewFD->getLocation(),
  8742. S.PDiag(diag::err_multiversion_diff)),
  8743. /*TemplatesSupported=*/false,
  8744. /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
  8745. /*CLinkageMayDiffer=*/false);
  8746. }
  8747. /// Check the validity of a multiversion function declaration that is the
  8748. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8749. ///
  8750. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8751. ///
  8752. /// Returns true if there was an error, false otherwise.
  8753. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8754. MultiVersionKind MVType,
  8755. const TargetAttr *TA) {
  8756. assert(MVType != MultiVersionKind::None &&
  8757. "Function lacks multiversion attribute");
  8758. // Target only causes MV if it is default, otherwise this is a normal
  8759. // function.
  8760. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8761. return false;
  8762. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8763. FD->setInvalidDecl();
  8764. return true;
  8765. }
  8766. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8767. FD->setInvalidDecl();
  8768. return true;
  8769. }
  8770. FD->setIsMultiVersion();
  8771. return false;
  8772. }
  8773. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8774. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8775. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8776. return true;
  8777. }
  8778. return false;
  8779. }
  8780. static bool CheckTargetCausesMultiVersioning(
  8781. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8782. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8783. LookupResult &Previous) {
  8784. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8785. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8786. // Sort order doesn't matter, it just needs to be consistent.
  8787. llvm::sort(NewParsed.Features);
  8788. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8789. // to change, this is a simple redeclaration.
  8790. if (!NewTA->isDefaultVersion() &&
  8791. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8792. return false;
  8793. // Otherwise, this decl causes MultiVersioning.
  8794. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8795. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8796. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8797. NewFD->setInvalidDecl();
  8798. return true;
  8799. }
  8800. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8801. MultiVersionKind::Target)) {
  8802. NewFD->setInvalidDecl();
  8803. return true;
  8804. }
  8805. if (CheckMultiVersionValue(S, NewFD)) {
  8806. NewFD->setInvalidDecl();
  8807. return true;
  8808. }
  8809. // If this is 'default', permit the forward declaration.
  8810. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8811. Redeclaration = true;
  8812. OldDecl = OldFD;
  8813. OldFD->setIsMultiVersion();
  8814. NewFD->setIsMultiVersion();
  8815. return false;
  8816. }
  8817. if (CheckMultiVersionValue(S, OldFD)) {
  8818. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8819. NewFD->setInvalidDecl();
  8820. return true;
  8821. }
  8822. TargetAttr::ParsedTargetAttr OldParsed =
  8823. OldTA->parse(std::less<std::string>());
  8824. if (OldParsed == NewParsed) {
  8825. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8826. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8827. NewFD->setInvalidDecl();
  8828. return true;
  8829. }
  8830. for (const auto *FD : OldFD->redecls()) {
  8831. const auto *CurTA = FD->getAttr<TargetAttr>();
  8832. // We allow forward declarations before ANY multiversioning attributes, but
  8833. // nothing after the fact.
  8834. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8835. (!CurTA || CurTA->isInherited())) {
  8836. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8837. << 0;
  8838. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8839. NewFD->setInvalidDecl();
  8840. return true;
  8841. }
  8842. }
  8843. OldFD->setIsMultiVersion();
  8844. NewFD->setIsMultiVersion();
  8845. Redeclaration = false;
  8846. MergeTypeWithPrevious = false;
  8847. OldDecl = nullptr;
  8848. Previous.clear();
  8849. return false;
  8850. }
  8851. /// Check the validity of a new function declaration being added to an existing
  8852. /// multiversioned declaration collection.
  8853. static bool CheckMultiVersionAdditionalDecl(
  8854. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8855. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8856. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8857. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8858. LookupResult &Previous) {
  8859. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8860. // Disallow mixing of multiversioning types.
  8861. if ((OldMVType == MultiVersionKind::Target &&
  8862. NewMVType != MultiVersionKind::Target) ||
  8863. (NewMVType == MultiVersionKind::Target &&
  8864. OldMVType != MultiVersionKind::Target)) {
  8865. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8866. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8867. NewFD->setInvalidDecl();
  8868. return true;
  8869. }
  8870. TargetAttr::ParsedTargetAttr NewParsed;
  8871. if (NewTA) {
  8872. NewParsed = NewTA->parse();
  8873. llvm::sort(NewParsed.Features);
  8874. }
  8875. bool UseMemberUsingDeclRules =
  8876. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8877. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8878. // previous member of the MultiVersion set.
  8879. for (NamedDecl *ND : Previous) {
  8880. FunctionDecl *CurFD = ND->getAsFunction();
  8881. if (!CurFD)
  8882. continue;
  8883. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8884. continue;
  8885. if (NewMVType == MultiVersionKind::Target) {
  8886. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8887. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8888. NewFD->setIsMultiVersion();
  8889. Redeclaration = true;
  8890. OldDecl = ND;
  8891. return false;
  8892. }
  8893. TargetAttr::ParsedTargetAttr CurParsed =
  8894. CurTA->parse(std::less<std::string>());
  8895. if (CurParsed == NewParsed) {
  8896. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8897. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8898. NewFD->setInvalidDecl();
  8899. return true;
  8900. }
  8901. } else {
  8902. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8903. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8904. // Handle CPUDispatch/CPUSpecific versions.
  8905. // Only 1 CPUDispatch function is allowed, this will make it go through
  8906. // the redeclaration errors.
  8907. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8908. CurFD->hasAttr<CPUDispatchAttr>()) {
  8909. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8910. std::equal(
  8911. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8912. NewCPUDisp->cpus_begin(),
  8913. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8914. return Cur->getName() == New->getName();
  8915. })) {
  8916. NewFD->setIsMultiVersion();
  8917. Redeclaration = true;
  8918. OldDecl = ND;
  8919. return false;
  8920. }
  8921. // If the declarations don't match, this is an error condition.
  8922. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8923. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8924. NewFD->setInvalidDecl();
  8925. return true;
  8926. }
  8927. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8928. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8929. std::equal(
  8930. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8931. NewCPUSpec->cpus_begin(),
  8932. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8933. return Cur->getName() == New->getName();
  8934. })) {
  8935. NewFD->setIsMultiVersion();
  8936. Redeclaration = true;
  8937. OldDecl = ND;
  8938. return false;
  8939. }
  8940. // Only 1 version of CPUSpecific is allowed for each CPU.
  8941. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8942. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8943. if (CurII == NewII) {
  8944. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8945. << NewII;
  8946. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8947. NewFD->setInvalidDecl();
  8948. return true;
  8949. }
  8950. }
  8951. }
  8952. }
  8953. // If the two decls aren't the same MVType, there is no possible error
  8954. // condition.
  8955. }
  8956. }
  8957. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8958. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8959. // handled in the attribute adding step.
  8960. if (NewMVType == MultiVersionKind::Target &&
  8961. CheckMultiVersionValue(S, NewFD)) {
  8962. NewFD->setInvalidDecl();
  8963. return true;
  8964. }
  8965. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8966. !OldFD->isMultiVersion(), NewMVType)) {
  8967. NewFD->setInvalidDecl();
  8968. return true;
  8969. }
  8970. // Permit forward declarations in the case where these two are compatible.
  8971. if (!OldFD->isMultiVersion()) {
  8972. OldFD->setIsMultiVersion();
  8973. NewFD->setIsMultiVersion();
  8974. Redeclaration = true;
  8975. OldDecl = OldFD;
  8976. return false;
  8977. }
  8978. NewFD->setIsMultiVersion();
  8979. Redeclaration = false;
  8980. MergeTypeWithPrevious = false;
  8981. OldDecl = nullptr;
  8982. Previous.clear();
  8983. return false;
  8984. }
  8985. /// Check the validity of a mulitversion function declaration.
  8986. /// Also sets the multiversion'ness' of the function itself.
  8987. ///
  8988. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8989. ///
  8990. /// Returns true if there was an error, false otherwise.
  8991. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8992. bool &Redeclaration, NamedDecl *&OldDecl,
  8993. bool &MergeTypeWithPrevious,
  8994. LookupResult &Previous) {
  8995. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8996. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8997. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8998. // Mixing Multiversioning types is prohibited.
  8999. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  9000. (NewCPUDisp && NewCPUSpec)) {
  9001. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  9002. NewFD->setInvalidDecl();
  9003. return true;
  9004. }
  9005. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  9006. // Main isn't allowed to become a multiversion function, however it IS
  9007. // permitted to have 'main' be marked with the 'target' optimization hint.
  9008. if (NewFD->isMain()) {
  9009. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  9010. MVType == MultiVersionKind::CPUDispatch ||
  9011. MVType == MultiVersionKind::CPUSpecific) {
  9012. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  9013. NewFD->setInvalidDecl();
  9014. return true;
  9015. }
  9016. return false;
  9017. }
  9018. if (!OldDecl || !OldDecl->getAsFunction() ||
  9019. OldDecl->getDeclContext()->getRedeclContext() !=
  9020. NewFD->getDeclContext()->getRedeclContext()) {
  9021. // If there's no previous declaration, AND this isn't attempting to cause
  9022. // multiversioning, this isn't an error condition.
  9023. if (MVType == MultiVersionKind::None)
  9024. return false;
  9025. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  9026. }
  9027. FunctionDecl *OldFD = OldDecl->getAsFunction();
  9028. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  9029. return false;
  9030. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  9031. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  9032. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  9033. NewFD->setInvalidDecl();
  9034. return true;
  9035. }
  9036. // Handle the target potentially causes multiversioning case.
  9037. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  9038. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  9039. Redeclaration, OldDecl,
  9040. MergeTypeWithPrevious, Previous);
  9041. // At this point, we have a multiversion function decl (in OldFD) AND an
  9042. // appropriate attribute in the current function decl. Resolve that these are
  9043. // still compatible with previous declarations.
  9044. return CheckMultiVersionAdditionalDecl(
  9045. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  9046. OldDecl, MergeTypeWithPrevious, Previous);
  9047. }
  9048. /// Perform semantic checking of a new function declaration.
  9049. ///
  9050. /// Performs semantic analysis of the new function declaration
  9051. /// NewFD. This routine performs all semantic checking that does not
  9052. /// require the actual declarator involved in the declaration, and is
  9053. /// used both for the declaration of functions as they are parsed
  9054. /// (called via ActOnDeclarator) and for the declaration of functions
  9055. /// that have been instantiated via C++ template instantiation (called
  9056. /// via InstantiateDecl).
  9057. ///
  9058. /// \param IsMemberSpecialization whether this new function declaration is
  9059. /// a member specialization (that replaces any definition provided by the
  9060. /// previous declaration).
  9061. ///
  9062. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9063. ///
  9064. /// \returns true if the function declaration is a redeclaration.
  9065. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  9066. LookupResult &Previous,
  9067. bool IsMemberSpecialization) {
  9068. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  9069. "Variably modified return types are not handled here");
  9070. // Determine whether the type of this function should be merged with
  9071. // a previous visible declaration. This never happens for functions in C++,
  9072. // and always happens in C if the previous declaration was visible.
  9073. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  9074. !Previous.isShadowed();
  9075. bool Redeclaration = false;
  9076. NamedDecl *OldDecl = nullptr;
  9077. bool MayNeedOverloadableChecks = false;
  9078. // Merge or overload the declaration with an existing declaration of
  9079. // the same name, if appropriate.
  9080. if (!Previous.empty()) {
  9081. // Determine whether NewFD is an overload of PrevDecl or
  9082. // a declaration that requires merging. If it's an overload,
  9083. // there's no more work to do here; we'll just add the new
  9084. // function to the scope.
  9085. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  9086. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  9087. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  9088. Redeclaration = true;
  9089. OldDecl = Candidate;
  9090. }
  9091. } else {
  9092. MayNeedOverloadableChecks = true;
  9093. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  9094. /*NewIsUsingDecl*/ false)) {
  9095. case Ovl_Match:
  9096. Redeclaration = true;
  9097. break;
  9098. case Ovl_NonFunction:
  9099. Redeclaration = true;
  9100. break;
  9101. case Ovl_Overload:
  9102. Redeclaration = false;
  9103. break;
  9104. }
  9105. }
  9106. }
  9107. // Check for a previous extern "C" declaration with this name.
  9108. if (!Redeclaration &&
  9109. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  9110. if (!Previous.empty()) {
  9111. // This is an extern "C" declaration with the same name as a previous
  9112. // declaration, and thus redeclares that entity...
  9113. Redeclaration = true;
  9114. OldDecl = Previous.getFoundDecl();
  9115. MergeTypeWithPrevious = false;
  9116. // ... except in the presence of __attribute__((overloadable)).
  9117. if (OldDecl->hasAttr<OverloadableAttr>() ||
  9118. NewFD->hasAttr<OverloadableAttr>()) {
  9119. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  9120. MayNeedOverloadableChecks = true;
  9121. Redeclaration = false;
  9122. OldDecl = nullptr;
  9123. }
  9124. }
  9125. }
  9126. }
  9127. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  9128. MergeTypeWithPrevious, Previous))
  9129. return Redeclaration;
  9130. // C++11 [dcl.constexpr]p8:
  9131. // A constexpr specifier for a non-static member function that is not
  9132. // a constructor declares that member function to be const.
  9133. //
  9134. // This needs to be delayed until we know whether this is an out-of-line
  9135. // definition of a static member function.
  9136. //
  9137. // This rule is not present in C++1y, so we produce a backwards
  9138. // compatibility warning whenever it happens in C++11.
  9139. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  9140. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  9141. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  9142. !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
  9143. CXXMethodDecl *OldMD = nullptr;
  9144. if (OldDecl)
  9145. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  9146. if (!OldMD || !OldMD->isStatic()) {
  9147. const FunctionProtoType *FPT =
  9148. MD->getType()->castAs<FunctionProtoType>();
  9149. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9150. EPI.TypeQuals.addConst();
  9151. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  9152. FPT->getParamTypes(), EPI));
  9153. // Warn that we did this, if we're not performing template instantiation.
  9154. // In that case, we'll have warned already when the template was defined.
  9155. if (!inTemplateInstantiation()) {
  9156. SourceLocation AddConstLoc;
  9157. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  9158. .IgnoreParens().getAs<FunctionTypeLoc>())
  9159. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  9160. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  9161. << FixItHint::CreateInsertion(AddConstLoc, " const");
  9162. }
  9163. }
  9164. }
  9165. if (Redeclaration) {
  9166. // NewFD and OldDecl represent declarations that need to be
  9167. // merged.
  9168. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  9169. NewFD->setInvalidDecl();
  9170. return Redeclaration;
  9171. }
  9172. Previous.clear();
  9173. Previous.addDecl(OldDecl);
  9174. if (FunctionTemplateDecl *OldTemplateDecl =
  9175. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  9176. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  9177. FunctionTemplateDecl *NewTemplateDecl
  9178. = NewFD->getDescribedFunctionTemplate();
  9179. assert(NewTemplateDecl && "Template/non-template mismatch");
  9180. // The call to MergeFunctionDecl above may have created some state in
  9181. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  9182. // can add it as a redeclaration.
  9183. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  9184. NewFD->setPreviousDeclaration(OldFD);
  9185. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9186. if (NewFD->isCXXClassMember()) {
  9187. NewFD->setAccess(OldTemplateDecl->getAccess());
  9188. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9189. }
  9190. // If this is an explicit specialization of a member that is a function
  9191. // template, mark it as a member specialization.
  9192. if (IsMemberSpecialization &&
  9193. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9194. NewTemplateDecl->setMemberSpecialization();
  9195. assert(OldTemplateDecl->isMemberSpecialization());
  9196. // Explicit specializations of a member template do not inherit deleted
  9197. // status from the parent member template that they are specializing.
  9198. if (OldFD->isDeleted()) {
  9199. // FIXME: This assert will not hold in the presence of modules.
  9200. assert(OldFD->getCanonicalDecl() == OldFD);
  9201. // FIXME: We need an update record for this AST mutation.
  9202. OldFD->setDeletedAsWritten(false);
  9203. }
  9204. }
  9205. } else {
  9206. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9207. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9208. // This needs to happen first so that 'inline' propagates.
  9209. NewFD->setPreviousDeclaration(OldFD);
  9210. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  9211. if (NewFD->isCXXClassMember())
  9212. NewFD->setAccess(OldFD->getAccess());
  9213. }
  9214. }
  9215. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9216. !NewFD->getAttr<OverloadableAttr>()) {
  9217. assert((Previous.empty() ||
  9218. llvm::any_of(Previous,
  9219. [](const NamedDecl *ND) {
  9220. return ND->hasAttr<OverloadableAttr>();
  9221. })) &&
  9222. "Non-redecls shouldn't happen without overloadable present");
  9223. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9224. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9225. return FD && !FD->hasAttr<OverloadableAttr>();
  9226. });
  9227. if (OtherUnmarkedIter != Previous.end()) {
  9228. Diag(NewFD->getLocation(),
  9229. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9230. Diag((*OtherUnmarkedIter)->getLocation(),
  9231. diag::note_attribute_overloadable_prev_overload)
  9232. << false;
  9233. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9234. }
  9235. }
  9236. // Semantic checking for this function declaration (in isolation).
  9237. if (getLangOpts().CPlusPlus) {
  9238. // C++-specific checks.
  9239. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9240. CheckConstructor(Constructor);
  9241. } else if (CXXDestructorDecl *Destructor =
  9242. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9243. CXXRecordDecl *Record = Destructor->getParent();
  9244. QualType ClassType = Context.getTypeDeclType(Record);
  9245. // FIXME: Shouldn't we be able to perform this check even when the class
  9246. // type is dependent? Both gcc and edg can handle that.
  9247. if (!ClassType->isDependentType()) {
  9248. DeclarationName Name
  9249. = Context.DeclarationNames.getCXXDestructorName(
  9250. Context.getCanonicalType(ClassType));
  9251. if (NewFD->getDeclName() != Name) {
  9252. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9253. NewFD->setInvalidDecl();
  9254. return Redeclaration;
  9255. }
  9256. }
  9257. } else if (CXXConversionDecl *Conversion
  9258. = dyn_cast<CXXConversionDecl>(NewFD)) {
  9259. ActOnConversionDeclarator(Conversion);
  9260. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9261. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9262. CheckDeductionGuideTemplate(TD);
  9263. // A deduction guide is not on the list of entities that can be
  9264. // explicitly specialized.
  9265. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9266. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9267. << /*explicit specialization*/ 1;
  9268. }
  9269. // Find any virtual functions that this function overrides.
  9270. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9271. if (!Method->isFunctionTemplateSpecialization() &&
  9272. !Method->getDescribedFunctionTemplate() &&
  9273. Method->isCanonicalDecl()) {
  9274. if (AddOverriddenMethods(Method->getParent(), Method)) {
  9275. // If the function was marked as "static", we have a problem.
  9276. if (NewFD->getStorageClass() == SC_Static) {
  9277. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  9278. }
  9279. }
  9280. }
  9281. if (Method->isStatic())
  9282. checkThisInStaticMemberFunctionType(Method);
  9283. }
  9284. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9285. if (NewFD->isOverloadedOperator() &&
  9286. CheckOverloadedOperatorDeclaration(NewFD)) {
  9287. NewFD->setInvalidDecl();
  9288. return Redeclaration;
  9289. }
  9290. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9291. if (NewFD->getLiteralIdentifier() &&
  9292. CheckLiteralOperatorDeclaration(NewFD)) {
  9293. NewFD->setInvalidDecl();
  9294. return Redeclaration;
  9295. }
  9296. // In C++, check default arguments now that we have merged decls. Unless
  9297. // the lexical context is the class, because in this case this is done
  9298. // during delayed parsing anyway.
  9299. if (!CurContext->isRecord())
  9300. CheckCXXDefaultArguments(NewFD);
  9301. // If this function declares a builtin function, check the type of this
  9302. // declaration against the expected type for the builtin.
  9303. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9304. ASTContext::GetBuiltinTypeError Error;
  9305. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9306. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9307. // If the type of the builtin differs only in its exception
  9308. // specification, that's OK.
  9309. // FIXME: If the types do differ in this way, it would be better to
  9310. // retain the 'noexcept' form of the type.
  9311. if (!T.isNull() &&
  9312. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9313. NewFD->getType()))
  9314. // The type of this function differs from the type of the builtin,
  9315. // so forget about the builtin entirely.
  9316. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9317. }
  9318. // If this function is declared as being extern "C", then check to see if
  9319. // the function returns a UDT (class, struct, or union type) that is not C
  9320. // compatible, and if it does, warn the user.
  9321. // But, issue any diagnostic on the first declaration only.
  9322. if (Previous.empty() && NewFD->isExternC()) {
  9323. QualType R = NewFD->getReturnType();
  9324. if (R->isIncompleteType() && !R->isVoidType())
  9325. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9326. << NewFD << R;
  9327. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9328. !R->isObjCObjectPointerType())
  9329. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9330. }
  9331. // C++1z [dcl.fct]p6:
  9332. // [...] whether the function has a non-throwing exception-specification
  9333. // [is] part of the function type
  9334. //
  9335. // This results in an ABI break between C++14 and C++17 for functions whose
  9336. // declared type includes an exception-specification in a parameter or
  9337. // return type. (Exception specifications on the function itself are OK in
  9338. // most cases, and exception specifications are not permitted in most other
  9339. // contexts where they could make it into a mangling.)
  9340. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9341. auto HasNoexcept = [&](QualType T) -> bool {
  9342. // Strip off declarator chunks that could be between us and a function
  9343. // type. We don't need to look far, exception specifications are very
  9344. // restricted prior to C++17.
  9345. if (auto *RT = T->getAs<ReferenceType>())
  9346. T = RT->getPointeeType();
  9347. else if (T->isAnyPointerType())
  9348. T = T->getPointeeType();
  9349. else if (auto *MPT = T->getAs<MemberPointerType>())
  9350. T = MPT->getPointeeType();
  9351. if (auto *FPT = T->getAs<FunctionProtoType>())
  9352. if (FPT->isNothrow())
  9353. return true;
  9354. return false;
  9355. };
  9356. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9357. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9358. for (QualType T : FPT->param_types())
  9359. AnyNoexcept |= HasNoexcept(T);
  9360. if (AnyNoexcept)
  9361. Diag(NewFD->getLocation(),
  9362. diag::warn_cxx17_compat_exception_spec_in_signature)
  9363. << NewFD;
  9364. }
  9365. if (!Redeclaration && LangOpts.CUDA)
  9366. checkCUDATargetOverload(NewFD, Previous);
  9367. }
  9368. return Redeclaration;
  9369. }
  9370. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9371. // C++11 [basic.start.main]p3:
  9372. // A program that [...] declares main to be inline, static or
  9373. // constexpr is ill-formed.
  9374. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9375. // appear in a declaration of main.
  9376. // static main is not an error under C99, but we should warn about it.
  9377. // We accept _Noreturn main as an extension.
  9378. if (FD->getStorageClass() == SC_Static)
  9379. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9380. ? diag::err_static_main : diag::warn_static_main)
  9381. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9382. if (FD->isInlineSpecified())
  9383. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9384. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9385. if (DS.isNoreturnSpecified()) {
  9386. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9387. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9388. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9389. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9390. << FixItHint::CreateRemoval(NoreturnRange);
  9391. }
  9392. if (FD->isConstexpr()) {
  9393. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9394. << FD->isConsteval()
  9395. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9396. FD->setConstexprKind(CSK_unspecified);
  9397. }
  9398. if (getLangOpts().OpenCL) {
  9399. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9400. << FD->hasAttr<OpenCLKernelAttr>();
  9401. FD->setInvalidDecl();
  9402. return;
  9403. }
  9404. QualType T = FD->getType();
  9405. assert(T->isFunctionType() && "function decl is not of function type");
  9406. const FunctionType* FT = T->castAs<FunctionType>();
  9407. // Set default calling convention for main()
  9408. if (FT->getCallConv() != CC_C) {
  9409. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9410. FD->setType(QualType(FT, 0));
  9411. T = Context.getCanonicalType(FD->getType());
  9412. }
  9413. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9414. // In C with GNU extensions we allow main() to have non-integer return
  9415. // type, but we should warn about the extension, and we disable the
  9416. // implicit-return-zero rule.
  9417. // GCC in C mode accepts qualified 'int'.
  9418. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9419. FD->setHasImplicitReturnZero(true);
  9420. else {
  9421. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9422. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9423. if (RTRange.isValid())
  9424. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9425. << FixItHint::CreateReplacement(RTRange, "int");
  9426. }
  9427. } else {
  9428. // In C and C++, main magically returns 0 if you fall off the end;
  9429. // set the flag which tells us that.
  9430. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9431. // All the standards say that main() should return 'int'.
  9432. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9433. FD->setHasImplicitReturnZero(true);
  9434. else {
  9435. // Otherwise, this is just a flat-out error.
  9436. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9437. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9438. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9439. : FixItHint());
  9440. FD->setInvalidDecl(true);
  9441. }
  9442. }
  9443. // Treat protoless main() as nullary.
  9444. if (isa<FunctionNoProtoType>(FT)) return;
  9445. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9446. unsigned nparams = FTP->getNumParams();
  9447. assert(FD->getNumParams() == nparams);
  9448. bool HasExtraParameters = (nparams > 3);
  9449. if (FTP->isVariadic()) {
  9450. Diag(FD->getLocation(), diag::ext_variadic_main);
  9451. // FIXME: if we had information about the location of the ellipsis, we
  9452. // could add a FixIt hint to remove it as a parameter.
  9453. }
  9454. // Darwin passes an undocumented fourth argument of type char**. If
  9455. // other platforms start sprouting these, the logic below will start
  9456. // getting shifty.
  9457. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9458. HasExtraParameters = false;
  9459. if (HasExtraParameters) {
  9460. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9461. FD->setInvalidDecl(true);
  9462. nparams = 3;
  9463. }
  9464. // FIXME: a lot of the following diagnostics would be improved
  9465. // if we had some location information about types.
  9466. QualType CharPP =
  9467. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9468. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9469. for (unsigned i = 0; i < nparams; ++i) {
  9470. QualType AT = FTP->getParamType(i);
  9471. bool mismatch = true;
  9472. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9473. mismatch = false;
  9474. else if (Expected[i] == CharPP) {
  9475. // As an extension, the following forms are okay:
  9476. // char const **
  9477. // char const * const *
  9478. // char * const *
  9479. QualifierCollector qs;
  9480. const PointerType* PT;
  9481. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9482. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9483. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9484. Context.CharTy)) {
  9485. qs.removeConst();
  9486. mismatch = !qs.empty();
  9487. }
  9488. }
  9489. if (mismatch) {
  9490. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9491. // TODO: suggest replacing given type with expected type
  9492. FD->setInvalidDecl(true);
  9493. }
  9494. }
  9495. if (nparams == 1 && !FD->isInvalidDecl()) {
  9496. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9497. }
  9498. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9499. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9500. FD->setInvalidDecl();
  9501. }
  9502. }
  9503. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9504. QualType T = FD->getType();
  9505. assert(T->isFunctionType() && "function decl is not of function type");
  9506. const FunctionType *FT = T->castAs<FunctionType>();
  9507. // Set an implicit return of 'zero' if the function can return some integral,
  9508. // enumeration, pointer or nullptr type.
  9509. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9510. FT->getReturnType()->isAnyPointerType() ||
  9511. FT->getReturnType()->isNullPtrType())
  9512. // DllMain is exempt because a return value of zero means it failed.
  9513. if (FD->getName() != "DllMain")
  9514. FD->setHasImplicitReturnZero(true);
  9515. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9516. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9517. FD->setInvalidDecl();
  9518. }
  9519. }
  9520. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9521. // FIXME: Need strict checking. In C89, we need to check for
  9522. // any assignment, increment, decrement, function-calls, or
  9523. // commas outside of a sizeof. In C99, it's the same list,
  9524. // except that the aforementioned are allowed in unevaluated
  9525. // expressions. Everything else falls under the
  9526. // "may accept other forms of constant expressions" exception.
  9527. // (We never end up here for C++, so the constant expression
  9528. // rules there don't matter.)
  9529. const Expr *Culprit;
  9530. if (Init->isConstantInitializer(Context, false, &Culprit))
  9531. return false;
  9532. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9533. << Culprit->getSourceRange();
  9534. return true;
  9535. }
  9536. namespace {
  9537. // Visits an initialization expression to see if OrigDecl is evaluated in
  9538. // its own initialization and throws a warning if it does.
  9539. class SelfReferenceChecker
  9540. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9541. Sema &S;
  9542. Decl *OrigDecl;
  9543. bool isRecordType;
  9544. bool isPODType;
  9545. bool isReferenceType;
  9546. bool isInitList;
  9547. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9548. public:
  9549. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9550. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9551. S(S), OrigDecl(OrigDecl) {
  9552. isPODType = false;
  9553. isRecordType = false;
  9554. isReferenceType = false;
  9555. isInitList = false;
  9556. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9557. isPODType = VD->getType().isPODType(S.Context);
  9558. isRecordType = VD->getType()->isRecordType();
  9559. isReferenceType = VD->getType()->isReferenceType();
  9560. }
  9561. }
  9562. // For most expressions, just call the visitor. For initializer lists,
  9563. // track the index of the field being initialized since fields are
  9564. // initialized in order allowing use of previously initialized fields.
  9565. void CheckExpr(Expr *E) {
  9566. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9567. if (!InitList) {
  9568. Visit(E);
  9569. return;
  9570. }
  9571. // Track and increment the index here.
  9572. isInitList = true;
  9573. InitFieldIndex.push_back(0);
  9574. for (auto Child : InitList->children()) {
  9575. CheckExpr(cast<Expr>(Child));
  9576. ++InitFieldIndex.back();
  9577. }
  9578. InitFieldIndex.pop_back();
  9579. }
  9580. // Returns true if MemberExpr is checked and no further checking is needed.
  9581. // Returns false if additional checking is required.
  9582. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9583. llvm::SmallVector<FieldDecl*, 4> Fields;
  9584. Expr *Base = E;
  9585. bool ReferenceField = false;
  9586. // Get the field members used.
  9587. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9588. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9589. if (!FD)
  9590. return false;
  9591. Fields.push_back(FD);
  9592. if (FD->getType()->isReferenceType())
  9593. ReferenceField = true;
  9594. Base = ME->getBase()->IgnoreParenImpCasts();
  9595. }
  9596. // Keep checking only if the base Decl is the same.
  9597. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9598. if (!DRE || DRE->getDecl() != OrigDecl)
  9599. return false;
  9600. // A reference field can be bound to an unininitialized field.
  9601. if (CheckReference && !ReferenceField)
  9602. return true;
  9603. // Convert FieldDecls to their index number.
  9604. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9605. for (const FieldDecl *I : llvm::reverse(Fields))
  9606. UsedFieldIndex.push_back(I->getFieldIndex());
  9607. // See if a warning is needed by checking the first difference in index
  9608. // numbers. If field being used has index less than the field being
  9609. // initialized, then the use is safe.
  9610. for (auto UsedIter = UsedFieldIndex.begin(),
  9611. UsedEnd = UsedFieldIndex.end(),
  9612. OrigIter = InitFieldIndex.begin(),
  9613. OrigEnd = InitFieldIndex.end();
  9614. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9615. if (*UsedIter < *OrigIter)
  9616. return true;
  9617. if (*UsedIter > *OrigIter)
  9618. break;
  9619. }
  9620. // TODO: Add a different warning which will print the field names.
  9621. HandleDeclRefExpr(DRE);
  9622. return true;
  9623. }
  9624. // For most expressions, the cast is directly above the DeclRefExpr.
  9625. // For conditional operators, the cast can be outside the conditional
  9626. // operator if both expressions are DeclRefExpr's.
  9627. void HandleValue(Expr *E) {
  9628. E = E->IgnoreParens();
  9629. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9630. HandleDeclRefExpr(DRE);
  9631. return;
  9632. }
  9633. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9634. Visit(CO->getCond());
  9635. HandleValue(CO->getTrueExpr());
  9636. HandleValue(CO->getFalseExpr());
  9637. return;
  9638. }
  9639. if (BinaryConditionalOperator *BCO =
  9640. dyn_cast<BinaryConditionalOperator>(E)) {
  9641. Visit(BCO->getCond());
  9642. HandleValue(BCO->getFalseExpr());
  9643. return;
  9644. }
  9645. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9646. HandleValue(OVE->getSourceExpr());
  9647. return;
  9648. }
  9649. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9650. if (BO->getOpcode() == BO_Comma) {
  9651. Visit(BO->getLHS());
  9652. HandleValue(BO->getRHS());
  9653. return;
  9654. }
  9655. }
  9656. if (isa<MemberExpr>(E)) {
  9657. if (isInitList) {
  9658. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9659. false /*CheckReference*/))
  9660. return;
  9661. }
  9662. Expr *Base = E->IgnoreParenImpCasts();
  9663. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9664. // Check for static member variables and don't warn on them.
  9665. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9666. return;
  9667. Base = ME->getBase()->IgnoreParenImpCasts();
  9668. }
  9669. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9670. HandleDeclRefExpr(DRE);
  9671. return;
  9672. }
  9673. Visit(E);
  9674. }
  9675. // Reference types not handled in HandleValue are handled here since all
  9676. // uses of references are bad, not just r-value uses.
  9677. void VisitDeclRefExpr(DeclRefExpr *E) {
  9678. if (isReferenceType)
  9679. HandleDeclRefExpr(E);
  9680. }
  9681. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9682. if (E->getCastKind() == CK_LValueToRValue) {
  9683. HandleValue(E->getSubExpr());
  9684. return;
  9685. }
  9686. Inherited::VisitImplicitCastExpr(E);
  9687. }
  9688. void VisitMemberExpr(MemberExpr *E) {
  9689. if (isInitList) {
  9690. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9691. return;
  9692. }
  9693. // Don't warn on arrays since they can be treated as pointers.
  9694. if (E->getType()->canDecayToPointerType()) return;
  9695. // Warn when a non-static method call is followed by non-static member
  9696. // field accesses, which is followed by a DeclRefExpr.
  9697. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9698. bool Warn = (MD && !MD->isStatic());
  9699. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9700. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9701. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9702. Warn = false;
  9703. Base = ME->getBase()->IgnoreParenImpCasts();
  9704. }
  9705. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9706. if (Warn)
  9707. HandleDeclRefExpr(DRE);
  9708. return;
  9709. }
  9710. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9711. // Visit that expression.
  9712. Visit(Base);
  9713. }
  9714. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9715. Expr *Callee = E->getCallee();
  9716. if (isa<UnresolvedLookupExpr>(Callee))
  9717. return Inherited::VisitCXXOperatorCallExpr(E);
  9718. Visit(Callee);
  9719. for (auto Arg: E->arguments())
  9720. HandleValue(Arg->IgnoreParenImpCasts());
  9721. }
  9722. void VisitUnaryOperator(UnaryOperator *E) {
  9723. // For POD record types, addresses of its own members are well-defined.
  9724. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9725. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9726. if (!isPODType)
  9727. HandleValue(E->getSubExpr());
  9728. return;
  9729. }
  9730. if (E->isIncrementDecrementOp()) {
  9731. HandleValue(E->getSubExpr());
  9732. return;
  9733. }
  9734. Inherited::VisitUnaryOperator(E);
  9735. }
  9736. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9737. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9738. if (E->getConstructor()->isCopyConstructor()) {
  9739. Expr *ArgExpr = E->getArg(0);
  9740. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9741. if (ILE->getNumInits() == 1)
  9742. ArgExpr = ILE->getInit(0);
  9743. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9744. if (ICE->getCastKind() == CK_NoOp)
  9745. ArgExpr = ICE->getSubExpr();
  9746. HandleValue(ArgExpr);
  9747. return;
  9748. }
  9749. Inherited::VisitCXXConstructExpr(E);
  9750. }
  9751. void VisitCallExpr(CallExpr *E) {
  9752. // Treat std::move as a use.
  9753. if (E->isCallToStdMove()) {
  9754. HandleValue(E->getArg(0));
  9755. return;
  9756. }
  9757. Inherited::VisitCallExpr(E);
  9758. }
  9759. void VisitBinaryOperator(BinaryOperator *E) {
  9760. if (E->isCompoundAssignmentOp()) {
  9761. HandleValue(E->getLHS());
  9762. Visit(E->getRHS());
  9763. return;
  9764. }
  9765. Inherited::VisitBinaryOperator(E);
  9766. }
  9767. // A custom visitor for BinaryConditionalOperator is needed because the
  9768. // regular visitor would check the condition and true expression separately
  9769. // but both point to the same place giving duplicate diagnostics.
  9770. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9771. Visit(E->getCond());
  9772. Visit(E->getFalseExpr());
  9773. }
  9774. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9775. Decl* ReferenceDecl = DRE->getDecl();
  9776. if (OrigDecl != ReferenceDecl) return;
  9777. unsigned diag;
  9778. if (isReferenceType) {
  9779. diag = diag::warn_uninit_self_reference_in_reference_init;
  9780. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9781. diag = diag::warn_static_self_reference_in_init;
  9782. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9783. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9784. DRE->getDecl()->getType()->isRecordType()) {
  9785. diag = diag::warn_uninit_self_reference_in_init;
  9786. } else {
  9787. // Local variables will be handled by the CFG analysis.
  9788. return;
  9789. }
  9790. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9791. S.PDiag(diag)
  9792. << DRE->getDecl() << OrigDecl->getLocation()
  9793. << DRE->getSourceRange());
  9794. }
  9795. };
  9796. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9797. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9798. bool DirectInit) {
  9799. // Parameters arguments are occassionially constructed with itself,
  9800. // for instance, in recursive functions. Skip them.
  9801. if (isa<ParmVarDecl>(OrigDecl))
  9802. return;
  9803. E = E->IgnoreParens();
  9804. // Skip checking T a = a where T is not a record or reference type.
  9805. // Doing so is a way to silence uninitialized warnings.
  9806. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9807. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9808. if (ICE->getCastKind() == CK_LValueToRValue)
  9809. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9810. if (DRE->getDecl() == OrigDecl)
  9811. return;
  9812. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9813. }
  9814. } // end anonymous namespace
  9815. namespace {
  9816. // Simple wrapper to add the name of a variable or (if no variable is
  9817. // available) a DeclarationName into a diagnostic.
  9818. struct VarDeclOrName {
  9819. VarDecl *VDecl;
  9820. DeclarationName Name;
  9821. friend const Sema::SemaDiagnosticBuilder &
  9822. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9823. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9824. }
  9825. };
  9826. } // end anonymous namespace
  9827. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9828. DeclarationName Name, QualType Type,
  9829. TypeSourceInfo *TSI,
  9830. SourceRange Range, bool DirectInit,
  9831. Expr *Init) {
  9832. bool IsInitCapture = !VDecl;
  9833. assert((!VDecl || !VDecl->isInitCapture()) &&
  9834. "init captures are expected to be deduced prior to initialization");
  9835. VarDeclOrName VN{VDecl, Name};
  9836. DeducedType *Deduced = Type->getContainedDeducedType();
  9837. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9838. // C++11 [dcl.spec.auto]p3
  9839. if (!Init) {
  9840. assert(VDecl && "no init for init capture deduction?");
  9841. // Except for class argument deduction, and then for an initializing
  9842. // declaration only, i.e. no static at class scope or extern.
  9843. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9844. VDecl->hasExternalStorage() ||
  9845. VDecl->isStaticDataMember()) {
  9846. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9847. << VDecl->getDeclName() << Type;
  9848. return QualType();
  9849. }
  9850. }
  9851. ArrayRef<Expr*> DeduceInits;
  9852. if (Init)
  9853. DeduceInits = Init;
  9854. if (DirectInit) {
  9855. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9856. DeduceInits = PL->exprs();
  9857. }
  9858. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9859. assert(VDecl && "non-auto type for init capture deduction?");
  9860. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9861. InitializationKind Kind = InitializationKind::CreateForInit(
  9862. VDecl->getLocation(), DirectInit, Init);
  9863. // FIXME: Initialization should not be taking a mutable list of inits.
  9864. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9865. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9866. InitsCopy);
  9867. }
  9868. if (DirectInit) {
  9869. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9870. DeduceInits = IL->inits();
  9871. }
  9872. // Deduction only works if we have exactly one source expression.
  9873. if (DeduceInits.empty()) {
  9874. // It isn't possible to write this directly, but it is possible to
  9875. // end up in this situation with "auto x(some_pack...);"
  9876. Diag(Init->getBeginLoc(), IsInitCapture
  9877. ? diag::err_init_capture_no_expression
  9878. : diag::err_auto_var_init_no_expression)
  9879. << VN << Type << Range;
  9880. return QualType();
  9881. }
  9882. if (DeduceInits.size() > 1) {
  9883. Diag(DeduceInits[1]->getBeginLoc(),
  9884. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9885. : diag::err_auto_var_init_multiple_expressions)
  9886. << VN << Type << Range;
  9887. return QualType();
  9888. }
  9889. Expr *DeduceInit = DeduceInits[0];
  9890. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9891. Diag(Init->getBeginLoc(), IsInitCapture
  9892. ? diag::err_init_capture_paren_braces
  9893. : diag::err_auto_var_init_paren_braces)
  9894. << isa<InitListExpr>(Init) << VN << Type << Range;
  9895. return QualType();
  9896. }
  9897. // Expressions default to 'id' when we're in a debugger.
  9898. bool DefaultedAnyToId = false;
  9899. if (getLangOpts().DebuggerCastResultToId &&
  9900. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9901. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9902. if (Result.isInvalid()) {
  9903. return QualType();
  9904. }
  9905. Init = Result.get();
  9906. DefaultedAnyToId = true;
  9907. }
  9908. // C++ [dcl.decomp]p1:
  9909. // If the assignment-expression [...] has array type A and no ref-qualifier
  9910. // is present, e has type cv A
  9911. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9912. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9913. DeduceInit->getType()->isConstantArrayType())
  9914. return Context.getQualifiedType(DeduceInit->getType(),
  9915. Type.getQualifiers());
  9916. QualType DeducedType;
  9917. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9918. if (!IsInitCapture)
  9919. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9920. else if (isa<InitListExpr>(Init))
  9921. Diag(Range.getBegin(),
  9922. diag::err_init_capture_deduction_failure_from_init_list)
  9923. << VN
  9924. << (DeduceInit->getType().isNull() ? TSI->getType()
  9925. : DeduceInit->getType())
  9926. << DeduceInit->getSourceRange();
  9927. else
  9928. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9929. << VN << TSI->getType()
  9930. << (DeduceInit->getType().isNull() ? TSI->getType()
  9931. : DeduceInit->getType())
  9932. << DeduceInit->getSourceRange();
  9933. }
  9934. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9935. // 'id' instead of a specific object type prevents most of our usual
  9936. // checks.
  9937. // We only want to warn outside of template instantiations, though:
  9938. // inside a template, the 'id' could have come from a parameter.
  9939. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9940. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9941. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9942. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9943. }
  9944. return DeducedType;
  9945. }
  9946. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9947. Expr *Init) {
  9948. QualType DeducedType = deduceVarTypeFromInitializer(
  9949. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9950. VDecl->getSourceRange(), DirectInit, Init);
  9951. if (DeducedType.isNull()) {
  9952. VDecl->setInvalidDecl();
  9953. return true;
  9954. }
  9955. VDecl->setType(DeducedType);
  9956. assert(VDecl->isLinkageValid());
  9957. // In ARC, infer lifetime.
  9958. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9959. VDecl->setInvalidDecl();
  9960. // If this is a redeclaration, check that the type we just deduced matches
  9961. // the previously declared type.
  9962. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9963. // We never need to merge the type, because we cannot form an incomplete
  9964. // array of auto, nor deduce such a type.
  9965. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9966. }
  9967. // Check the deduced type is valid for a variable declaration.
  9968. CheckVariableDeclarationType(VDecl);
  9969. return VDecl->isInvalidDecl();
  9970. }
  9971. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  9972. SourceLocation Loc) {
  9973. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  9974. Init = CE->getSubExpr();
  9975. QualType InitType = Init->getType();
  9976. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  9977. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  9978. "shouldn't be called if type doesn't have a non-trivial C struct");
  9979. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  9980. for (auto I : ILE->inits()) {
  9981. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  9982. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  9983. continue;
  9984. SourceLocation SL = I->getExprLoc();
  9985. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  9986. }
  9987. return;
  9988. }
  9989. if (isa<ImplicitValueInitExpr>(Init)) {
  9990. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  9991. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  9992. NTCUK_Init);
  9993. } else {
  9994. // Assume all other explicit initializers involving copying some existing
  9995. // object.
  9996. // TODO: ignore any explicit initializers where we can guarantee
  9997. // copy-elision.
  9998. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  9999. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  10000. }
  10001. }
  10002. namespace {
  10003. bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
  10004. // Ignore unavailable fields. A field can be marked as unavailable explicitly
  10005. // in the source code or implicitly by the compiler if it is in a union
  10006. // defined in a system header and has non-trivial ObjC ownership
  10007. // qualifications. We don't want those fields to participate in determining
  10008. // whether the containing union is non-trivial.
  10009. return FD->hasAttr<UnavailableAttr>();
  10010. }
  10011. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  10012. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  10013. void> {
  10014. using Super =
  10015. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  10016. void>;
  10017. DiagNonTrivalCUnionDefaultInitializeVisitor(
  10018. QualType OrigTy, SourceLocation OrigLoc,
  10019. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10020. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10021. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  10022. const FieldDecl *FD, bool InNonTrivialUnion) {
  10023. if (const auto *AT = S.Context.getAsArrayType(QT))
  10024. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10025. InNonTrivialUnion);
  10026. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  10027. }
  10028. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10029. bool InNonTrivialUnion) {
  10030. if (InNonTrivialUnion)
  10031. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10032. << 1 << 0 << QT << FD->getName();
  10033. }
  10034. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10035. if (InNonTrivialUnion)
  10036. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10037. << 1 << 0 << QT << FD->getName();
  10038. }
  10039. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10040. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10041. if (RD->isUnion()) {
  10042. if (OrigLoc.isValid()) {
  10043. bool IsUnion = false;
  10044. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10045. IsUnion = OrigRD->isUnion();
  10046. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10047. << 0 << OrigTy << IsUnion << UseContext;
  10048. // Reset OrigLoc so that this diagnostic is emitted only once.
  10049. OrigLoc = SourceLocation();
  10050. }
  10051. InNonTrivialUnion = true;
  10052. }
  10053. if (InNonTrivialUnion)
  10054. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10055. << 0 << 0 << QT.getUnqualifiedType() << "";
  10056. for (const FieldDecl *FD : RD->fields())
  10057. if (!shouldIgnoreForRecordTriviality(FD))
  10058. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10059. }
  10060. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10061. // The non-trivial C union type or the struct/union type that contains a
  10062. // non-trivial C union.
  10063. QualType OrigTy;
  10064. SourceLocation OrigLoc;
  10065. Sema::NonTrivialCUnionContext UseContext;
  10066. Sema &S;
  10067. };
  10068. struct DiagNonTrivalCUnionDestructedTypeVisitor
  10069. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  10070. using Super =
  10071. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  10072. DiagNonTrivalCUnionDestructedTypeVisitor(
  10073. QualType OrigTy, SourceLocation OrigLoc,
  10074. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10075. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10076. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  10077. const FieldDecl *FD, bool InNonTrivialUnion) {
  10078. if (const auto *AT = S.Context.getAsArrayType(QT))
  10079. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10080. InNonTrivialUnion);
  10081. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  10082. }
  10083. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10084. bool InNonTrivialUnion) {
  10085. if (InNonTrivialUnion)
  10086. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10087. << 1 << 1 << QT << FD->getName();
  10088. }
  10089. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10090. if (InNonTrivialUnion)
  10091. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10092. << 1 << 1 << QT << FD->getName();
  10093. }
  10094. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10095. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10096. if (RD->isUnion()) {
  10097. if (OrigLoc.isValid()) {
  10098. bool IsUnion = false;
  10099. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10100. IsUnion = OrigRD->isUnion();
  10101. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10102. << 1 << OrigTy << IsUnion << UseContext;
  10103. // Reset OrigLoc so that this diagnostic is emitted only once.
  10104. OrigLoc = SourceLocation();
  10105. }
  10106. InNonTrivialUnion = true;
  10107. }
  10108. if (InNonTrivialUnion)
  10109. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10110. << 0 << 1 << QT.getUnqualifiedType() << "";
  10111. for (const FieldDecl *FD : RD->fields())
  10112. if (!shouldIgnoreForRecordTriviality(FD))
  10113. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10114. }
  10115. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10116. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  10117. bool InNonTrivialUnion) {}
  10118. // The non-trivial C union type or the struct/union type that contains a
  10119. // non-trivial C union.
  10120. QualType OrigTy;
  10121. SourceLocation OrigLoc;
  10122. Sema::NonTrivialCUnionContext UseContext;
  10123. Sema &S;
  10124. };
  10125. struct DiagNonTrivalCUnionCopyVisitor
  10126. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  10127. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  10128. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  10129. Sema::NonTrivialCUnionContext UseContext,
  10130. Sema &S)
  10131. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10132. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  10133. const FieldDecl *FD, bool InNonTrivialUnion) {
  10134. if (const auto *AT = S.Context.getAsArrayType(QT))
  10135. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10136. InNonTrivialUnion);
  10137. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  10138. }
  10139. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10140. bool InNonTrivialUnion) {
  10141. if (InNonTrivialUnion)
  10142. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10143. << 1 << 2 << QT << FD->getName();
  10144. }
  10145. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10146. if (InNonTrivialUnion)
  10147. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10148. << 1 << 2 << QT << FD->getName();
  10149. }
  10150. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10151. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10152. if (RD->isUnion()) {
  10153. if (OrigLoc.isValid()) {
  10154. bool IsUnion = false;
  10155. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10156. IsUnion = OrigRD->isUnion();
  10157. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10158. << 2 << OrigTy << IsUnion << UseContext;
  10159. // Reset OrigLoc so that this diagnostic is emitted only once.
  10160. OrigLoc = SourceLocation();
  10161. }
  10162. InNonTrivialUnion = true;
  10163. }
  10164. if (InNonTrivialUnion)
  10165. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10166. << 0 << 2 << QT.getUnqualifiedType() << "";
  10167. for (const FieldDecl *FD : RD->fields())
  10168. if (!shouldIgnoreForRecordTriviality(FD))
  10169. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10170. }
  10171. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  10172. const FieldDecl *FD, bool InNonTrivialUnion) {}
  10173. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10174. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  10175. bool InNonTrivialUnion) {}
  10176. // The non-trivial C union type or the struct/union type that contains a
  10177. // non-trivial C union.
  10178. QualType OrigTy;
  10179. SourceLocation OrigLoc;
  10180. Sema::NonTrivialCUnionContext UseContext;
  10181. Sema &S;
  10182. };
  10183. } // namespace
  10184. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  10185. NonTrivialCUnionContext UseContext,
  10186. unsigned NonTrivialKind) {
  10187. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10188. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  10189. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  10190. "shouldn't be called if type doesn't have a non-trivial C union");
  10191. if ((NonTrivialKind & NTCUK_Init) &&
  10192. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10193. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  10194. .visit(QT, nullptr, false);
  10195. if ((NonTrivialKind & NTCUK_Destruct) &&
  10196. QT.hasNonTrivialToPrimitiveDestructCUnion())
  10197. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  10198. .visit(QT, nullptr, false);
  10199. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10200. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10201. .visit(QT, nullptr, false);
  10202. }
  10203. /// AddInitializerToDecl - Adds the initializer Init to the
  10204. /// declaration dcl. If DirectInit is true, this is C++ direct
  10205. /// initialization rather than copy initialization.
  10206. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10207. // If there is no declaration, there was an error parsing it. Just ignore
  10208. // the initializer.
  10209. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10210. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10211. return;
  10212. }
  10213. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10214. // Pure-specifiers are handled in ActOnPureSpecifier.
  10215. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10216. << Method->getDeclName() << Init->getSourceRange();
  10217. Method->setInvalidDecl();
  10218. return;
  10219. }
  10220. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10221. if (!VDecl) {
  10222. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10223. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10224. RealDecl->setInvalidDecl();
  10225. return;
  10226. }
  10227. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10228. if (VDecl->getType()->isUndeducedType()) {
  10229. // Attempt typo correction early so that the type of the init expression can
  10230. // be deduced based on the chosen correction if the original init contains a
  10231. // TypoExpr.
  10232. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10233. if (!Res.isUsable()) {
  10234. RealDecl->setInvalidDecl();
  10235. return;
  10236. }
  10237. Init = Res.get();
  10238. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10239. return;
  10240. }
  10241. // dllimport cannot be used on variable definitions.
  10242. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10243. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10244. VDecl->setInvalidDecl();
  10245. return;
  10246. }
  10247. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10248. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10249. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10250. VDecl->setInvalidDecl();
  10251. return;
  10252. }
  10253. if (!VDecl->getType()->isDependentType()) {
  10254. // A definition must end up with a complete type, which means it must be
  10255. // complete with the restriction that an array type might be completed by
  10256. // the initializer; note that later code assumes this restriction.
  10257. QualType BaseDeclType = VDecl->getType();
  10258. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10259. BaseDeclType = Array->getElementType();
  10260. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10261. diag::err_typecheck_decl_incomplete_type)) {
  10262. RealDecl->setInvalidDecl();
  10263. return;
  10264. }
  10265. // The variable can not have an abstract class type.
  10266. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10267. diag::err_abstract_type_in_decl,
  10268. AbstractVariableType))
  10269. VDecl->setInvalidDecl();
  10270. }
  10271. // If adding the initializer will turn this declaration into a definition,
  10272. // and we already have a definition for this variable, diagnose or otherwise
  10273. // handle the situation.
  10274. VarDecl *Def;
  10275. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  10276. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10277. !VDecl->isThisDeclarationADemotedDefinition() &&
  10278. checkVarDeclRedefinition(Def, VDecl))
  10279. return;
  10280. if (getLangOpts().CPlusPlus) {
  10281. // C++ [class.static.data]p4
  10282. // If a static data member is of const integral or const
  10283. // enumeration type, its declaration in the class definition can
  10284. // specify a constant-initializer which shall be an integral
  10285. // constant expression (5.19). In that case, the member can appear
  10286. // in integral constant expressions. The member shall still be
  10287. // defined in a namespace scope if it is used in the program and the
  10288. // namespace scope definition shall not contain an initializer.
  10289. //
  10290. // We already performed a redefinition check above, but for static
  10291. // data members we also need to check whether there was an in-class
  10292. // declaration with an initializer.
  10293. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10294. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10295. << VDecl->getDeclName();
  10296. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10297. diag::note_previous_initializer)
  10298. << 0;
  10299. return;
  10300. }
  10301. if (VDecl->hasLocalStorage())
  10302. setFunctionHasBranchProtectedScope();
  10303. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10304. VDecl->setInvalidDecl();
  10305. return;
  10306. }
  10307. }
  10308. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10309. // a kernel function cannot be initialized."
  10310. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10311. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10312. VDecl->setInvalidDecl();
  10313. return;
  10314. }
  10315. // Get the decls type and save a reference for later, since
  10316. // CheckInitializerTypes may change it.
  10317. QualType DclT = VDecl->getType(), SavT = DclT;
  10318. // Expressions default to 'id' when we're in a debugger
  10319. // and we are assigning it to a variable of Objective-C pointer type.
  10320. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10321. Init->getType() == Context.UnknownAnyTy) {
  10322. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10323. if (Result.isInvalid()) {
  10324. VDecl->setInvalidDecl();
  10325. return;
  10326. }
  10327. Init = Result.get();
  10328. }
  10329. // Perform the initialization.
  10330. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  10331. if (!VDecl->isInvalidDecl()) {
  10332. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10333. InitializationKind Kind = InitializationKind::CreateForInit(
  10334. VDecl->getLocation(), DirectInit, Init);
  10335. MultiExprArg Args = Init;
  10336. if (CXXDirectInit)
  10337. Args = MultiExprArg(CXXDirectInit->getExprs(),
  10338. CXXDirectInit->getNumExprs());
  10339. // Try to correct any TypoExprs in the initialization arguments.
  10340. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  10341. ExprResult Res = CorrectDelayedTyposInExpr(
  10342. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  10343. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  10344. return Init.Failed() ? ExprError() : E;
  10345. });
  10346. if (Res.isInvalid()) {
  10347. VDecl->setInvalidDecl();
  10348. } else if (Res.get() != Args[Idx]) {
  10349. Args[Idx] = Res.get();
  10350. }
  10351. }
  10352. if (VDecl->isInvalidDecl())
  10353. return;
  10354. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  10355. /*TopLevelOfInitList=*/false,
  10356. /*TreatUnavailableAsInvalid=*/false);
  10357. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  10358. if (Result.isInvalid()) {
  10359. VDecl->setInvalidDecl();
  10360. return;
  10361. }
  10362. Init = Result.getAs<Expr>();
  10363. }
  10364. // Check for self-references within variable initializers.
  10365. // Variables declared within a function/method body (except for references)
  10366. // are handled by a dataflow analysis.
  10367. // This is undefined behavior in C++, but valid in C.
  10368. if (getLangOpts().CPlusPlus) {
  10369. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  10370. VDecl->getType()->isReferenceType()) {
  10371. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  10372. }
  10373. }
  10374. // If the type changed, it means we had an incomplete type that was
  10375. // completed by the initializer. For example:
  10376. // int ary[] = { 1, 3, 5 };
  10377. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  10378. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  10379. VDecl->setType(DclT);
  10380. if (!VDecl->isInvalidDecl()) {
  10381. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  10382. if (VDecl->hasAttr<BlocksAttr>())
  10383. checkRetainCycles(VDecl, Init);
  10384. // It is safe to assign a weak reference into a strong variable.
  10385. // Although this code can still have problems:
  10386. // id x = self.weakProp;
  10387. // id y = self.weakProp;
  10388. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  10389. // paths through the function. This should be revisited if
  10390. // -Wrepeated-use-of-weak is made flow-sensitive.
  10391. if (FunctionScopeInfo *FSI = getCurFunction())
  10392. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  10393. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  10394. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  10395. Init->getBeginLoc()))
  10396. FSI->markSafeWeakUse(Init);
  10397. }
  10398. // The initialization is usually a full-expression.
  10399. //
  10400. // FIXME: If this is a braced initialization of an aggregate, it is not
  10401. // an expression, and each individual field initializer is a separate
  10402. // full-expression. For instance, in:
  10403. //
  10404. // struct Temp { ~Temp(); };
  10405. // struct S { S(Temp); };
  10406. // struct T { S a, b; } t = { Temp(), Temp() }
  10407. //
  10408. // we should destroy the first Temp before constructing the second.
  10409. ExprResult Result =
  10410. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  10411. /*DiscardedValue*/ false, VDecl->isConstexpr());
  10412. if (Result.isInvalid()) {
  10413. VDecl->setInvalidDecl();
  10414. return;
  10415. }
  10416. Init = Result.get();
  10417. // Attach the initializer to the decl.
  10418. VDecl->setInit(Init);
  10419. if (VDecl->isLocalVarDecl()) {
  10420. // Don't check the initializer if the declaration is malformed.
  10421. if (VDecl->isInvalidDecl()) {
  10422. // do nothing
  10423. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  10424. // This is true even in C++ for OpenCL.
  10425. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  10426. CheckForConstantInitializer(Init, DclT);
  10427. // Otherwise, C++ does not restrict the initializer.
  10428. } else if (getLangOpts().CPlusPlus) {
  10429. // do nothing
  10430. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  10431. // static storage duration shall be constant expressions or string literals.
  10432. } else if (VDecl->getStorageClass() == SC_Static) {
  10433. CheckForConstantInitializer(Init, DclT);
  10434. // C89 is stricter than C99 for aggregate initializers.
  10435. // C89 6.5.7p3: All the expressions [...] in an initializer list
  10436. // for an object that has aggregate or union type shall be
  10437. // constant expressions.
  10438. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  10439. isa<InitListExpr>(Init)) {
  10440. const Expr *Culprit;
  10441. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  10442. Diag(Culprit->getExprLoc(),
  10443. diag::ext_aggregate_init_not_constant)
  10444. << Culprit->getSourceRange();
  10445. }
  10446. }
  10447. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  10448. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  10449. if (VDecl->hasLocalStorage())
  10450. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  10451. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  10452. VDecl->getLexicalDeclContext()->isRecord()) {
  10453. // This is an in-class initialization for a static data member, e.g.,
  10454. //
  10455. // struct S {
  10456. // static const int value = 17;
  10457. // };
  10458. // C++ [class.mem]p4:
  10459. // A member-declarator can contain a constant-initializer only
  10460. // if it declares a static member (9.4) of const integral or
  10461. // const enumeration type, see 9.4.2.
  10462. //
  10463. // C++11 [class.static.data]p3:
  10464. // If a non-volatile non-inline const static data member is of integral
  10465. // or enumeration type, its declaration in the class definition can
  10466. // specify a brace-or-equal-initializer in which every initializer-clause
  10467. // that is an assignment-expression is a constant expression. A static
  10468. // data member of literal type can be declared in the class definition
  10469. // with the constexpr specifier; if so, its declaration shall specify a
  10470. // brace-or-equal-initializer in which every initializer-clause that is
  10471. // an assignment-expression is a constant expression.
  10472. // Do nothing on dependent types.
  10473. if (DclT->isDependentType()) {
  10474. // Allow any 'static constexpr' members, whether or not they are of literal
  10475. // type. We separately check that every constexpr variable is of literal
  10476. // type.
  10477. } else if (VDecl->isConstexpr()) {
  10478. // Require constness.
  10479. } else if (!DclT.isConstQualified()) {
  10480. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  10481. << Init->getSourceRange();
  10482. VDecl->setInvalidDecl();
  10483. // We allow integer constant expressions in all cases.
  10484. } else if (DclT->isIntegralOrEnumerationType()) {
  10485. // Check whether the expression is a constant expression.
  10486. SourceLocation Loc;
  10487. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  10488. // In C++11, a non-constexpr const static data member with an
  10489. // in-class initializer cannot be volatile.
  10490. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  10491. else if (Init->isValueDependent())
  10492. ; // Nothing to check.
  10493. else if (Init->isIntegerConstantExpr(Context, &Loc))
  10494. ; // Ok, it's an ICE!
  10495. else if (Init->getType()->isScopedEnumeralType() &&
  10496. Init->isCXX11ConstantExpr(Context))
  10497. ; // Ok, it is a scoped-enum constant expression.
  10498. else if (Init->isEvaluatable(Context)) {
  10499. // If we can constant fold the initializer through heroics, accept it,
  10500. // but report this as a use of an extension for -pedantic.
  10501. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  10502. << Init->getSourceRange();
  10503. } else {
  10504. // Otherwise, this is some crazy unknown case. Report the issue at the
  10505. // location provided by the isIntegerConstantExpr failed check.
  10506. Diag(Loc, diag::err_in_class_initializer_non_constant)
  10507. << Init->getSourceRange();
  10508. VDecl->setInvalidDecl();
  10509. }
  10510. // We allow foldable floating-point constants as an extension.
  10511. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  10512. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  10513. // it anyway and provide a fixit to add the 'constexpr'.
  10514. if (getLangOpts().CPlusPlus11) {
  10515. Diag(VDecl->getLocation(),
  10516. diag::ext_in_class_initializer_float_type_cxx11)
  10517. << DclT << Init->getSourceRange();
  10518. Diag(VDecl->getBeginLoc(),
  10519. diag::note_in_class_initializer_float_type_cxx11)
  10520. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10521. } else {
  10522. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10523. << DclT << Init->getSourceRange();
  10524. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10525. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10526. << Init->getSourceRange();
  10527. VDecl->setInvalidDecl();
  10528. }
  10529. }
  10530. // Suggest adding 'constexpr' in C++11 for literal types.
  10531. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10532. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10533. << DclT << Init->getSourceRange()
  10534. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10535. VDecl->setConstexpr(true);
  10536. } else {
  10537. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10538. << DclT << Init->getSourceRange();
  10539. VDecl->setInvalidDecl();
  10540. }
  10541. } else if (VDecl->isFileVarDecl()) {
  10542. // In C, extern is typically used to avoid tentative definitions when
  10543. // declaring variables in headers, but adding an intializer makes it a
  10544. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10545. // In C++, extern is often used to give implictly static const variables
  10546. // external linkage, so don't warn in that case. If selectany is present,
  10547. // this might be header code intended for C and C++ inclusion, so apply the
  10548. // C++ rules.
  10549. if (VDecl->getStorageClass() == SC_Extern &&
  10550. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10551. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10552. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10553. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10554. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10555. // In Microsoft C++ mode, a const variable defined in namespace scope has
  10556. // external linkage by default if the variable is declared with
  10557. // __declspec(dllexport).
  10558. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10559. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  10560. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  10561. VDecl->setStorageClass(SC_Extern);
  10562. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10563. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10564. CheckForConstantInitializer(Init, DclT);
  10565. }
  10566. QualType InitType = Init->getType();
  10567. if (!InitType.isNull() &&
  10568. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10569. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  10570. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  10571. // We will represent direct-initialization similarly to copy-initialization:
  10572. // int x(1); -as-> int x = 1;
  10573. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10574. //
  10575. // Clients that want to distinguish between the two forms, can check for
  10576. // direct initializer using VarDecl::getInitStyle().
  10577. // A major benefit is that clients that don't particularly care about which
  10578. // exactly form was it (like the CodeGen) can handle both cases without
  10579. // special case code.
  10580. // C++ 8.5p11:
  10581. // The form of initialization (using parentheses or '=') is generally
  10582. // insignificant, but does matter when the entity being initialized has a
  10583. // class type.
  10584. if (CXXDirectInit) {
  10585. assert(DirectInit && "Call-style initializer must be direct init.");
  10586. VDecl->setInitStyle(VarDecl::CallInit);
  10587. } else if (DirectInit) {
  10588. // This must be list-initialization. No other way is direct-initialization.
  10589. VDecl->setInitStyle(VarDecl::ListInit);
  10590. }
  10591. CheckCompleteVariableDeclaration(VDecl);
  10592. }
  10593. /// ActOnInitializerError - Given that there was an error parsing an
  10594. /// initializer for the given declaration, try to return to some form
  10595. /// of sanity.
  10596. void Sema::ActOnInitializerError(Decl *D) {
  10597. // Our main concern here is re-establishing invariants like "a
  10598. // variable's type is either dependent or complete".
  10599. if (!D || D->isInvalidDecl()) return;
  10600. VarDecl *VD = dyn_cast<VarDecl>(D);
  10601. if (!VD) return;
  10602. // Bindings are not usable if we can't make sense of the initializer.
  10603. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10604. for (auto *BD : DD->bindings())
  10605. BD->setInvalidDecl();
  10606. // Auto types are meaningless if we can't make sense of the initializer.
  10607. if (ParsingInitForAutoVars.count(D)) {
  10608. D->setInvalidDecl();
  10609. return;
  10610. }
  10611. QualType Ty = VD->getType();
  10612. if (Ty->isDependentType()) return;
  10613. // Require a complete type.
  10614. if (RequireCompleteType(VD->getLocation(),
  10615. Context.getBaseElementType(Ty),
  10616. diag::err_typecheck_decl_incomplete_type)) {
  10617. VD->setInvalidDecl();
  10618. return;
  10619. }
  10620. // Require a non-abstract type.
  10621. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10622. diag::err_abstract_type_in_decl,
  10623. AbstractVariableType)) {
  10624. VD->setInvalidDecl();
  10625. return;
  10626. }
  10627. // Don't bother complaining about constructors or destructors,
  10628. // though.
  10629. }
  10630. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10631. // If there is no declaration, there was an error parsing it. Just ignore it.
  10632. if (!RealDecl)
  10633. return;
  10634. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10635. QualType Type = Var->getType();
  10636. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10637. if (isa<DecompositionDecl>(RealDecl)) {
  10638. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10639. Var->setInvalidDecl();
  10640. return;
  10641. }
  10642. if (Type->isUndeducedType() &&
  10643. DeduceVariableDeclarationType(Var, false, nullptr))
  10644. return;
  10645. // C++11 [class.static.data]p3: A static data member can be declared with
  10646. // the constexpr specifier; if so, its declaration shall specify
  10647. // a brace-or-equal-initializer.
  10648. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10649. // the definition of a variable [...] or the declaration of a static data
  10650. // member.
  10651. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10652. !Var->isThisDeclarationADemotedDefinition()) {
  10653. if (Var->isStaticDataMember()) {
  10654. // C++1z removes the relevant rule; the in-class declaration is always
  10655. // a definition there.
  10656. if (!getLangOpts().CPlusPlus17 &&
  10657. !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  10658. Diag(Var->getLocation(),
  10659. diag::err_constexpr_static_mem_var_requires_init)
  10660. << Var->getDeclName();
  10661. Var->setInvalidDecl();
  10662. return;
  10663. }
  10664. } else {
  10665. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10666. Var->setInvalidDecl();
  10667. return;
  10668. }
  10669. }
  10670. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10671. // be initialized.
  10672. if (!Var->isInvalidDecl() &&
  10673. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10674. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10675. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10676. Var->setInvalidDecl();
  10677. return;
  10678. }
  10679. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  10680. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  10681. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10682. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  10683. NTCUC_DefaultInitializedObject, NTCUK_Init);
  10684. switch (DefKind) {
  10685. case VarDecl::Definition:
  10686. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10687. break;
  10688. // We have an out-of-line definition of a static data member
  10689. // that has an in-class initializer, so we type-check this like
  10690. // a declaration.
  10691. //
  10692. LLVM_FALLTHROUGH;
  10693. case VarDecl::DeclarationOnly:
  10694. // It's only a declaration.
  10695. // Block scope. C99 6.7p7: If an identifier for an object is
  10696. // declared with no linkage (C99 6.2.2p6), the type for the
  10697. // object shall be complete.
  10698. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10699. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10700. RequireCompleteType(Var->getLocation(), Type,
  10701. diag::err_typecheck_decl_incomplete_type))
  10702. Var->setInvalidDecl();
  10703. // Make sure that the type is not abstract.
  10704. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10705. RequireNonAbstractType(Var->getLocation(), Type,
  10706. diag::err_abstract_type_in_decl,
  10707. AbstractVariableType))
  10708. Var->setInvalidDecl();
  10709. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10710. Var->getStorageClass() == SC_PrivateExtern) {
  10711. Diag(Var->getLocation(), diag::warn_private_extern);
  10712. Diag(Var->getLocation(), diag::note_private_extern);
  10713. }
  10714. return;
  10715. case VarDecl::TentativeDefinition:
  10716. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10717. // object that has file scope without an initializer, and without a
  10718. // storage-class specifier or with the storage-class specifier "static",
  10719. // constitutes a tentative definition. Note: A tentative definition with
  10720. // external linkage is valid (C99 6.2.2p5).
  10721. if (!Var->isInvalidDecl()) {
  10722. if (const IncompleteArrayType *ArrayT
  10723. = Context.getAsIncompleteArrayType(Type)) {
  10724. if (RequireCompleteType(Var->getLocation(),
  10725. ArrayT->getElementType(),
  10726. diag::err_illegal_decl_array_incomplete_type))
  10727. Var->setInvalidDecl();
  10728. } else if (Var->getStorageClass() == SC_Static) {
  10729. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10730. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10731. // declared type shall not be an incomplete type.
  10732. // NOTE: code such as the following
  10733. // static struct s;
  10734. // struct s { int a; };
  10735. // is accepted by gcc. Hence here we issue a warning instead of
  10736. // an error and we do not invalidate the static declaration.
  10737. // NOTE: to avoid multiple warnings, only check the first declaration.
  10738. if (Var->isFirstDecl())
  10739. RequireCompleteType(Var->getLocation(), Type,
  10740. diag::ext_typecheck_decl_incomplete_type);
  10741. }
  10742. }
  10743. // Record the tentative definition; we're done.
  10744. if (!Var->isInvalidDecl())
  10745. TentativeDefinitions.push_back(Var);
  10746. return;
  10747. }
  10748. // Provide a specific diagnostic for uninitialized variable
  10749. // definitions with incomplete array type.
  10750. if (Type->isIncompleteArrayType()) {
  10751. Diag(Var->getLocation(),
  10752. diag::err_typecheck_incomplete_array_needs_initializer);
  10753. Var->setInvalidDecl();
  10754. return;
  10755. }
  10756. // Provide a specific diagnostic for uninitialized variable
  10757. // definitions with reference type.
  10758. if (Type->isReferenceType()) {
  10759. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10760. << Var->getDeclName()
  10761. << SourceRange(Var->getLocation(), Var->getLocation());
  10762. Var->setInvalidDecl();
  10763. return;
  10764. }
  10765. // Do not attempt to type-check the default initializer for a
  10766. // variable with dependent type.
  10767. if (Type->isDependentType())
  10768. return;
  10769. if (Var->isInvalidDecl())
  10770. return;
  10771. if (!Var->hasAttr<AliasAttr>()) {
  10772. if (RequireCompleteType(Var->getLocation(),
  10773. Context.getBaseElementType(Type),
  10774. diag::err_typecheck_decl_incomplete_type)) {
  10775. Var->setInvalidDecl();
  10776. return;
  10777. }
  10778. } else {
  10779. return;
  10780. }
  10781. // The variable can not have an abstract class type.
  10782. if (RequireNonAbstractType(Var->getLocation(), Type,
  10783. diag::err_abstract_type_in_decl,
  10784. AbstractVariableType)) {
  10785. Var->setInvalidDecl();
  10786. return;
  10787. }
  10788. // Check for jumps past the implicit initializer. C++0x
  10789. // clarifies that this applies to a "variable with automatic
  10790. // storage duration", not a "local variable".
  10791. // C++11 [stmt.dcl]p3
  10792. // A program that jumps from a point where a variable with automatic
  10793. // storage duration is not in scope to a point where it is in scope is
  10794. // ill-formed unless the variable has scalar type, class type with a
  10795. // trivial default constructor and a trivial destructor, a cv-qualified
  10796. // version of one of these types, or an array of one of the preceding
  10797. // types and is declared without an initializer.
  10798. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10799. if (const RecordType *Record
  10800. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10801. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10802. // Mark the function (if we're in one) for further checking even if the
  10803. // looser rules of C++11 do not require such checks, so that we can
  10804. // diagnose incompatibilities with C++98.
  10805. if (!CXXRecord->isPOD())
  10806. setFunctionHasBranchProtectedScope();
  10807. }
  10808. }
  10809. // In OpenCL, we can't initialize objects in the __local address space,
  10810. // even implicitly, so don't synthesize an implicit initializer.
  10811. if (getLangOpts().OpenCL &&
  10812. Var->getType().getAddressSpace() == LangAS::opencl_local)
  10813. return;
  10814. // C++03 [dcl.init]p9:
  10815. // If no initializer is specified for an object, and the
  10816. // object is of (possibly cv-qualified) non-POD class type (or
  10817. // array thereof), the object shall be default-initialized; if
  10818. // the object is of const-qualified type, the underlying class
  10819. // type shall have a user-declared default
  10820. // constructor. Otherwise, if no initializer is specified for
  10821. // a non- static object, the object and its subobjects, if
  10822. // any, have an indeterminate initial value); if the object
  10823. // or any of its subobjects are of const-qualified type, the
  10824. // program is ill-formed.
  10825. // C++0x [dcl.init]p11:
  10826. // If no initializer is specified for an object, the object is
  10827. // default-initialized; [...].
  10828. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10829. InitializationKind Kind
  10830. = InitializationKind::CreateDefault(Var->getLocation());
  10831. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10832. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10833. if (Init.isInvalid())
  10834. Var->setInvalidDecl();
  10835. else if (Init.get()) {
  10836. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10837. // This is important for template substitution.
  10838. Var->setInitStyle(VarDecl::CallInit);
  10839. }
  10840. CheckCompleteVariableDeclaration(Var);
  10841. }
  10842. }
  10843. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10844. // If there is no declaration, there was an error parsing it. Ignore it.
  10845. if (!D)
  10846. return;
  10847. VarDecl *VD = dyn_cast<VarDecl>(D);
  10848. if (!VD) {
  10849. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10850. D->setInvalidDecl();
  10851. return;
  10852. }
  10853. VD->setCXXForRangeDecl(true);
  10854. // for-range-declaration cannot be given a storage class specifier.
  10855. int Error = -1;
  10856. switch (VD->getStorageClass()) {
  10857. case SC_None:
  10858. break;
  10859. case SC_Extern:
  10860. Error = 0;
  10861. break;
  10862. case SC_Static:
  10863. Error = 1;
  10864. break;
  10865. case SC_PrivateExtern:
  10866. Error = 2;
  10867. break;
  10868. case SC_Auto:
  10869. Error = 3;
  10870. break;
  10871. case SC_Register:
  10872. Error = 4;
  10873. break;
  10874. }
  10875. if (Error != -1) {
  10876. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10877. << VD->getDeclName() << Error;
  10878. D->setInvalidDecl();
  10879. }
  10880. }
  10881. StmtResult
  10882. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10883. IdentifierInfo *Ident,
  10884. ParsedAttributes &Attrs,
  10885. SourceLocation AttrEnd) {
  10886. // C++1y [stmt.iter]p1:
  10887. // A range-based for statement of the form
  10888. // for ( for-range-identifier : for-range-initializer ) statement
  10889. // is equivalent to
  10890. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10891. DeclSpec DS(Attrs.getPool().getFactory());
  10892. const char *PrevSpec;
  10893. unsigned DiagID;
  10894. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10895. getPrintingPolicy());
  10896. Declarator D(DS, DeclaratorContext::ForContext);
  10897. D.SetIdentifier(Ident, IdentLoc);
  10898. D.takeAttributes(Attrs, AttrEnd);
  10899. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10900. IdentLoc);
  10901. Decl *Var = ActOnDeclarator(S, D);
  10902. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10903. FinalizeDeclaration(Var);
  10904. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10905. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10906. }
  10907. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10908. if (var->isInvalidDecl()) return;
  10909. if (getLangOpts().OpenCL) {
  10910. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10911. // initialiser
  10912. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10913. !var->hasInit()) {
  10914. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10915. << 1 /*Init*/;
  10916. var->setInvalidDecl();
  10917. return;
  10918. }
  10919. }
  10920. // In Objective-C, don't allow jumps past the implicit initialization of a
  10921. // local retaining variable.
  10922. if (getLangOpts().ObjC &&
  10923. var->hasLocalStorage()) {
  10924. switch (var->getType().getObjCLifetime()) {
  10925. case Qualifiers::OCL_None:
  10926. case Qualifiers::OCL_ExplicitNone:
  10927. case Qualifiers::OCL_Autoreleasing:
  10928. break;
  10929. case Qualifiers::OCL_Weak:
  10930. case Qualifiers::OCL_Strong:
  10931. setFunctionHasBranchProtectedScope();
  10932. break;
  10933. }
  10934. }
  10935. if (var->hasLocalStorage() &&
  10936. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10937. setFunctionHasBranchProtectedScope();
  10938. // Warn about externally-visible variables being defined without a
  10939. // prior declaration. We only want to do this for global
  10940. // declarations, but we also specifically need to avoid doing it for
  10941. // class members because the linkage of an anonymous class can
  10942. // change if it's later given a typedef name.
  10943. if (var->isThisDeclarationADefinition() &&
  10944. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10945. var->isExternallyVisible() && var->hasLinkage() &&
  10946. !var->isInline() && !var->getDescribedVarTemplate() &&
  10947. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10948. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10949. var->getLocation())) {
  10950. // Find a previous declaration that's not a definition.
  10951. VarDecl *prev = var->getPreviousDecl();
  10952. while (prev && prev->isThisDeclarationADefinition())
  10953. prev = prev->getPreviousDecl();
  10954. if (!prev) {
  10955. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10956. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  10957. << /* variable */ 0;
  10958. }
  10959. }
  10960. // Cache the result of checking for constant initialization.
  10961. Optional<bool> CacheHasConstInit;
  10962. const Expr *CacheCulprit = nullptr;
  10963. auto checkConstInit = [&]() mutable {
  10964. if (!CacheHasConstInit)
  10965. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10966. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10967. return *CacheHasConstInit;
  10968. };
  10969. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10970. if (var->getType().isDestructedType()) {
  10971. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10972. // The type of an object with thread storage duration shall not
  10973. // have a non-trivial destructor.
  10974. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10975. if (getLangOpts().CPlusPlus11)
  10976. Diag(var->getLocation(), diag::note_use_thread_local);
  10977. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10978. if (!checkConstInit()) {
  10979. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10980. // An object of thread storage duration shall not require dynamic
  10981. // initialization.
  10982. // FIXME: Need strict checking here.
  10983. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10984. << CacheCulprit->getSourceRange();
  10985. if (getLangOpts().CPlusPlus11)
  10986. Diag(var->getLocation(), diag::note_use_thread_local);
  10987. }
  10988. }
  10989. }
  10990. // Apply section attributes and pragmas to global variables.
  10991. bool GlobalStorage = var->hasGlobalStorage();
  10992. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10993. !inTemplateInstantiation()) {
  10994. PragmaStack<StringLiteral *> *Stack = nullptr;
  10995. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10996. if (var->getType().isConstQualified())
  10997. Stack = &ConstSegStack;
  10998. else if (!var->getInit()) {
  10999. Stack = &BSSSegStack;
  11000. SectionFlags |= ASTContext::PSF_Write;
  11001. } else {
  11002. Stack = &DataSegStack;
  11003. SectionFlags |= ASTContext::PSF_Write;
  11004. }
  11005. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>())
  11006. var->addAttr(SectionAttr::CreateImplicit(
  11007. Context, Stack->CurrentValue->getString(),
  11008. Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  11009. SectionAttr::Declspec_allocate));
  11010. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  11011. if (UnifySection(SA->getName(), SectionFlags, var))
  11012. var->dropAttr<SectionAttr>();
  11013. // Apply the init_seg attribute if this has an initializer. If the
  11014. // initializer turns out to not be dynamic, we'll end up ignoring this
  11015. // attribute.
  11016. if (CurInitSeg && var->getInit())
  11017. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  11018. CurInitSegLoc,
  11019. AttributeCommonInfo::AS_Pragma));
  11020. }
  11021. // All the following checks are C++ only.
  11022. if (!getLangOpts().CPlusPlus) {
  11023. // If this variable must be emitted, add it as an initializer for the
  11024. // current module.
  11025. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11026. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11027. return;
  11028. }
  11029. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  11030. CheckCompleteDecompositionDeclaration(DD);
  11031. QualType type = var->getType();
  11032. if (type->isDependentType()) return;
  11033. if (var->hasAttr<BlocksAttr>())
  11034. getCurFunction()->addByrefBlockVar(var);
  11035. Expr *Init = var->getInit();
  11036. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  11037. QualType baseType = Context.getBaseElementType(type);
  11038. if (Init && !Init->isValueDependent()) {
  11039. if (var->isConstexpr()) {
  11040. SmallVector<PartialDiagnosticAt, 8> Notes;
  11041. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  11042. SourceLocation DiagLoc = var->getLocation();
  11043. // If the note doesn't add any useful information other than a source
  11044. // location, fold it into the primary diagnostic.
  11045. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  11046. diag::note_invalid_subexpr_in_const_expr) {
  11047. DiagLoc = Notes[0].first;
  11048. Notes.clear();
  11049. }
  11050. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  11051. << var << Init->getSourceRange();
  11052. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  11053. Diag(Notes[I].first, Notes[I].second);
  11054. }
  11055. } else if (var->mightBeUsableInConstantExpressions(Context)) {
  11056. // Check whether the initializer of a const variable of integral or
  11057. // enumeration type is an ICE now, since we can't tell whether it was
  11058. // initialized by a constant expression if we check later.
  11059. var->checkInitIsICE();
  11060. }
  11061. // Don't emit further diagnostics about constexpr globals since they
  11062. // were just diagnosed.
  11063. if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  11064. // FIXME: Need strict checking in C++03 here.
  11065. bool DiagErr = getLangOpts().CPlusPlus11
  11066. ? !var->checkInitIsICE() : !checkConstInit();
  11067. if (DiagErr) {
  11068. auto *Attr = var->getAttr<ConstInitAttr>();
  11069. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  11070. << Init->getSourceRange();
  11071. Diag(Attr->getLocation(),
  11072. diag::note_declared_required_constant_init_here)
  11073. << Attr->getRange() << Attr->isConstinit();
  11074. if (getLangOpts().CPlusPlus11) {
  11075. APValue Value;
  11076. SmallVector<PartialDiagnosticAt, 8> Notes;
  11077. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  11078. for (auto &it : Notes)
  11079. Diag(it.first, it.second);
  11080. } else {
  11081. Diag(CacheCulprit->getExprLoc(),
  11082. diag::note_invalid_subexpr_in_const_expr)
  11083. << CacheCulprit->getSourceRange();
  11084. }
  11085. }
  11086. }
  11087. else if (!var->isConstexpr() && IsGlobal &&
  11088. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  11089. var->getLocation())) {
  11090. // Warn about globals which don't have a constant initializer. Don't
  11091. // warn about globals with a non-trivial destructor because we already
  11092. // warned about them.
  11093. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  11094. if (!(RD && !RD->hasTrivialDestructor())) {
  11095. if (!checkConstInit())
  11096. Diag(var->getLocation(), diag::warn_global_constructor)
  11097. << Init->getSourceRange();
  11098. }
  11099. }
  11100. }
  11101. // Require the destructor.
  11102. if (const RecordType *recordType = baseType->getAs<RecordType>())
  11103. FinalizeVarWithDestructor(var, recordType);
  11104. // If this variable must be emitted, add it as an initializer for the current
  11105. // module.
  11106. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11107. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11108. }
  11109. /// Determines if a variable's alignment is dependent.
  11110. static bool hasDependentAlignment(VarDecl *VD) {
  11111. if (VD->getType()->isDependentType())
  11112. return true;
  11113. for (auto *I : VD->specific_attrs<AlignedAttr>())
  11114. if (I->isAlignmentDependent())
  11115. return true;
  11116. return false;
  11117. }
  11118. /// Check if VD needs to be dllexport/dllimport due to being in a
  11119. /// dllexport/import function.
  11120. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  11121. assert(VD->isStaticLocal());
  11122. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11123. // Find outermost function when VD is in lambda function.
  11124. while (FD && !getDLLAttr(FD) &&
  11125. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  11126. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  11127. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  11128. }
  11129. if (!FD)
  11130. return;
  11131. // Static locals inherit dll attributes from their function.
  11132. if (Attr *A = getDLLAttr(FD)) {
  11133. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  11134. NewAttr->setInherited(true);
  11135. VD->addAttr(NewAttr);
  11136. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  11137. auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
  11138. NewAttr->setInherited(true);
  11139. VD->addAttr(NewAttr);
  11140. // Export this function to enforce exporting this static variable even
  11141. // if it is not used in this compilation unit.
  11142. if (!FD->hasAttr<DLLExportAttr>())
  11143. FD->addAttr(NewAttr);
  11144. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  11145. auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
  11146. NewAttr->setInherited(true);
  11147. VD->addAttr(NewAttr);
  11148. }
  11149. }
  11150. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  11151. /// any semantic actions necessary after any initializer has been attached.
  11152. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  11153. // Note that we are no longer parsing the initializer for this declaration.
  11154. ParsingInitForAutoVars.erase(ThisDecl);
  11155. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  11156. if (!VD)
  11157. return;
  11158. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  11159. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  11160. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  11161. if (PragmaClangBSSSection.Valid)
  11162. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
  11163. Context, PragmaClangBSSSection.SectionName,
  11164. PragmaClangBSSSection.PragmaLocation,
  11165. AttributeCommonInfo::AS_Pragma));
  11166. if (PragmaClangDataSection.Valid)
  11167. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
  11168. Context, PragmaClangDataSection.SectionName,
  11169. PragmaClangDataSection.PragmaLocation,
  11170. AttributeCommonInfo::AS_Pragma));
  11171. if (PragmaClangRodataSection.Valid)
  11172. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
  11173. Context, PragmaClangRodataSection.SectionName,
  11174. PragmaClangRodataSection.PragmaLocation,
  11175. AttributeCommonInfo::AS_Pragma));
  11176. }
  11177. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  11178. for (auto *BD : DD->bindings()) {
  11179. FinalizeDeclaration(BD);
  11180. }
  11181. }
  11182. checkAttributesAfterMerging(*this, *VD);
  11183. // Perform TLS alignment check here after attributes attached to the variable
  11184. // which may affect the alignment have been processed. Only perform the check
  11185. // if the target has a maximum TLS alignment (zero means no constraints).
  11186. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  11187. // Protect the check so that it's not performed on dependent types and
  11188. // dependent alignments (we can't determine the alignment in that case).
  11189. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  11190. !VD->isInvalidDecl()) {
  11191. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  11192. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  11193. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  11194. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  11195. << (unsigned)MaxAlignChars.getQuantity();
  11196. }
  11197. }
  11198. }
  11199. if (VD->isStaticLocal()) {
  11200. CheckStaticLocalForDllExport(VD);
  11201. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  11202. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  11203. // function, only __shared__ variables or variables without any device
  11204. // memory qualifiers may be declared with static storage class.
  11205. // Note: It is unclear how a function-scope non-const static variable
  11206. // without device memory qualifier is implemented, therefore only static
  11207. // const variable without device memory qualifier is allowed.
  11208. [&]() {
  11209. if (!getLangOpts().CUDA)
  11210. return;
  11211. if (VD->hasAttr<CUDASharedAttr>())
  11212. return;
  11213. if (VD->getType().isConstQualified() &&
  11214. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  11215. return;
  11216. if (CUDADiagIfDeviceCode(VD->getLocation(),
  11217. diag::err_device_static_local_var)
  11218. << CurrentCUDATarget())
  11219. VD->setInvalidDecl();
  11220. }();
  11221. }
  11222. }
  11223. // Perform check for initializers of device-side global variables.
  11224. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11225. // 7.5). We must also apply the same checks to all __shared__
  11226. // variables whether they are local or not. CUDA also allows
  11227. // constant initializers for __constant__ and __device__ variables.
  11228. if (getLangOpts().CUDA)
  11229. checkAllowedCUDAInitializer(VD);
  11230. // Grab the dllimport or dllexport attribute off of the VarDecl.
  11231. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  11232. // Imported static data members cannot be defined out-of-line.
  11233. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  11234. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  11235. VD->isThisDeclarationADefinition()) {
  11236. // We allow definitions of dllimport class template static data members
  11237. // with a warning.
  11238. CXXRecordDecl *Context =
  11239. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  11240. bool IsClassTemplateMember =
  11241. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  11242. Context->getDescribedClassTemplate();
  11243. Diag(VD->getLocation(),
  11244. IsClassTemplateMember
  11245. ? diag::warn_attribute_dllimport_static_field_definition
  11246. : diag::err_attribute_dllimport_static_field_definition);
  11247. Diag(IA->getLocation(), diag::note_attribute);
  11248. if (!IsClassTemplateMember)
  11249. VD->setInvalidDecl();
  11250. }
  11251. }
  11252. // dllimport/dllexport variables cannot be thread local, their TLS index
  11253. // isn't exported with the variable.
  11254. if (DLLAttr && VD->getTLSKind()) {
  11255. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11256. if (F && getDLLAttr(F)) {
  11257. assert(VD->isStaticLocal());
  11258. // But if this is a static local in a dlimport/dllexport function, the
  11259. // function will never be inlined, which means the var would never be
  11260. // imported, so having it marked import/export is safe.
  11261. } else {
  11262. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  11263. << DLLAttr;
  11264. VD->setInvalidDecl();
  11265. }
  11266. }
  11267. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  11268. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  11269. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  11270. VD->dropAttr<UsedAttr>();
  11271. }
  11272. }
  11273. const DeclContext *DC = VD->getDeclContext();
  11274. // If there's a #pragma GCC visibility in scope, and this isn't a class
  11275. // member, set the visibility of this variable.
  11276. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  11277. AddPushedVisibilityAttribute(VD);
  11278. // FIXME: Warn on unused var template partial specializations.
  11279. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  11280. MarkUnusedFileScopedDecl(VD);
  11281. // Now we have parsed the initializer and can update the table of magic
  11282. // tag values.
  11283. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  11284. !VD->getType()->isIntegralOrEnumerationType())
  11285. return;
  11286. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  11287. const Expr *MagicValueExpr = VD->getInit();
  11288. if (!MagicValueExpr) {
  11289. continue;
  11290. }
  11291. llvm::APSInt MagicValueInt;
  11292. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  11293. Diag(I->getRange().getBegin(),
  11294. diag::err_type_tag_for_datatype_not_ice)
  11295. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11296. continue;
  11297. }
  11298. if (MagicValueInt.getActiveBits() > 64) {
  11299. Diag(I->getRange().getBegin(),
  11300. diag::err_type_tag_for_datatype_too_large)
  11301. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  11302. continue;
  11303. }
  11304. uint64_t MagicValue = MagicValueInt.getZExtValue();
  11305. RegisterTypeTagForDatatype(I->getArgumentKind(),
  11306. MagicValue,
  11307. I->getMatchingCType(),
  11308. I->getLayoutCompatible(),
  11309. I->getMustBeNull());
  11310. }
  11311. }
  11312. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  11313. auto *VD = dyn_cast<VarDecl>(DD);
  11314. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  11315. }
  11316. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  11317. ArrayRef<Decl *> Group) {
  11318. SmallVector<Decl*, 8> Decls;
  11319. if (DS.isTypeSpecOwned())
  11320. Decls.push_back(DS.getRepAsDecl());
  11321. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  11322. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  11323. bool DiagnosedMultipleDecomps = false;
  11324. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  11325. bool DiagnosedNonDeducedAuto = false;
  11326. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11327. if (Decl *D = Group[i]) {
  11328. // For declarators, there are some additional syntactic-ish checks we need
  11329. // to perform.
  11330. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  11331. if (!FirstDeclaratorInGroup)
  11332. FirstDeclaratorInGroup = DD;
  11333. if (!FirstDecompDeclaratorInGroup)
  11334. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  11335. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  11336. !hasDeducedAuto(DD))
  11337. FirstNonDeducedAutoInGroup = DD;
  11338. if (FirstDeclaratorInGroup != DD) {
  11339. // A decomposition declaration cannot be combined with any other
  11340. // declaration in the same group.
  11341. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  11342. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  11343. diag::err_decomp_decl_not_alone)
  11344. << FirstDeclaratorInGroup->getSourceRange()
  11345. << DD->getSourceRange();
  11346. DiagnosedMultipleDecomps = true;
  11347. }
  11348. // A declarator that uses 'auto' in any way other than to declare a
  11349. // variable with a deduced type cannot be combined with any other
  11350. // declarator in the same group.
  11351. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  11352. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  11353. diag::err_auto_non_deduced_not_alone)
  11354. << FirstNonDeducedAutoInGroup->getType()
  11355. ->hasAutoForTrailingReturnType()
  11356. << FirstDeclaratorInGroup->getSourceRange()
  11357. << DD->getSourceRange();
  11358. DiagnosedNonDeducedAuto = true;
  11359. }
  11360. }
  11361. }
  11362. Decls.push_back(D);
  11363. }
  11364. }
  11365. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  11366. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  11367. handleTagNumbering(Tag, S);
  11368. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  11369. getLangOpts().CPlusPlus)
  11370. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  11371. }
  11372. }
  11373. return BuildDeclaratorGroup(Decls);
  11374. }
  11375. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  11376. /// group, performing any necessary semantic checking.
  11377. Sema::DeclGroupPtrTy
  11378. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  11379. // C++14 [dcl.spec.auto]p7: (DR1347)
  11380. // If the type that replaces the placeholder type is not the same in each
  11381. // deduction, the program is ill-formed.
  11382. if (Group.size() > 1) {
  11383. QualType Deduced;
  11384. VarDecl *DeducedDecl = nullptr;
  11385. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  11386. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  11387. if (!D || D->isInvalidDecl())
  11388. break;
  11389. DeducedType *DT = D->getType()->getContainedDeducedType();
  11390. if (!DT || DT->getDeducedType().isNull())
  11391. continue;
  11392. if (Deduced.isNull()) {
  11393. Deduced = DT->getDeducedType();
  11394. DeducedDecl = D;
  11395. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  11396. auto *AT = dyn_cast<AutoType>(DT);
  11397. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  11398. diag::err_auto_different_deductions)
  11399. << (AT ? (unsigned)AT->getKeyword() : 3)
  11400. << Deduced << DeducedDecl->getDeclName()
  11401. << DT->getDeducedType() << D->getDeclName()
  11402. << DeducedDecl->getInit()->getSourceRange()
  11403. << D->getInit()->getSourceRange();
  11404. D->setInvalidDecl();
  11405. break;
  11406. }
  11407. }
  11408. }
  11409. ActOnDocumentableDecls(Group);
  11410. return DeclGroupPtrTy::make(
  11411. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  11412. }
  11413. void Sema::ActOnDocumentableDecl(Decl *D) {
  11414. ActOnDocumentableDecls(D);
  11415. }
  11416. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  11417. // Don't parse the comment if Doxygen diagnostics are ignored.
  11418. if (Group.empty() || !Group[0])
  11419. return;
  11420. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  11421. Group[0]->getLocation()) &&
  11422. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  11423. Group[0]->getLocation()))
  11424. return;
  11425. if (Group.size() >= 2) {
  11426. // This is a decl group. Normally it will contain only declarations
  11427. // produced from declarator list. But in case we have any definitions or
  11428. // additional declaration references:
  11429. // 'typedef struct S {} S;'
  11430. // 'typedef struct S *S;'
  11431. // 'struct S *pS;'
  11432. // FinalizeDeclaratorGroup adds these as separate declarations.
  11433. Decl *MaybeTagDecl = Group[0];
  11434. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  11435. Group = Group.slice(1);
  11436. }
  11437. }
  11438. // FIMXE: We assume every Decl in the group is in the same file.
  11439. // This is false when preprocessor constructs the group from decls in
  11440. // different files (e. g. macros or #include).
  11441. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  11442. }
  11443. /// Common checks for a parameter-declaration that should apply to both function
  11444. /// parameters and non-type template parameters.
  11445. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  11446. // Check that there are no default arguments inside the type of this
  11447. // parameter.
  11448. if (getLangOpts().CPlusPlus)
  11449. CheckExtraCXXDefaultArguments(D);
  11450. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  11451. if (D.getCXXScopeSpec().isSet()) {
  11452. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  11453. << D.getCXXScopeSpec().getRange();
  11454. }
  11455. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  11456. // simple identifier except [...irrelevant cases...].
  11457. switch (D.getName().getKind()) {
  11458. case UnqualifiedIdKind::IK_Identifier:
  11459. break;
  11460. case UnqualifiedIdKind::IK_OperatorFunctionId:
  11461. case UnqualifiedIdKind::IK_ConversionFunctionId:
  11462. case UnqualifiedIdKind::IK_LiteralOperatorId:
  11463. case UnqualifiedIdKind::IK_ConstructorName:
  11464. case UnqualifiedIdKind::IK_DestructorName:
  11465. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  11466. case UnqualifiedIdKind::IK_DeductionGuideName:
  11467. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  11468. << GetNameForDeclarator(D).getName();
  11469. break;
  11470. case UnqualifiedIdKind::IK_TemplateId:
  11471. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  11472. // GetNameForDeclarator would not produce a useful name in this case.
  11473. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  11474. break;
  11475. }
  11476. }
  11477. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  11478. /// to introduce parameters into function prototype scope.
  11479. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  11480. const DeclSpec &DS = D.getDeclSpec();
  11481. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  11482. // C++03 [dcl.stc]p2 also permits 'auto'.
  11483. StorageClass SC = SC_None;
  11484. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  11485. SC = SC_Register;
  11486. // In C++11, the 'register' storage class specifier is deprecated.
  11487. // In C++17, it is not allowed, but we tolerate it as an extension.
  11488. if (getLangOpts().CPlusPlus11) {
  11489. Diag(DS.getStorageClassSpecLoc(),
  11490. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  11491. : diag::warn_deprecated_register)
  11492. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  11493. }
  11494. } else if (getLangOpts().CPlusPlus &&
  11495. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  11496. SC = SC_Auto;
  11497. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  11498. Diag(DS.getStorageClassSpecLoc(),
  11499. diag::err_invalid_storage_class_in_func_decl);
  11500. D.getMutableDeclSpec().ClearStorageClassSpecs();
  11501. }
  11502. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  11503. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  11504. << DeclSpec::getSpecifierName(TSCS);
  11505. if (DS.isInlineSpecified())
  11506. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  11507. << getLangOpts().CPlusPlus17;
  11508. if (DS.hasConstexprSpecifier())
  11509. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  11510. << 0 << D.getDeclSpec().getConstexprSpecifier();
  11511. DiagnoseFunctionSpecifiers(DS);
  11512. CheckFunctionOrTemplateParamDeclarator(S, D);
  11513. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  11514. QualType parmDeclType = TInfo->getType();
  11515. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  11516. IdentifierInfo *II = D.getIdentifier();
  11517. if (II) {
  11518. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  11519. ForVisibleRedeclaration);
  11520. LookupName(R, S);
  11521. if (R.isSingleResult()) {
  11522. NamedDecl *PrevDecl = R.getFoundDecl();
  11523. if (PrevDecl->isTemplateParameter()) {
  11524. // Maybe we will complain about the shadowed template parameter.
  11525. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  11526. // Just pretend that we didn't see the previous declaration.
  11527. PrevDecl = nullptr;
  11528. } else if (S->isDeclScope(PrevDecl)) {
  11529. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  11530. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  11531. // Recover by removing the name
  11532. II = nullptr;
  11533. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  11534. D.setInvalidType(true);
  11535. }
  11536. }
  11537. }
  11538. // Temporarily put parameter variables in the translation unit, not
  11539. // the enclosing context. This prevents them from accidentally
  11540. // looking like class members in C++.
  11541. ParmVarDecl *New =
  11542. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  11543. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  11544. if (D.isInvalidType())
  11545. New->setInvalidDecl();
  11546. assert(S->isFunctionPrototypeScope());
  11547. assert(S->getFunctionPrototypeDepth() >= 1);
  11548. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11549. S->getNextFunctionPrototypeIndex());
  11550. // Add the parameter declaration into this scope.
  11551. S->AddDecl(New);
  11552. if (II)
  11553. IdResolver.AddDecl(New);
  11554. ProcessDeclAttributes(S, New, D);
  11555. if (D.getDeclSpec().isModulePrivateSpecified())
  11556. Diag(New->getLocation(), diag::err_module_private_local)
  11557. << 1 << New->getDeclName()
  11558. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11559. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11560. if (New->hasAttr<BlocksAttr>()) {
  11561. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11562. }
  11563. return New;
  11564. }
  11565. /// Synthesizes a variable for a parameter arising from a
  11566. /// typedef.
  11567. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11568. SourceLocation Loc,
  11569. QualType T) {
  11570. /* FIXME: setting StartLoc == Loc.
  11571. Would it be worth to modify callers so as to provide proper source
  11572. location for the unnamed parameters, embedding the parameter's type? */
  11573. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11574. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11575. SC_None, nullptr);
  11576. Param->setImplicit();
  11577. return Param;
  11578. }
  11579. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11580. // Don't diagnose unused-parameter errors in template instantiations; we
  11581. // will already have done so in the template itself.
  11582. if (inTemplateInstantiation())
  11583. return;
  11584. for (const ParmVarDecl *Parameter : Parameters) {
  11585. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11586. !Parameter->hasAttr<UnusedAttr>()) {
  11587. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11588. << Parameter->getDeclName();
  11589. }
  11590. }
  11591. }
  11592. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11593. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11594. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11595. return;
  11596. // Warn if the return value is pass-by-value and larger than the specified
  11597. // threshold.
  11598. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11599. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11600. if (Size > LangOpts.NumLargeByValueCopy)
  11601. Diag(D->getLocation(), diag::warn_return_value_size)
  11602. << D->getDeclName() << Size;
  11603. }
  11604. // Warn if any parameter is pass-by-value and larger than the specified
  11605. // threshold.
  11606. for (const ParmVarDecl *Parameter : Parameters) {
  11607. QualType T = Parameter->getType();
  11608. if (T->isDependentType() || !T.isPODType(Context))
  11609. continue;
  11610. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11611. if (Size > LangOpts.NumLargeByValueCopy)
  11612. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11613. << Parameter->getDeclName() << Size;
  11614. }
  11615. }
  11616. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11617. SourceLocation NameLoc, IdentifierInfo *Name,
  11618. QualType T, TypeSourceInfo *TSInfo,
  11619. StorageClass SC) {
  11620. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11621. if (getLangOpts().ObjCAutoRefCount &&
  11622. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11623. T->isObjCLifetimeType()) {
  11624. Qualifiers::ObjCLifetime lifetime;
  11625. // Special cases for arrays:
  11626. // - if it's const, use __unsafe_unretained
  11627. // - otherwise, it's an error
  11628. if (T->isArrayType()) {
  11629. if (!T.isConstQualified()) {
  11630. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11631. DelayedDiagnostics.add(
  11632. sema::DelayedDiagnostic::makeForbiddenType(
  11633. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11634. else
  11635. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11636. << TSInfo->getTypeLoc().getSourceRange();
  11637. }
  11638. lifetime = Qualifiers::OCL_ExplicitNone;
  11639. } else {
  11640. lifetime = T->getObjCARCImplicitLifetime();
  11641. }
  11642. T = Context.getLifetimeQualifiedType(T, lifetime);
  11643. }
  11644. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11645. Context.getAdjustedParameterType(T),
  11646. TSInfo, SC, nullptr);
  11647. // Make a note if we created a new pack in the scope of a lambda, so that
  11648. // we know that references to that pack must also be expanded within the
  11649. // lambda scope.
  11650. if (New->isParameterPack())
  11651. if (auto *LSI = getEnclosingLambda())
  11652. LSI->LocalPacks.push_back(New);
  11653. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  11654. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11655. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  11656. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  11657. // Parameters can not be abstract class types.
  11658. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11659. // the class has been completely parsed.
  11660. if (!CurContext->isRecord() &&
  11661. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11662. AbstractParamType))
  11663. New->setInvalidDecl();
  11664. // Parameter declarators cannot be interface types. All ObjC objects are
  11665. // passed by reference.
  11666. if (T->isObjCObjectType()) {
  11667. SourceLocation TypeEndLoc =
  11668. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11669. Diag(NameLoc,
  11670. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11671. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11672. T = Context.getObjCObjectPointerType(T);
  11673. New->setType(T);
  11674. }
  11675. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11676. // duration shall not be qualified by an address-space qualifier."
  11677. // Since all parameters have automatic store duration, they can not have
  11678. // an address space.
  11679. if (T.getAddressSpace() != LangAS::Default &&
  11680. // OpenCL allows function arguments declared to be an array of a type
  11681. // to be qualified with an address space.
  11682. !(getLangOpts().OpenCL &&
  11683. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11684. Diag(NameLoc, diag::err_arg_with_address_space);
  11685. New->setInvalidDecl();
  11686. }
  11687. return New;
  11688. }
  11689. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11690. SourceLocation LocAfterDecls) {
  11691. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11692. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11693. // for a K&R function.
  11694. if (!FTI.hasPrototype) {
  11695. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11696. --i;
  11697. if (FTI.Params[i].Param == nullptr) {
  11698. SmallString<256> Code;
  11699. llvm::raw_svector_ostream(Code)
  11700. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11701. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11702. << FTI.Params[i].Ident
  11703. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11704. // Implicitly declare the argument as type 'int' for lack of a better
  11705. // type.
  11706. AttributeFactory attrs;
  11707. DeclSpec DS(attrs);
  11708. const char* PrevSpec; // unused
  11709. unsigned DiagID; // unused
  11710. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11711. DiagID, Context.getPrintingPolicy());
  11712. // Use the identifier location for the type source range.
  11713. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11714. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11715. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11716. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11717. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11718. }
  11719. }
  11720. }
  11721. }
  11722. Decl *
  11723. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11724. MultiTemplateParamsArg TemplateParameterLists,
  11725. SkipBodyInfo *SkipBody) {
  11726. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11727. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11728. Scope *ParentScope = FnBodyScope->getParent();
  11729. D.setFunctionDefinitionKind(FDK_Definition);
  11730. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11731. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11732. }
  11733. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11734. Consumer.HandleInlineFunctionDefinition(D);
  11735. }
  11736. static bool
  11737. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11738. const FunctionDecl *&PossiblePrototype) {
  11739. // Don't warn about invalid declarations.
  11740. if (FD->isInvalidDecl())
  11741. return false;
  11742. // Or declarations that aren't global.
  11743. if (!FD->isGlobal())
  11744. return false;
  11745. // Don't warn about C++ member functions.
  11746. if (isa<CXXMethodDecl>(FD))
  11747. return false;
  11748. // Don't warn about 'main'.
  11749. if (FD->isMain())
  11750. return false;
  11751. // Don't warn about inline functions.
  11752. if (FD->isInlined())
  11753. return false;
  11754. // Don't warn about function templates.
  11755. if (FD->getDescribedFunctionTemplate())
  11756. return false;
  11757. // Don't warn about function template specializations.
  11758. if (FD->isFunctionTemplateSpecialization())
  11759. return false;
  11760. // Don't warn for OpenCL kernels.
  11761. if (FD->hasAttr<OpenCLKernelAttr>())
  11762. return false;
  11763. // Don't warn on explicitly deleted functions.
  11764. if (FD->isDeleted())
  11765. return false;
  11766. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11767. Prev; Prev = Prev->getPreviousDecl()) {
  11768. // Ignore any declarations that occur in function or method
  11769. // scope, because they aren't visible from the header.
  11770. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11771. continue;
  11772. PossiblePrototype = Prev;
  11773. return Prev->getType()->isFunctionNoProtoType();
  11774. }
  11775. return true;
  11776. }
  11777. void
  11778. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11779. const FunctionDecl *EffectiveDefinition,
  11780. SkipBodyInfo *SkipBody) {
  11781. const FunctionDecl *Definition = EffectiveDefinition;
  11782. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11783. // If this is a friend function defined in a class template, it does not
  11784. // have a body until it is used, nevertheless it is a definition, see
  11785. // [temp.inst]p2:
  11786. //
  11787. // ... for the purpose of determining whether an instantiated redeclaration
  11788. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11789. // corresponds to a definition in the template is considered to be a
  11790. // definition.
  11791. //
  11792. // The following code must produce redefinition error:
  11793. //
  11794. // template<typename T> struct C20 { friend void func_20() {} };
  11795. // C20<int> c20i;
  11796. // void func_20() {}
  11797. //
  11798. for (auto I : FD->redecls()) {
  11799. if (I != FD && !I->isInvalidDecl() &&
  11800. I->getFriendObjectKind() != Decl::FOK_None) {
  11801. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11802. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11803. // A merged copy of the same function, instantiated as a member of
  11804. // the same class, is OK.
  11805. if (declaresSameEntity(OrigFD, Original) &&
  11806. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11807. cast<Decl>(FD->getLexicalDeclContext())))
  11808. continue;
  11809. }
  11810. if (Original->isThisDeclarationADefinition()) {
  11811. Definition = I;
  11812. break;
  11813. }
  11814. }
  11815. }
  11816. }
  11817. }
  11818. if (!Definition)
  11819. // Similar to friend functions a friend function template may be a
  11820. // definition and do not have a body if it is instantiated in a class
  11821. // template.
  11822. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11823. for (auto I : FTD->redecls()) {
  11824. auto D = cast<FunctionTemplateDecl>(I);
  11825. if (D != FTD) {
  11826. assert(!D->isThisDeclarationADefinition() &&
  11827. "More than one definition in redeclaration chain");
  11828. if (D->getFriendObjectKind() != Decl::FOK_None)
  11829. if (FunctionTemplateDecl *FT =
  11830. D->getInstantiatedFromMemberTemplate()) {
  11831. if (FT->isThisDeclarationADefinition()) {
  11832. Definition = D->getTemplatedDecl();
  11833. break;
  11834. }
  11835. }
  11836. }
  11837. }
  11838. }
  11839. if (!Definition)
  11840. return;
  11841. if (canRedefineFunction(Definition, getLangOpts()))
  11842. return;
  11843. // Don't emit an error when this is redefinition of a typo-corrected
  11844. // definition.
  11845. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11846. return;
  11847. // If we don't have a visible definition of the function, and it's inline or
  11848. // a template, skip the new definition.
  11849. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11850. (Definition->getFormalLinkage() == InternalLinkage ||
  11851. Definition->isInlined() ||
  11852. Definition->getDescribedFunctionTemplate() ||
  11853. Definition->getNumTemplateParameterLists())) {
  11854. SkipBody->ShouldSkip = true;
  11855. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11856. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11857. makeMergedDefinitionVisible(TD);
  11858. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11859. return;
  11860. }
  11861. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11862. Definition->getStorageClass() == SC_Extern)
  11863. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11864. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11865. else
  11866. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11867. Diag(Definition->getLocation(), diag::note_previous_definition);
  11868. FD->setInvalidDecl();
  11869. }
  11870. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11871. Sema &S) {
  11872. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11873. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11874. LSI->CallOperator = CallOperator;
  11875. LSI->Lambda = LambdaClass;
  11876. LSI->ReturnType = CallOperator->getReturnType();
  11877. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11878. if (LCD == LCD_None)
  11879. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11880. else if (LCD == LCD_ByCopy)
  11881. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11882. else if (LCD == LCD_ByRef)
  11883. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11884. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11885. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11886. LSI->Mutable = !CallOperator->isConst();
  11887. // Add the captures to the LSI so they can be noted as already
  11888. // captured within tryCaptureVar.
  11889. auto I = LambdaClass->field_begin();
  11890. for (const auto &C : LambdaClass->captures()) {
  11891. if (C.capturesVariable()) {
  11892. VarDecl *VD = C.getCapturedVar();
  11893. if (VD->isInitCapture())
  11894. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11895. QualType CaptureType = VD->getType();
  11896. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11897. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11898. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11899. /*EllipsisLoc*/C.isPackExpansion()
  11900. ? C.getEllipsisLoc() : SourceLocation(),
  11901. CaptureType, /*Invalid*/false);
  11902. } else if (C.capturesThis()) {
  11903. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  11904. C.getCaptureKind() == LCK_StarThis);
  11905. } else {
  11906. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  11907. I->getType());
  11908. }
  11909. ++I;
  11910. }
  11911. }
  11912. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11913. SkipBodyInfo *SkipBody) {
  11914. if (!D) {
  11915. // Parsing the function declaration failed in some way. Push on a fake scope
  11916. // anyway so we can try to parse the function body.
  11917. PushFunctionScope();
  11918. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11919. return D;
  11920. }
  11921. FunctionDecl *FD = nullptr;
  11922. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11923. FD = FunTmpl->getTemplatedDecl();
  11924. else
  11925. FD = cast<FunctionDecl>(D);
  11926. // Do not push if it is a lambda because one is already pushed when building
  11927. // the lambda in ActOnStartOfLambdaDefinition().
  11928. if (!isLambdaCallOperator(FD))
  11929. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11930. // Check for defining attributes before the check for redefinition.
  11931. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11932. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11933. FD->dropAttr<AliasAttr>();
  11934. FD->setInvalidDecl();
  11935. }
  11936. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11937. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11938. FD->dropAttr<IFuncAttr>();
  11939. FD->setInvalidDecl();
  11940. }
  11941. // See if this is a redefinition. If 'will have body' is already set, then
  11942. // these checks were already performed when it was set.
  11943. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11944. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11945. // If we're skipping the body, we're done. Don't enter the scope.
  11946. if (SkipBody && SkipBody->ShouldSkip)
  11947. return D;
  11948. }
  11949. // Mark this function as "will have a body eventually". This lets users to
  11950. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11951. // this function.
  11952. FD->setWillHaveBody();
  11953. // If we are instantiating a generic lambda call operator, push
  11954. // a LambdaScopeInfo onto the function stack. But use the information
  11955. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11956. // LambdaScopeInfo.
  11957. // When the template operator is being specialized, the LambdaScopeInfo,
  11958. // has to be properly restored so that tryCaptureVariable doesn't try
  11959. // and capture any new variables. In addition when calculating potential
  11960. // captures during transformation of nested lambdas, it is necessary to
  11961. // have the LSI properly restored.
  11962. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11963. assert(inTemplateInstantiation() &&
  11964. "There should be an active template instantiation on the stack "
  11965. "when instantiating a generic lambda!");
  11966. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11967. } else {
  11968. // Enter a new function scope
  11969. PushFunctionScope();
  11970. }
  11971. // Builtin functions cannot be defined.
  11972. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11973. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11974. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11975. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11976. FD->setInvalidDecl();
  11977. }
  11978. }
  11979. // The return type of a function definition must be complete
  11980. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11981. QualType ResultType = FD->getReturnType();
  11982. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11983. !FD->isInvalidDecl() &&
  11984. RequireCompleteType(FD->getLocation(), ResultType,
  11985. diag::err_func_def_incomplete_result))
  11986. FD->setInvalidDecl();
  11987. if (FnBodyScope)
  11988. PushDeclContext(FnBodyScope, FD);
  11989. // Check the validity of our function parameters
  11990. CheckParmsForFunctionDef(FD->parameters(),
  11991. /*CheckParameterNames=*/true);
  11992. // Add non-parameter declarations already in the function to the current
  11993. // scope.
  11994. if (FnBodyScope) {
  11995. for (Decl *NPD : FD->decls()) {
  11996. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11997. if (!NonParmDecl)
  11998. continue;
  11999. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  12000. "parameters should not be in newly created FD yet");
  12001. // If the decl has a name, make it accessible in the current scope.
  12002. if (NonParmDecl->getDeclName())
  12003. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  12004. // Similarly, dive into enums and fish their constants out, making them
  12005. // accessible in this scope.
  12006. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  12007. for (auto *EI : ED->enumerators())
  12008. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  12009. }
  12010. }
  12011. }
  12012. // Introduce our parameters into the function scope
  12013. for (auto Param : FD->parameters()) {
  12014. Param->setOwningFunction(FD);
  12015. // If this has an identifier, add it to the scope stack.
  12016. if (Param->getIdentifier() && FnBodyScope) {
  12017. CheckShadow(FnBodyScope, Param);
  12018. PushOnScopeChains(Param, FnBodyScope);
  12019. }
  12020. }
  12021. // Ensure that the function's exception specification is instantiated.
  12022. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  12023. ResolveExceptionSpec(D->getLocation(), FPT);
  12024. // dllimport cannot be applied to non-inline function definitions.
  12025. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  12026. !FD->isTemplateInstantiation()) {
  12027. assert(!FD->hasAttr<DLLExportAttr>());
  12028. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  12029. FD->setInvalidDecl();
  12030. return D;
  12031. }
  12032. // We want to attach documentation to original Decl (which might be
  12033. // a function template).
  12034. ActOnDocumentableDecl(D);
  12035. if (getCurLexicalContext()->isObjCContainer() &&
  12036. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  12037. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  12038. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  12039. return D;
  12040. }
  12041. /// Given the set of return statements within a function body,
  12042. /// compute the variables that are subject to the named return value
  12043. /// optimization.
  12044. ///
  12045. /// Each of the variables that is subject to the named return value
  12046. /// optimization will be marked as NRVO variables in the AST, and any
  12047. /// return statement that has a marked NRVO variable as its NRVO candidate can
  12048. /// use the named return value optimization.
  12049. ///
  12050. /// This function applies a very simplistic algorithm for NRVO: if every return
  12051. /// statement in the scope of a variable has the same NRVO candidate, that
  12052. /// candidate is an NRVO variable.
  12053. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  12054. ReturnStmt **Returns = Scope->Returns.data();
  12055. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  12056. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  12057. if (!NRVOCandidate->isNRVOVariable())
  12058. Returns[I]->setNRVOCandidate(nullptr);
  12059. }
  12060. }
  12061. }
  12062. bool Sema::canDelayFunctionBody(const Declarator &D) {
  12063. // We can't delay parsing the body of a constexpr function template (yet).
  12064. if (D.getDeclSpec().hasConstexprSpecifier())
  12065. return false;
  12066. // We can't delay parsing the body of a function template with a deduced
  12067. // return type (yet).
  12068. if (D.getDeclSpec().hasAutoTypeSpec()) {
  12069. // If the placeholder introduces a non-deduced trailing return type,
  12070. // we can still delay parsing it.
  12071. if (D.getNumTypeObjects()) {
  12072. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  12073. if (Outer.Kind == DeclaratorChunk::Function &&
  12074. Outer.Fun.hasTrailingReturnType()) {
  12075. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  12076. return Ty.isNull() || !Ty->isUndeducedType();
  12077. }
  12078. }
  12079. return false;
  12080. }
  12081. return true;
  12082. }
  12083. bool Sema::canSkipFunctionBody(Decl *D) {
  12084. // We cannot skip the body of a function (or function template) which is
  12085. // constexpr, since we may need to evaluate its body in order to parse the
  12086. // rest of the file.
  12087. // We cannot skip the body of a function with an undeduced return type,
  12088. // because any callers of that function need to know the type.
  12089. if (const FunctionDecl *FD = D->getAsFunction()) {
  12090. if (FD->isConstexpr())
  12091. return false;
  12092. // We can't simply call Type::isUndeducedType here, because inside template
  12093. // auto can be deduced to a dependent type, which is not considered
  12094. // "undeduced".
  12095. if (FD->getReturnType()->getContainedDeducedType())
  12096. return false;
  12097. }
  12098. return Consumer.shouldSkipFunctionBody(D);
  12099. }
  12100. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  12101. if (!Decl)
  12102. return nullptr;
  12103. if (FunctionDecl *FD = Decl->getAsFunction())
  12104. FD->setHasSkippedBody();
  12105. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  12106. MD->setHasSkippedBody();
  12107. return Decl;
  12108. }
  12109. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  12110. return ActOnFinishFunctionBody(D, BodyArg, false);
  12111. }
  12112. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  12113. /// body.
  12114. class ExitFunctionBodyRAII {
  12115. public:
  12116. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  12117. ~ExitFunctionBodyRAII() {
  12118. if (!IsLambda)
  12119. S.PopExpressionEvaluationContext();
  12120. }
  12121. private:
  12122. Sema &S;
  12123. bool IsLambda = false;
  12124. };
  12125. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  12126. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  12127. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  12128. if (EscapeInfo.count(BD))
  12129. return EscapeInfo[BD];
  12130. bool R = false;
  12131. const BlockDecl *CurBD = BD;
  12132. do {
  12133. R = !CurBD->doesNotEscape();
  12134. if (R)
  12135. break;
  12136. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  12137. } while (CurBD);
  12138. return EscapeInfo[BD] = R;
  12139. };
  12140. // If the location where 'self' is implicitly retained is inside a escaping
  12141. // block, emit a diagnostic.
  12142. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  12143. S.ImplicitlyRetainedSelfLocs)
  12144. if (IsOrNestedInEscapingBlock(P.second))
  12145. S.Diag(P.first, diag::warn_implicitly_retains_self)
  12146. << FixItHint::CreateInsertion(P.first, "self->");
  12147. }
  12148. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  12149. bool IsInstantiation) {
  12150. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  12151. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12152. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  12153. if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
  12154. CheckCompletedCoroutineBody(FD, Body);
  12155. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  12156. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  12157. // meant to pop the context added in ActOnStartOfFunctionDef().
  12158. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  12159. if (FD) {
  12160. FD->setBody(Body);
  12161. FD->setWillHaveBody(false);
  12162. if (getLangOpts().CPlusPlus14) {
  12163. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  12164. FD->getReturnType()->isUndeducedType()) {
  12165. // If the function has a deduced result type but contains no 'return'
  12166. // statements, the result type as written must be exactly 'auto', and
  12167. // the deduced result type is 'void'.
  12168. if (!FD->getReturnType()->getAs<AutoType>()) {
  12169. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  12170. << FD->getReturnType();
  12171. FD->setInvalidDecl();
  12172. } else {
  12173. // Substitute 'void' for the 'auto' in the type.
  12174. TypeLoc ResultType = getReturnTypeLoc(FD);
  12175. Context.adjustDeducedFunctionResultType(
  12176. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  12177. }
  12178. }
  12179. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  12180. // In C++11, we don't use 'auto' deduction rules for lambda call
  12181. // operators because we don't support return type deduction.
  12182. auto *LSI = getCurLambda();
  12183. if (LSI->HasImplicitReturnType) {
  12184. deduceClosureReturnType(*LSI);
  12185. // C++11 [expr.prim.lambda]p4:
  12186. // [...] if there are no return statements in the compound-statement
  12187. // [the deduced type is] the type void
  12188. QualType RetType =
  12189. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  12190. // Update the return type to the deduced type.
  12191. const FunctionProtoType *Proto =
  12192. FD->getType()->getAs<FunctionProtoType>();
  12193. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  12194. Proto->getExtProtoInfo()));
  12195. }
  12196. }
  12197. // If the function implicitly returns zero (like 'main') or is naked,
  12198. // don't complain about missing return statements.
  12199. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12200. WP.disableCheckFallThrough();
  12201. // MSVC permits the use of pure specifier (=0) on function definition,
  12202. // defined at class scope, warn about this non-standard construct.
  12203. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12204. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12205. if (!FD->isInvalidDecl()) {
  12206. // Don't diagnose unused parameters of defaulted or deleted functions.
  12207. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  12208. DiagnoseUnusedParameters(FD->parameters());
  12209. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12210. FD->getReturnType(), FD);
  12211. // If this is a structor, we need a vtable.
  12212. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12213. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12214. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  12215. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12216. // Try to apply the named return value optimization. We have to check
  12217. // if we can do this here because lambdas keep return statements around
  12218. // to deduce an implicit return type.
  12219. if (FD->getReturnType()->isRecordType() &&
  12220. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12221. computeNRVO(Body, getCurFunction());
  12222. }
  12223. // GNU warning -Wmissing-prototypes:
  12224. // Warn if a global function is defined without a previous
  12225. // prototype declaration. This warning is issued even if the
  12226. // definition itself provides a prototype. The aim is to detect
  12227. // global functions that fail to be declared in header files.
  12228. const FunctionDecl *PossiblePrototype = nullptr;
  12229. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  12230. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  12231. if (PossiblePrototype) {
  12232. // We found a declaration that is not a prototype,
  12233. // but that could be a zero-parameter prototype
  12234. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  12235. TypeLoc TL = TI->getTypeLoc();
  12236. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  12237. Diag(PossiblePrototype->getLocation(),
  12238. diag::note_declaration_not_a_prototype)
  12239. << (FD->getNumParams() != 0)
  12240. << (FD->getNumParams() == 0
  12241. ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
  12242. : FixItHint{});
  12243. }
  12244. } else {
  12245. Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12246. << /* function */ 1
  12247. << (FD->getStorageClass() == SC_None
  12248. ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(),
  12249. "static ")
  12250. : FixItHint{});
  12251. }
  12252. // GNU warning -Wstrict-prototypes
  12253. // Warn if K&R function is defined without a previous declaration.
  12254. // This warning is issued only if the definition itself does not provide
  12255. // a prototype. Only K&R definitions do not provide a prototype.
  12256. // An empty list in a function declarator that is part of a definition
  12257. // of that function specifies that the function has no parameters
  12258. // (C99 6.7.5.3p14)
  12259. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  12260. !LangOpts.CPlusPlus) {
  12261. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  12262. TypeLoc TL = TI->getTypeLoc();
  12263. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  12264. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  12265. }
  12266. }
  12267. // Warn on CPUDispatch with an actual body.
  12268. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  12269. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  12270. if (!CmpndBody->body_empty())
  12271. Diag(CmpndBody->body_front()->getBeginLoc(),
  12272. diag::warn_dispatch_body_ignored);
  12273. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  12274. const CXXMethodDecl *KeyFunction;
  12275. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  12276. MD->isVirtual() &&
  12277. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  12278. MD == KeyFunction->getCanonicalDecl()) {
  12279. // Update the key-function state if necessary for this ABI.
  12280. if (FD->isInlined() &&
  12281. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  12282. Context.setNonKeyFunction(MD);
  12283. // If the newly-chosen key function is already defined, then we
  12284. // need to mark the vtable as used retroactively.
  12285. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  12286. const FunctionDecl *Definition;
  12287. if (KeyFunction && KeyFunction->isDefined(Definition))
  12288. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  12289. } else {
  12290. // We just defined they key function; mark the vtable as used.
  12291. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  12292. }
  12293. }
  12294. }
  12295. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  12296. "Function parsing confused");
  12297. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  12298. assert(MD == getCurMethodDecl() && "Method parsing confused");
  12299. MD->setBody(Body);
  12300. if (!MD->isInvalidDecl()) {
  12301. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  12302. MD->getReturnType(), MD);
  12303. if (Body)
  12304. computeNRVO(Body, getCurFunction());
  12305. }
  12306. if (getCurFunction()->ObjCShouldCallSuper) {
  12307. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  12308. << MD->getSelector().getAsString();
  12309. getCurFunction()->ObjCShouldCallSuper = false;
  12310. }
  12311. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  12312. const ObjCMethodDecl *InitMethod = nullptr;
  12313. bool isDesignated =
  12314. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  12315. assert(isDesignated && InitMethod);
  12316. (void)isDesignated;
  12317. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  12318. auto IFace = MD->getClassInterface();
  12319. if (!IFace)
  12320. return false;
  12321. auto SuperD = IFace->getSuperClass();
  12322. if (!SuperD)
  12323. return false;
  12324. return SuperD->getIdentifier() ==
  12325. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  12326. };
  12327. // Don't issue this warning for unavailable inits or direct subclasses
  12328. // of NSObject.
  12329. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  12330. Diag(MD->getLocation(),
  12331. diag::warn_objc_designated_init_missing_super_call);
  12332. Diag(InitMethod->getLocation(),
  12333. diag::note_objc_designated_init_marked_here);
  12334. }
  12335. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  12336. }
  12337. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  12338. // Don't issue this warning for unavaialable inits.
  12339. if (!MD->isUnavailable())
  12340. Diag(MD->getLocation(),
  12341. diag::warn_objc_secondary_init_missing_init_call);
  12342. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  12343. }
  12344. diagnoseImplicitlyRetainedSelf(*this);
  12345. } else {
  12346. // Parsing the function declaration failed in some way. Pop the fake scope
  12347. // we pushed on.
  12348. PopFunctionScopeInfo(ActivePolicy, dcl);
  12349. return nullptr;
  12350. }
  12351. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  12352. DiagnoseUnguardedAvailabilityViolations(dcl);
  12353. assert(!getCurFunction()->ObjCShouldCallSuper &&
  12354. "This should only be set for ObjC methods, which should have been "
  12355. "handled in the block above.");
  12356. // Verify and clean out per-function state.
  12357. if (Body && (!FD || !FD->isDefaulted())) {
  12358. // C++ constructors that have function-try-blocks can't have return
  12359. // statements in the handlers of that block. (C++ [except.handle]p14)
  12360. // Verify this.
  12361. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  12362. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  12363. // Verify that gotos and switch cases don't jump into scopes illegally.
  12364. if (getCurFunction()->NeedsScopeChecking() &&
  12365. !PP.isCodeCompletionEnabled())
  12366. DiagnoseInvalidJumps(Body);
  12367. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  12368. if (!Destructor->getParent()->isDependentType())
  12369. CheckDestructor(Destructor);
  12370. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  12371. Destructor->getParent());
  12372. }
  12373. // If any errors have occurred, clear out any temporaries that may have
  12374. // been leftover. This ensures that these temporaries won't be picked up for
  12375. // deletion in some later function.
  12376. if (getDiagnostics().hasErrorOccurred() ||
  12377. getDiagnostics().getSuppressAllDiagnostics()) {
  12378. DiscardCleanupsInEvaluationContext();
  12379. }
  12380. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  12381. !isa<FunctionTemplateDecl>(dcl)) {
  12382. // Since the body is valid, issue any analysis-based warnings that are
  12383. // enabled.
  12384. ActivePolicy = &WP;
  12385. }
  12386. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  12387. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  12388. FD->setInvalidDecl();
  12389. if (FD && FD->hasAttr<NakedAttr>()) {
  12390. for (const Stmt *S : Body->children()) {
  12391. // Allow local register variables without initializer as they don't
  12392. // require prologue.
  12393. bool RegisterVariables = false;
  12394. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  12395. for (const auto *Decl : DS->decls()) {
  12396. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  12397. RegisterVariables =
  12398. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  12399. if (!RegisterVariables)
  12400. break;
  12401. }
  12402. }
  12403. }
  12404. if (RegisterVariables)
  12405. continue;
  12406. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  12407. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  12408. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  12409. FD->setInvalidDecl();
  12410. break;
  12411. }
  12412. }
  12413. }
  12414. assert(ExprCleanupObjects.size() ==
  12415. ExprEvalContexts.back().NumCleanupObjects &&
  12416. "Leftover temporaries in function");
  12417. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  12418. assert(MaybeODRUseExprs.empty() &&
  12419. "Leftover expressions for odr-use checking");
  12420. }
  12421. if (!IsInstantiation)
  12422. PopDeclContext();
  12423. PopFunctionScopeInfo(ActivePolicy, dcl);
  12424. // If any errors have occurred, clear out any temporaries that may have
  12425. // been leftover. This ensures that these temporaries won't be picked up for
  12426. // deletion in some later function.
  12427. if (getDiagnostics().hasErrorOccurred()) {
  12428. DiscardCleanupsInEvaluationContext();
  12429. }
  12430. return dcl;
  12431. }
  12432. /// When we finish delayed parsing of an attribute, we must attach it to the
  12433. /// relevant Decl.
  12434. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  12435. ParsedAttributes &Attrs) {
  12436. // Always attach attributes to the underlying decl.
  12437. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  12438. D = TD->getTemplatedDecl();
  12439. ProcessDeclAttributeList(S, D, Attrs);
  12440. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  12441. if (Method->isStatic())
  12442. checkThisInStaticMemberFunctionAttributes(Method);
  12443. }
  12444. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  12445. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  12446. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  12447. IdentifierInfo &II, Scope *S) {
  12448. // Find the scope in which the identifier is injected and the corresponding
  12449. // DeclContext.
  12450. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  12451. // In that case, we inject the declaration into the translation unit scope
  12452. // instead.
  12453. Scope *BlockScope = S;
  12454. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  12455. BlockScope = BlockScope->getParent();
  12456. Scope *ContextScope = BlockScope;
  12457. while (!ContextScope->getEntity())
  12458. ContextScope = ContextScope->getParent();
  12459. ContextRAII SavedContext(*this, ContextScope->getEntity());
  12460. // Before we produce a declaration for an implicitly defined
  12461. // function, see whether there was a locally-scoped declaration of
  12462. // this name as a function or variable. If so, use that
  12463. // (non-visible) declaration, and complain about it.
  12464. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  12465. if (ExternCPrev) {
  12466. // We still need to inject the function into the enclosing block scope so
  12467. // that later (non-call) uses can see it.
  12468. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  12469. // C89 footnote 38:
  12470. // If in fact it is not defined as having type "function returning int",
  12471. // the behavior is undefined.
  12472. if (!isa<FunctionDecl>(ExternCPrev) ||
  12473. !Context.typesAreCompatible(
  12474. cast<FunctionDecl>(ExternCPrev)->getType(),
  12475. Context.getFunctionNoProtoType(Context.IntTy))) {
  12476. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  12477. << ExternCPrev << !getLangOpts().C99;
  12478. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  12479. return ExternCPrev;
  12480. }
  12481. }
  12482. // Extension in C99. Legal in C90, but warn about it.
  12483. unsigned diag_id;
  12484. if (II.getName().startswith("__builtin_"))
  12485. diag_id = diag::warn_builtin_unknown;
  12486. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  12487. else if (getLangOpts().OpenCL)
  12488. diag_id = diag::err_opencl_implicit_function_decl;
  12489. else if (getLangOpts().C99)
  12490. diag_id = diag::ext_implicit_function_decl;
  12491. else
  12492. diag_id = diag::warn_implicit_function_decl;
  12493. Diag(Loc, diag_id) << &II;
  12494. // If we found a prior declaration of this function, don't bother building
  12495. // another one. We've already pushed that one into scope, so there's nothing
  12496. // more to do.
  12497. if (ExternCPrev)
  12498. return ExternCPrev;
  12499. // Because typo correction is expensive, only do it if the implicit
  12500. // function declaration is going to be treated as an error.
  12501. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  12502. TypoCorrection Corrected;
  12503. DeclFilterCCC<FunctionDecl> CCC{};
  12504. if (S && (Corrected =
  12505. CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  12506. S, nullptr, CCC, CTK_NonError)))
  12507. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  12508. /*ErrorRecovery*/false);
  12509. }
  12510. // Set a Declarator for the implicit definition: int foo();
  12511. const char *Dummy;
  12512. AttributeFactory attrFactory;
  12513. DeclSpec DS(attrFactory);
  12514. unsigned DiagID;
  12515. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  12516. Context.getPrintingPolicy());
  12517. (void)Error; // Silence warning.
  12518. assert(!Error && "Error setting up implicit decl!");
  12519. SourceLocation NoLoc;
  12520. Declarator D(DS, DeclaratorContext::BlockContext);
  12521. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  12522. /*IsAmbiguous=*/false,
  12523. /*LParenLoc=*/NoLoc,
  12524. /*Params=*/nullptr,
  12525. /*NumParams=*/0,
  12526. /*EllipsisLoc=*/NoLoc,
  12527. /*RParenLoc=*/NoLoc,
  12528. /*RefQualifierIsLvalueRef=*/true,
  12529. /*RefQualifierLoc=*/NoLoc,
  12530. /*MutableLoc=*/NoLoc, EST_None,
  12531. /*ESpecRange=*/SourceRange(),
  12532. /*Exceptions=*/nullptr,
  12533. /*ExceptionRanges=*/nullptr,
  12534. /*NumExceptions=*/0,
  12535. /*NoexceptExpr=*/nullptr,
  12536. /*ExceptionSpecTokens=*/nullptr,
  12537. /*DeclsInPrototype=*/None, Loc,
  12538. Loc, D),
  12539. std::move(DS.getAttributes()), SourceLocation());
  12540. D.SetIdentifier(&II, Loc);
  12541. // Insert this function into the enclosing block scope.
  12542. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  12543. FD->setImplicit();
  12544. AddKnownFunctionAttributes(FD);
  12545. return FD;
  12546. }
  12547. /// Adds any function attributes that we know a priori based on
  12548. /// the declaration of this function.
  12549. ///
  12550. /// These attributes can apply both to implicitly-declared builtins
  12551. /// (like __builtin___printf_chk) or to library-declared functions
  12552. /// like NSLog or printf.
  12553. ///
  12554. /// We need to check for duplicate attributes both here and where user-written
  12555. /// attributes are applied to declarations.
  12556. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  12557. if (FD->isInvalidDecl())
  12558. return;
  12559. // If this is a built-in function, map its builtin attributes to
  12560. // actual attributes.
  12561. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12562. // Handle printf-formatting attributes.
  12563. unsigned FormatIdx;
  12564. bool HasVAListArg;
  12565. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  12566. if (!FD->hasAttr<FormatAttr>()) {
  12567. const char *fmt = "printf";
  12568. unsigned int NumParams = FD->getNumParams();
  12569. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  12570. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  12571. fmt = "NSString";
  12572. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12573. &Context.Idents.get(fmt),
  12574. FormatIdx+1,
  12575. HasVAListArg ? 0 : FormatIdx+2,
  12576. FD->getLocation()));
  12577. }
  12578. }
  12579. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  12580. HasVAListArg)) {
  12581. if (!FD->hasAttr<FormatAttr>())
  12582. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12583. &Context.Idents.get("scanf"),
  12584. FormatIdx+1,
  12585. HasVAListArg ? 0 : FormatIdx+2,
  12586. FD->getLocation()));
  12587. }
  12588. // Handle automatically recognized callbacks.
  12589. SmallVector<int, 4> Encoding;
  12590. if (!FD->hasAttr<CallbackAttr>() &&
  12591. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12592. FD->addAttr(CallbackAttr::CreateImplicit(
  12593. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12594. // Mark const if we don't care about errno and that is the only thing
  12595. // preventing the function from being const. This allows IRgen to use LLVM
  12596. // intrinsics for such functions.
  12597. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12598. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12599. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12600. // We make "fma" on some platforms const because we know it does not set
  12601. // errno in those environments even though it could set errno based on the
  12602. // C standard.
  12603. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12604. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12605. !FD->hasAttr<ConstAttr>()) {
  12606. switch (BuiltinID) {
  12607. case Builtin::BI__builtin_fma:
  12608. case Builtin::BI__builtin_fmaf:
  12609. case Builtin::BI__builtin_fmal:
  12610. case Builtin::BIfma:
  12611. case Builtin::BIfmaf:
  12612. case Builtin::BIfmal:
  12613. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12614. break;
  12615. default:
  12616. break;
  12617. }
  12618. }
  12619. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12620. !FD->hasAttr<ReturnsTwiceAttr>())
  12621. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12622. FD->getLocation()));
  12623. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12624. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12625. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12626. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12627. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12628. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12629. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12630. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12631. // Add the appropriate attribute, depending on the CUDA compilation mode
  12632. // and which target the builtin belongs to. For example, during host
  12633. // compilation, aux builtins are __device__, while the rest are __host__.
  12634. if (getLangOpts().CUDAIsDevice !=
  12635. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12636. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12637. else
  12638. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12639. }
  12640. }
  12641. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12642. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12643. // across.
  12644. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12645. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12646. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12647. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12648. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12649. }
  12650. IdentifierInfo *Name = FD->getIdentifier();
  12651. if (!Name)
  12652. return;
  12653. if ((!getLangOpts().CPlusPlus &&
  12654. FD->getDeclContext()->isTranslationUnit()) ||
  12655. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12656. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12657. LinkageSpecDecl::lang_c)) {
  12658. // Okay: this could be a libc/libm/Objective-C function we know
  12659. // about.
  12660. } else
  12661. return;
  12662. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12663. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12664. // target-specific builtins, perhaps?
  12665. if (!FD->hasAttr<FormatAttr>())
  12666. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12667. &Context.Idents.get("printf"), 2,
  12668. Name->isStr("vasprintf") ? 0 : 3,
  12669. FD->getLocation()));
  12670. }
  12671. if (Name->isStr("__CFStringMakeConstantString")) {
  12672. // We already have a __builtin___CFStringMakeConstantString,
  12673. // but builds that use -fno-constant-cfstrings don't go through that.
  12674. if (!FD->hasAttr<FormatArgAttr>())
  12675. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12676. FD->getLocation()));
  12677. }
  12678. }
  12679. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12680. TypeSourceInfo *TInfo) {
  12681. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12682. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12683. if (!TInfo) {
  12684. assert(D.isInvalidType() && "no declarator info for valid type");
  12685. TInfo = Context.getTrivialTypeSourceInfo(T);
  12686. }
  12687. // Scope manipulation handled by caller.
  12688. TypedefDecl *NewTD =
  12689. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12690. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12691. // Bail out immediately if we have an invalid declaration.
  12692. if (D.isInvalidType()) {
  12693. NewTD->setInvalidDecl();
  12694. return NewTD;
  12695. }
  12696. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12697. if (CurContext->isFunctionOrMethod())
  12698. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12699. << 2 << NewTD->getDeclName()
  12700. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12701. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12702. else
  12703. NewTD->setModulePrivate();
  12704. }
  12705. // C++ [dcl.typedef]p8:
  12706. // If the typedef declaration defines an unnamed class (or
  12707. // enum), the first typedef-name declared by the declaration
  12708. // to be that class type (or enum type) is used to denote the
  12709. // class type (or enum type) for linkage purposes only.
  12710. // We need to check whether the type was declared in the declaration.
  12711. switch (D.getDeclSpec().getTypeSpecType()) {
  12712. case TST_enum:
  12713. case TST_struct:
  12714. case TST_interface:
  12715. case TST_union:
  12716. case TST_class: {
  12717. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12718. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12719. break;
  12720. }
  12721. default:
  12722. break;
  12723. }
  12724. return NewTD;
  12725. }
  12726. /// Check that this is a valid underlying type for an enum declaration.
  12727. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12728. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12729. QualType T = TI->getType();
  12730. if (T->isDependentType())
  12731. return false;
  12732. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12733. if (BT->isInteger())
  12734. return false;
  12735. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12736. return true;
  12737. }
  12738. /// Check whether this is a valid redeclaration of a previous enumeration.
  12739. /// \return true if the redeclaration was invalid.
  12740. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12741. QualType EnumUnderlyingTy, bool IsFixed,
  12742. const EnumDecl *Prev) {
  12743. if (IsScoped != Prev->isScoped()) {
  12744. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12745. << Prev->isScoped();
  12746. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12747. return true;
  12748. }
  12749. if (IsFixed && Prev->isFixed()) {
  12750. if (!EnumUnderlyingTy->isDependentType() &&
  12751. !Prev->getIntegerType()->isDependentType() &&
  12752. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12753. Prev->getIntegerType())) {
  12754. // TODO: Highlight the underlying type of the redeclaration.
  12755. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12756. << EnumUnderlyingTy << Prev->getIntegerType();
  12757. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12758. << Prev->getIntegerTypeRange();
  12759. return true;
  12760. }
  12761. } else if (IsFixed != Prev->isFixed()) {
  12762. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12763. << Prev->isFixed();
  12764. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12765. return true;
  12766. }
  12767. return false;
  12768. }
  12769. /// Get diagnostic %select index for tag kind for
  12770. /// redeclaration diagnostic message.
  12771. /// WARNING: Indexes apply to particular diagnostics only!
  12772. ///
  12773. /// \returns diagnostic %select index.
  12774. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12775. switch (Tag) {
  12776. case TTK_Struct: return 0;
  12777. case TTK_Interface: return 1;
  12778. case TTK_Class: return 2;
  12779. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12780. }
  12781. }
  12782. /// Determine if tag kind is a class-key compatible with
  12783. /// class for redeclaration (class, struct, or __interface).
  12784. ///
  12785. /// \returns true iff the tag kind is compatible.
  12786. static bool isClassCompatTagKind(TagTypeKind Tag)
  12787. {
  12788. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12789. }
  12790. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12791. TagTypeKind TTK) {
  12792. if (isa<TypedefDecl>(PrevDecl))
  12793. return NTK_Typedef;
  12794. else if (isa<TypeAliasDecl>(PrevDecl))
  12795. return NTK_TypeAlias;
  12796. else if (isa<ClassTemplateDecl>(PrevDecl))
  12797. return NTK_Template;
  12798. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12799. return NTK_TypeAliasTemplate;
  12800. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12801. return NTK_TemplateTemplateArgument;
  12802. switch (TTK) {
  12803. case TTK_Struct:
  12804. case TTK_Interface:
  12805. case TTK_Class:
  12806. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12807. case TTK_Union:
  12808. return NTK_NonUnion;
  12809. case TTK_Enum:
  12810. return NTK_NonEnum;
  12811. }
  12812. llvm_unreachable("invalid TTK");
  12813. }
  12814. /// Determine whether a tag with a given kind is acceptable
  12815. /// as a redeclaration of the given tag declaration.
  12816. ///
  12817. /// \returns true if the new tag kind is acceptable, false otherwise.
  12818. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12819. TagTypeKind NewTag, bool isDefinition,
  12820. SourceLocation NewTagLoc,
  12821. const IdentifierInfo *Name) {
  12822. // C++ [dcl.type.elab]p3:
  12823. // The class-key or enum keyword present in the
  12824. // elaborated-type-specifier shall agree in kind with the
  12825. // declaration to which the name in the elaborated-type-specifier
  12826. // refers. This rule also applies to the form of
  12827. // elaborated-type-specifier that declares a class-name or
  12828. // friend class since it can be construed as referring to the
  12829. // definition of the class. Thus, in any
  12830. // elaborated-type-specifier, the enum keyword shall be used to
  12831. // refer to an enumeration (7.2), the union class-key shall be
  12832. // used to refer to a union (clause 9), and either the class or
  12833. // struct class-key shall be used to refer to a class (clause 9)
  12834. // declared using the class or struct class-key.
  12835. TagTypeKind OldTag = Previous->getTagKind();
  12836. if (OldTag != NewTag &&
  12837. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12838. return false;
  12839. // Tags are compatible, but we might still want to warn on mismatched tags.
  12840. // Non-class tags can't be mismatched at this point.
  12841. if (!isClassCompatTagKind(NewTag))
  12842. return true;
  12843. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12844. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12845. // declarations in system headers that are designed to be specialized, but if
  12846. // a user asks us to warn, we should warn if their code contains mismatched
  12847. // declarations.
  12848. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12849. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12850. Loc);
  12851. };
  12852. if (IsIgnoredLoc(NewTagLoc))
  12853. return true;
  12854. auto IsIgnored = [&](const TagDecl *Tag) {
  12855. return IsIgnoredLoc(Tag->getLocation());
  12856. };
  12857. while (IsIgnored(Previous)) {
  12858. Previous = Previous->getPreviousDecl();
  12859. if (!Previous)
  12860. return true;
  12861. OldTag = Previous->getTagKind();
  12862. }
  12863. bool isTemplate = false;
  12864. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12865. isTemplate = Record->getDescribedClassTemplate();
  12866. if (inTemplateInstantiation()) {
  12867. if (OldTag != NewTag) {
  12868. // In a template instantiation, do not offer fix-its for tag mismatches
  12869. // since they usually mess up the template instead of fixing the problem.
  12870. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12871. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12872. << getRedeclDiagFromTagKind(OldTag);
  12873. // FIXME: Note previous location?
  12874. }
  12875. return true;
  12876. }
  12877. if (isDefinition) {
  12878. // On definitions, check all previous tags and issue a fix-it for each
  12879. // one that doesn't match the current tag.
  12880. if (Previous->getDefinition()) {
  12881. // Don't suggest fix-its for redefinitions.
  12882. return true;
  12883. }
  12884. bool previousMismatch = false;
  12885. for (const TagDecl *I : Previous->redecls()) {
  12886. if (I->getTagKind() != NewTag) {
  12887. // Ignore previous declarations for which the warning was disabled.
  12888. if (IsIgnored(I))
  12889. continue;
  12890. if (!previousMismatch) {
  12891. previousMismatch = true;
  12892. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12893. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12894. << getRedeclDiagFromTagKind(I->getTagKind());
  12895. }
  12896. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12897. << getRedeclDiagFromTagKind(NewTag)
  12898. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12899. TypeWithKeyword::getTagTypeKindName(NewTag));
  12900. }
  12901. }
  12902. return true;
  12903. }
  12904. // Identify the prevailing tag kind: this is the kind of the definition (if
  12905. // there is a non-ignored definition), or otherwise the kind of the prior
  12906. // (non-ignored) declaration.
  12907. const TagDecl *PrevDef = Previous->getDefinition();
  12908. if (PrevDef && IsIgnored(PrevDef))
  12909. PrevDef = nullptr;
  12910. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12911. if (Redecl->getTagKind() != NewTag) {
  12912. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12913. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12914. << getRedeclDiagFromTagKind(OldTag);
  12915. Diag(Redecl->getLocation(), diag::note_previous_use);
  12916. // If there is a previous definition, suggest a fix-it.
  12917. if (PrevDef) {
  12918. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12919. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12920. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12921. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12922. }
  12923. }
  12924. return true;
  12925. }
  12926. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12927. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12928. /// This should provide the commented out code in the following snippet:
  12929. /// namespace N {
  12930. /// struct X;
  12931. /// namespace M {
  12932. /// struct Y { friend struct /*N::*/ X; };
  12933. /// }
  12934. /// }
  12935. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12936. SourceLocation NameLoc) {
  12937. // While the decl is in a namespace, do repeated lookup of that name and see
  12938. // if we get the same namespace back. If we do not, continue until
  12939. // translation unit scope, at which point we have a fully qualified NNS.
  12940. SmallVector<IdentifierInfo *, 4> Namespaces;
  12941. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12942. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12943. // This tag should be declared in a namespace, which can only be enclosed by
  12944. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12945. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12946. if (!Namespace || Namespace->isAnonymousNamespace())
  12947. return FixItHint();
  12948. IdentifierInfo *II = Namespace->getIdentifier();
  12949. Namespaces.push_back(II);
  12950. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12951. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12952. if (Lookup == Namespace)
  12953. break;
  12954. }
  12955. // Once we have all the namespaces, reverse them to go outermost first, and
  12956. // build an NNS.
  12957. SmallString<64> Insertion;
  12958. llvm::raw_svector_ostream OS(Insertion);
  12959. if (DC->isTranslationUnit())
  12960. OS << "::";
  12961. std::reverse(Namespaces.begin(), Namespaces.end());
  12962. for (auto *II : Namespaces)
  12963. OS << II->getName() << "::";
  12964. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12965. }
  12966. /// Determine whether a tag originally declared in context \p OldDC can
  12967. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12968. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12969. /// using-declaration).
  12970. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12971. DeclContext *NewDC) {
  12972. OldDC = OldDC->getRedeclContext();
  12973. NewDC = NewDC->getRedeclContext();
  12974. if (OldDC->Equals(NewDC))
  12975. return true;
  12976. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12977. // encloses the other).
  12978. if (S.getLangOpts().MSVCCompat &&
  12979. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12980. return true;
  12981. return false;
  12982. }
  12983. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12984. /// former case, Name will be non-null. In the later case, Name will be null.
  12985. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12986. /// reference/declaration/definition of a tag.
  12987. ///
  12988. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12989. /// trailing-type-specifier) other than one in an alias-declaration.
  12990. ///
  12991. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12992. /// skip the definition of this tag and treat it as if it were a declaration.
  12993. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12994. SourceLocation KWLoc, CXXScopeSpec &SS,
  12995. IdentifierInfo *Name, SourceLocation NameLoc,
  12996. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12997. SourceLocation ModulePrivateLoc,
  12998. MultiTemplateParamsArg TemplateParameterLists,
  12999. bool &OwnedDecl, bool &IsDependent,
  13000. SourceLocation ScopedEnumKWLoc,
  13001. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  13002. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  13003. SkipBodyInfo *SkipBody) {
  13004. // If this is not a definition, it must have a name.
  13005. IdentifierInfo *OrigName = Name;
  13006. assert((Name != nullptr || TUK == TUK_Definition) &&
  13007. "Nameless record must be a definition!");
  13008. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  13009. OwnedDecl = false;
  13010. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  13011. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  13012. // FIXME: Check member specializations more carefully.
  13013. bool isMemberSpecialization = false;
  13014. bool Invalid = false;
  13015. // We only need to do this matching if we have template parameters
  13016. // or a scope specifier, which also conveniently avoids this work
  13017. // for non-C++ cases.
  13018. if (TemplateParameterLists.size() > 0 ||
  13019. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  13020. if (TemplateParameterList *TemplateParams =
  13021. MatchTemplateParametersToScopeSpecifier(
  13022. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  13023. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  13024. if (Kind == TTK_Enum) {
  13025. Diag(KWLoc, diag::err_enum_template);
  13026. return nullptr;
  13027. }
  13028. if (TemplateParams->size() > 0) {
  13029. // This is a declaration or definition of a class template (which may
  13030. // be a member of another template).
  13031. if (Invalid)
  13032. return nullptr;
  13033. OwnedDecl = false;
  13034. DeclResult Result = CheckClassTemplate(
  13035. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  13036. AS, ModulePrivateLoc,
  13037. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  13038. TemplateParameterLists.data(), SkipBody);
  13039. return Result.get();
  13040. } else {
  13041. // The "template<>" header is extraneous.
  13042. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  13043. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  13044. isMemberSpecialization = true;
  13045. }
  13046. }
  13047. }
  13048. // Figure out the underlying type if this a enum declaration. We need to do
  13049. // this early, because it's needed to detect if this is an incompatible
  13050. // redeclaration.
  13051. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  13052. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  13053. if (Kind == TTK_Enum) {
  13054. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  13055. // No underlying type explicitly specified, or we failed to parse the
  13056. // type, default to int.
  13057. EnumUnderlying = Context.IntTy.getTypePtr();
  13058. } else if (UnderlyingType.get()) {
  13059. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  13060. // integral type; any cv-qualification is ignored.
  13061. TypeSourceInfo *TI = nullptr;
  13062. GetTypeFromParser(UnderlyingType.get(), &TI);
  13063. EnumUnderlying = TI;
  13064. if (CheckEnumUnderlyingType(TI))
  13065. // Recover by falling back to int.
  13066. EnumUnderlying = Context.IntTy.getTypePtr();
  13067. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  13068. UPPC_FixedUnderlyingType))
  13069. EnumUnderlying = Context.IntTy.getTypePtr();
  13070. } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
  13071. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  13072. // of 'int'. However, if this is an unfixed forward declaration, don't set
  13073. // the underlying type unless the user enables -fms-compatibility. This
  13074. // makes unfixed forward declared enums incomplete and is more conforming.
  13075. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  13076. EnumUnderlying = Context.IntTy.getTypePtr();
  13077. }
  13078. }
  13079. DeclContext *SearchDC = CurContext;
  13080. DeclContext *DC = CurContext;
  13081. bool isStdBadAlloc = false;
  13082. bool isStdAlignValT = false;
  13083. RedeclarationKind Redecl = forRedeclarationInCurContext();
  13084. if (TUK == TUK_Friend || TUK == TUK_Reference)
  13085. Redecl = NotForRedeclaration;
  13086. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  13087. /// implemented asks for structural equivalence checking, the returned decl
  13088. /// here is passed back to the parser, allowing the tag body to be parsed.
  13089. auto createTagFromNewDecl = [&]() -> TagDecl * {
  13090. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  13091. // If there is an identifier, use the location of the identifier as the
  13092. // location of the decl, otherwise use the location of the struct/union
  13093. // keyword.
  13094. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13095. TagDecl *New = nullptr;
  13096. if (Kind == TTK_Enum) {
  13097. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  13098. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  13099. // If this is an undefined enum, bail.
  13100. if (TUK != TUK_Definition && !Invalid)
  13101. return nullptr;
  13102. if (EnumUnderlying) {
  13103. EnumDecl *ED = cast<EnumDecl>(New);
  13104. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  13105. ED->setIntegerTypeSourceInfo(TI);
  13106. else
  13107. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  13108. ED->setPromotionType(ED->getIntegerType());
  13109. }
  13110. } else { // struct/union
  13111. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13112. nullptr);
  13113. }
  13114. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13115. // Add alignment attributes if necessary; these attributes are checked
  13116. // when the ASTContext lays out the structure.
  13117. //
  13118. // It is important for implementing the correct semantics that this
  13119. // happen here (in ActOnTag). The #pragma pack stack is
  13120. // maintained as a result of parser callbacks which can occur at
  13121. // many points during the parsing of a struct declaration (because
  13122. // the #pragma tokens are effectively skipped over during the
  13123. // parsing of the struct).
  13124. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13125. AddAlignmentAttributesForRecord(RD);
  13126. AddMsStructLayoutForRecord(RD);
  13127. }
  13128. }
  13129. New->setLexicalDeclContext(CurContext);
  13130. return New;
  13131. };
  13132. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  13133. if (Name && SS.isNotEmpty()) {
  13134. // We have a nested-name tag ('struct foo::bar').
  13135. // Check for invalid 'foo::'.
  13136. if (SS.isInvalid()) {
  13137. Name = nullptr;
  13138. goto CreateNewDecl;
  13139. }
  13140. // If this is a friend or a reference to a class in a dependent
  13141. // context, don't try to make a decl for it.
  13142. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13143. DC = computeDeclContext(SS, false);
  13144. if (!DC) {
  13145. IsDependent = true;
  13146. return nullptr;
  13147. }
  13148. } else {
  13149. DC = computeDeclContext(SS, true);
  13150. if (!DC) {
  13151. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  13152. << SS.getRange();
  13153. return nullptr;
  13154. }
  13155. }
  13156. if (RequireCompleteDeclContext(SS, DC))
  13157. return nullptr;
  13158. SearchDC = DC;
  13159. // Look-up name inside 'foo::'.
  13160. LookupQualifiedName(Previous, DC);
  13161. if (Previous.isAmbiguous())
  13162. return nullptr;
  13163. if (Previous.empty()) {
  13164. // Name lookup did not find anything. However, if the
  13165. // nested-name-specifier refers to the current instantiation,
  13166. // and that current instantiation has any dependent base
  13167. // classes, we might find something at instantiation time: treat
  13168. // this as a dependent elaborated-type-specifier.
  13169. // But this only makes any sense for reference-like lookups.
  13170. if (Previous.wasNotFoundInCurrentInstantiation() &&
  13171. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  13172. IsDependent = true;
  13173. return nullptr;
  13174. }
  13175. // A tag 'foo::bar' must already exist.
  13176. Diag(NameLoc, diag::err_not_tag_in_scope)
  13177. << Kind << Name << DC << SS.getRange();
  13178. Name = nullptr;
  13179. Invalid = true;
  13180. goto CreateNewDecl;
  13181. }
  13182. } else if (Name) {
  13183. // C++14 [class.mem]p14:
  13184. // If T is the name of a class, then each of the following shall have a
  13185. // name different from T:
  13186. // -- every member of class T that is itself a type
  13187. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  13188. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  13189. return nullptr;
  13190. // If this is a named struct, check to see if there was a previous forward
  13191. // declaration or definition.
  13192. // FIXME: We're looking into outer scopes here, even when we
  13193. // shouldn't be. Doing so can result in ambiguities that we
  13194. // shouldn't be diagnosing.
  13195. LookupName(Previous, S);
  13196. // When declaring or defining a tag, ignore ambiguities introduced
  13197. // by types using'ed into this scope.
  13198. if (Previous.isAmbiguous() &&
  13199. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  13200. LookupResult::Filter F = Previous.makeFilter();
  13201. while (F.hasNext()) {
  13202. NamedDecl *ND = F.next();
  13203. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  13204. SearchDC->getRedeclContext()))
  13205. F.erase();
  13206. }
  13207. F.done();
  13208. }
  13209. // C++11 [namespace.memdef]p3:
  13210. // If the name in a friend declaration is neither qualified nor
  13211. // a template-id and the declaration is a function or an
  13212. // elaborated-type-specifier, the lookup to determine whether
  13213. // the entity has been previously declared shall not consider
  13214. // any scopes outside the innermost enclosing namespace.
  13215. //
  13216. // MSVC doesn't implement the above rule for types, so a friend tag
  13217. // declaration may be a redeclaration of a type declared in an enclosing
  13218. // scope. They do implement this rule for friend functions.
  13219. //
  13220. // Does it matter that this should be by scope instead of by
  13221. // semantic context?
  13222. if (!Previous.empty() && TUK == TUK_Friend) {
  13223. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  13224. LookupResult::Filter F = Previous.makeFilter();
  13225. bool FriendSawTagOutsideEnclosingNamespace = false;
  13226. while (F.hasNext()) {
  13227. NamedDecl *ND = F.next();
  13228. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13229. if (DC->isFileContext() &&
  13230. !EnclosingNS->Encloses(ND->getDeclContext())) {
  13231. if (getLangOpts().MSVCCompat)
  13232. FriendSawTagOutsideEnclosingNamespace = true;
  13233. else
  13234. F.erase();
  13235. }
  13236. }
  13237. F.done();
  13238. // Diagnose this MSVC extension in the easy case where lookup would have
  13239. // unambiguously found something outside the enclosing namespace.
  13240. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  13241. NamedDecl *ND = Previous.getFoundDecl();
  13242. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  13243. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  13244. }
  13245. }
  13246. // Note: there used to be some attempt at recovery here.
  13247. if (Previous.isAmbiguous())
  13248. return nullptr;
  13249. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  13250. // FIXME: This makes sure that we ignore the contexts associated
  13251. // with C structs, unions, and enums when looking for a matching
  13252. // tag declaration or definition. See the similar lookup tweak
  13253. // in Sema::LookupName; is there a better way to deal with this?
  13254. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  13255. SearchDC = SearchDC->getParent();
  13256. }
  13257. }
  13258. if (Previous.isSingleResult() &&
  13259. Previous.getFoundDecl()->isTemplateParameter()) {
  13260. // Maybe we will complain about the shadowed template parameter.
  13261. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  13262. // Just pretend that we didn't see the previous declaration.
  13263. Previous.clear();
  13264. }
  13265. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  13266. DC->Equals(getStdNamespace())) {
  13267. if (Name->isStr("bad_alloc")) {
  13268. // This is a declaration of or a reference to "std::bad_alloc".
  13269. isStdBadAlloc = true;
  13270. // If std::bad_alloc has been implicitly declared (but made invisible to
  13271. // name lookup), fill in this implicit declaration as the previous
  13272. // declaration, so that the declarations get chained appropriately.
  13273. if (Previous.empty() && StdBadAlloc)
  13274. Previous.addDecl(getStdBadAlloc());
  13275. } else if (Name->isStr("align_val_t")) {
  13276. isStdAlignValT = true;
  13277. if (Previous.empty() && StdAlignValT)
  13278. Previous.addDecl(getStdAlignValT());
  13279. }
  13280. }
  13281. // If we didn't find a previous declaration, and this is a reference
  13282. // (or friend reference), move to the correct scope. In C++, we
  13283. // also need to do a redeclaration lookup there, just in case
  13284. // there's a shadow friend decl.
  13285. if (Name && Previous.empty() &&
  13286. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  13287. if (Invalid) goto CreateNewDecl;
  13288. assert(SS.isEmpty());
  13289. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  13290. // C++ [basic.scope.pdecl]p5:
  13291. // -- for an elaborated-type-specifier of the form
  13292. //
  13293. // class-key identifier
  13294. //
  13295. // if the elaborated-type-specifier is used in the
  13296. // decl-specifier-seq or parameter-declaration-clause of a
  13297. // function defined in namespace scope, the identifier is
  13298. // declared as a class-name in the namespace that contains
  13299. // the declaration; otherwise, except as a friend
  13300. // declaration, the identifier is declared in the smallest
  13301. // non-class, non-function-prototype scope that contains the
  13302. // declaration.
  13303. //
  13304. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  13305. // C structs and unions.
  13306. //
  13307. // It is an error in C++ to declare (rather than define) an enum
  13308. // type, including via an elaborated type specifier. We'll
  13309. // diagnose that later; for now, declare the enum in the same
  13310. // scope as we would have picked for any other tag type.
  13311. //
  13312. // GNU C also supports this behavior as part of its incomplete
  13313. // enum types extension, while GNU C++ does not.
  13314. //
  13315. // Find the context where we'll be declaring the tag.
  13316. // FIXME: We would like to maintain the current DeclContext as the
  13317. // lexical context,
  13318. SearchDC = getTagInjectionContext(SearchDC);
  13319. // Find the scope where we'll be declaring the tag.
  13320. S = getTagInjectionScope(S, getLangOpts());
  13321. } else {
  13322. assert(TUK == TUK_Friend);
  13323. // C++ [namespace.memdef]p3:
  13324. // If a friend declaration in a non-local class first declares a
  13325. // class or function, the friend class or function is a member of
  13326. // the innermost enclosing namespace.
  13327. SearchDC = SearchDC->getEnclosingNamespaceContext();
  13328. }
  13329. // In C++, we need to do a redeclaration lookup to properly
  13330. // diagnose some problems.
  13331. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  13332. // hidden declaration so that we don't get ambiguity errors when using a
  13333. // type declared by an elaborated-type-specifier. In C that is not correct
  13334. // and we should instead merge compatible types found by lookup.
  13335. if (getLangOpts().CPlusPlus) {
  13336. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13337. LookupQualifiedName(Previous, SearchDC);
  13338. } else {
  13339. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  13340. LookupName(Previous, S);
  13341. }
  13342. }
  13343. // If we have a known previous declaration to use, then use it.
  13344. if (Previous.empty() && SkipBody && SkipBody->Previous)
  13345. Previous.addDecl(SkipBody->Previous);
  13346. if (!Previous.empty()) {
  13347. NamedDecl *PrevDecl = Previous.getFoundDecl();
  13348. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  13349. // It's okay to have a tag decl in the same scope as a typedef
  13350. // which hides a tag decl in the same scope. Finding this
  13351. // insanity with a redeclaration lookup can only actually happen
  13352. // in C++.
  13353. //
  13354. // This is also okay for elaborated-type-specifiers, which is
  13355. // technically forbidden by the current standard but which is
  13356. // okay according to the likely resolution of an open issue;
  13357. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  13358. if (getLangOpts().CPlusPlus) {
  13359. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13360. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  13361. TagDecl *Tag = TT->getDecl();
  13362. if (Tag->getDeclName() == Name &&
  13363. Tag->getDeclContext()->getRedeclContext()
  13364. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  13365. PrevDecl = Tag;
  13366. Previous.clear();
  13367. Previous.addDecl(Tag);
  13368. Previous.resolveKind();
  13369. }
  13370. }
  13371. }
  13372. }
  13373. // If this is a redeclaration of a using shadow declaration, it must
  13374. // declare a tag in the same context. In MSVC mode, we allow a
  13375. // redefinition if either context is within the other.
  13376. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  13377. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  13378. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  13379. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  13380. !(OldTag && isAcceptableTagRedeclContext(
  13381. *this, OldTag->getDeclContext(), SearchDC))) {
  13382. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  13383. Diag(Shadow->getTargetDecl()->getLocation(),
  13384. diag::note_using_decl_target);
  13385. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  13386. << 0;
  13387. // Recover by ignoring the old declaration.
  13388. Previous.clear();
  13389. goto CreateNewDecl;
  13390. }
  13391. }
  13392. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  13393. // If this is a use of a previous tag, or if the tag is already declared
  13394. // in the same scope (so that the definition/declaration completes or
  13395. // rementions the tag), reuse the decl.
  13396. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  13397. isDeclInScope(DirectPrevDecl, SearchDC, S,
  13398. SS.isNotEmpty() || isMemberSpecialization)) {
  13399. // Make sure that this wasn't declared as an enum and now used as a
  13400. // struct or something similar.
  13401. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  13402. TUK == TUK_Definition, KWLoc,
  13403. Name)) {
  13404. bool SafeToContinue
  13405. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  13406. Kind != TTK_Enum);
  13407. if (SafeToContinue)
  13408. Diag(KWLoc, diag::err_use_with_wrong_tag)
  13409. << Name
  13410. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  13411. PrevTagDecl->getKindName());
  13412. else
  13413. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  13414. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  13415. if (SafeToContinue)
  13416. Kind = PrevTagDecl->getTagKind();
  13417. else {
  13418. // Recover by making this an anonymous redefinition.
  13419. Name = nullptr;
  13420. Previous.clear();
  13421. Invalid = true;
  13422. }
  13423. }
  13424. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  13425. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  13426. // If this is an elaborated-type-specifier for a scoped enumeration,
  13427. // the 'class' keyword is not necessary and not permitted.
  13428. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13429. if (ScopedEnum)
  13430. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  13431. << PrevEnum->isScoped()
  13432. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  13433. return PrevTagDecl;
  13434. }
  13435. QualType EnumUnderlyingTy;
  13436. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13437. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  13438. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  13439. EnumUnderlyingTy = QualType(T, 0);
  13440. // All conflicts with previous declarations are recovered by
  13441. // returning the previous declaration, unless this is a definition,
  13442. // in which case we want the caller to bail out.
  13443. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  13444. ScopedEnum, EnumUnderlyingTy,
  13445. IsFixed, PrevEnum))
  13446. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  13447. }
  13448. // C++11 [class.mem]p1:
  13449. // A member shall not be declared twice in the member-specification,
  13450. // except that a nested class or member class template can be declared
  13451. // and then later defined.
  13452. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  13453. S->isDeclScope(PrevDecl)) {
  13454. Diag(NameLoc, diag::ext_member_redeclared);
  13455. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  13456. }
  13457. if (!Invalid) {
  13458. // If this is a use, just return the declaration we found, unless
  13459. // we have attributes.
  13460. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13461. if (!Attrs.empty()) {
  13462. // FIXME: Diagnose these attributes. For now, we create a new
  13463. // declaration to hold them.
  13464. } else if (TUK == TUK_Reference &&
  13465. (PrevTagDecl->getFriendObjectKind() ==
  13466. Decl::FOK_Undeclared ||
  13467. PrevDecl->getOwningModule() != getCurrentModule()) &&
  13468. SS.isEmpty()) {
  13469. // This declaration is a reference to an existing entity, but
  13470. // has different visibility from that entity: it either makes
  13471. // a friend visible or it makes a type visible in a new module.
  13472. // In either case, create a new declaration. We only do this if
  13473. // the declaration would have meant the same thing if no prior
  13474. // declaration were found, that is, if it was found in the same
  13475. // scope where we would have injected a declaration.
  13476. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  13477. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  13478. return PrevTagDecl;
  13479. // This is in the injected scope, create a new declaration in
  13480. // that scope.
  13481. S = getTagInjectionScope(S, getLangOpts());
  13482. } else {
  13483. return PrevTagDecl;
  13484. }
  13485. }
  13486. // Diagnose attempts to redefine a tag.
  13487. if (TUK == TUK_Definition) {
  13488. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  13489. // If we're defining a specialization and the previous definition
  13490. // is from an implicit instantiation, don't emit an error
  13491. // here; we'll catch this in the general case below.
  13492. bool IsExplicitSpecializationAfterInstantiation = false;
  13493. if (isMemberSpecialization) {
  13494. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  13495. IsExplicitSpecializationAfterInstantiation =
  13496. RD->getTemplateSpecializationKind() !=
  13497. TSK_ExplicitSpecialization;
  13498. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  13499. IsExplicitSpecializationAfterInstantiation =
  13500. ED->getTemplateSpecializationKind() !=
  13501. TSK_ExplicitSpecialization;
  13502. }
  13503. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  13504. // not keep more that one definition around (merge them). However,
  13505. // ensure the decl passes the structural compatibility check in
  13506. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  13507. NamedDecl *Hidden = nullptr;
  13508. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  13509. // There is a definition of this tag, but it is not visible. We
  13510. // explicitly make use of C++'s one definition rule here, and
  13511. // assume that this definition is identical to the hidden one
  13512. // we already have. Make the existing definition visible and
  13513. // use it in place of this one.
  13514. if (!getLangOpts().CPlusPlus) {
  13515. // Postpone making the old definition visible until after we
  13516. // complete parsing the new one and do the structural
  13517. // comparison.
  13518. SkipBody->CheckSameAsPrevious = true;
  13519. SkipBody->New = createTagFromNewDecl();
  13520. SkipBody->Previous = Def;
  13521. return Def;
  13522. } else {
  13523. SkipBody->ShouldSkip = true;
  13524. SkipBody->Previous = Def;
  13525. makeMergedDefinitionVisible(Hidden);
  13526. // Carry on and handle it like a normal definition. We'll
  13527. // skip starting the definitiion later.
  13528. }
  13529. } else if (!IsExplicitSpecializationAfterInstantiation) {
  13530. // A redeclaration in function prototype scope in C isn't
  13531. // visible elsewhere, so merely issue a warning.
  13532. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  13533. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  13534. else
  13535. Diag(NameLoc, diag::err_redefinition) << Name;
  13536. notePreviousDefinition(Def,
  13537. NameLoc.isValid() ? NameLoc : KWLoc);
  13538. // If this is a redefinition, recover by making this
  13539. // struct be anonymous, which will make any later
  13540. // references get the previous definition.
  13541. Name = nullptr;
  13542. Previous.clear();
  13543. Invalid = true;
  13544. }
  13545. } else {
  13546. // If the type is currently being defined, complain
  13547. // about a nested redefinition.
  13548. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  13549. if (TD->isBeingDefined()) {
  13550. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  13551. Diag(PrevTagDecl->getLocation(),
  13552. diag::note_previous_definition);
  13553. Name = nullptr;
  13554. Previous.clear();
  13555. Invalid = true;
  13556. }
  13557. }
  13558. // Okay, this is definition of a previously declared or referenced
  13559. // tag. We're going to create a new Decl for it.
  13560. }
  13561. // Okay, we're going to make a redeclaration. If this is some kind
  13562. // of reference, make sure we build the redeclaration in the same DC
  13563. // as the original, and ignore the current access specifier.
  13564. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  13565. SearchDC = PrevTagDecl->getDeclContext();
  13566. AS = AS_none;
  13567. }
  13568. }
  13569. // If we get here we have (another) forward declaration or we
  13570. // have a definition. Just create a new decl.
  13571. } else {
  13572. // If we get here, this is a definition of a new tag type in a nested
  13573. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  13574. // new decl/type. We set PrevDecl to NULL so that the entities
  13575. // have distinct types.
  13576. Previous.clear();
  13577. }
  13578. // If we get here, we're going to create a new Decl. If PrevDecl
  13579. // is non-NULL, it's a definition of the tag declared by
  13580. // PrevDecl. If it's NULL, we have a new definition.
  13581. // Otherwise, PrevDecl is not a tag, but was found with tag
  13582. // lookup. This is only actually possible in C++, where a few
  13583. // things like templates still live in the tag namespace.
  13584. } else {
  13585. // Use a better diagnostic if an elaborated-type-specifier
  13586. // found the wrong kind of type on the first
  13587. // (non-redeclaration) lookup.
  13588. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13589. !Previous.isForRedeclaration()) {
  13590. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13591. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13592. << Kind;
  13593. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13594. Invalid = true;
  13595. // Otherwise, only diagnose if the declaration is in scope.
  13596. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13597. SS.isNotEmpty() || isMemberSpecialization)) {
  13598. // do nothing
  13599. // Diagnose implicit declarations introduced by elaborated types.
  13600. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13601. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13602. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13603. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13604. Invalid = true;
  13605. // Otherwise it's a declaration. Call out a particularly common
  13606. // case here.
  13607. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13608. unsigned Kind = 0;
  13609. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13610. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13611. << Name << Kind << TND->getUnderlyingType();
  13612. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13613. Invalid = true;
  13614. // Otherwise, diagnose.
  13615. } else {
  13616. // The tag name clashes with something else in the target scope,
  13617. // issue an error and recover by making this tag be anonymous.
  13618. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13619. notePreviousDefinition(PrevDecl, NameLoc);
  13620. Name = nullptr;
  13621. Invalid = true;
  13622. }
  13623. // The existing declaration isn't relevant to us; we're in a
  13624. // new scope, so clear out the previous declaration.
  13625. Previous.clear();
  13626. }
  13627. }
  13628. CreateNewDecl:
  13629. TagDecl *PrevDecl = nullptr;
  13630. if (Previous.isSingleResult())
  13631. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13632. // If there is an identifier, use the location of the identifier as the
  13633. // location of the decl, otherwise use the location of the struct/union
  13634. // keyword.
  13635. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13636. // Otherwise, create a new declaration. If there is a previous
  13637. // declaration of the same entity, the two will be linked via
  13638. // PrevDecl.
  13639. TagDecl *New;
  13640. if (Kind == TTK_Enum) {
  13641. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13642. // enum X { A, B, C } D; D should chain to X.
  13643. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13644. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13645. ScopedEnumUsesClassTag, IsFixed);
  13646. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13647. StdAlignValT = cast<EnumDecl>(New);
  13648. // If this is an undefined enum, warn.
  13649. if (TUK != TUK_Definition && !Invalid) {
  13650. TagDecl *Def;
  13651. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13652. // C++0x: 7.2p2: opaque-enum-declaration.
  13653. // Conflicts are diagnosed above. Do nothing.
  13654. }
  13655. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13656. Diag(Loc, diag::ext_forward_ref_enum_def)
  13657. << New;
  13658. Diag(Def->getLocation(), diag::note_previous_definition);
  13659. } else {
  13660. unsigned DiagID = diag::ext_forward_ref_enum;
  13661. if (getLangOpts().MSVCCompat)
  13662. DiagID = diag::ext_ms_forward_ref_enum;
  13663. else if (getLangOpts().CPlusPlus)
  13664. DiagID = diag::err_forward_ref_enum;
  13665. Diag(Loc, DiagID);
  13666. }
  13667. }
  13668. if (EnumUnderlying) {
  13669. EnumDecl *ED = cast<EnumDecl>(New);
  13670. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13671. ED->setIntegerTypeSourceInfo(TI);
  13672. else
  13673. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13674. ED->setPromotionType(ED->getIntegerType());
  13675. assert(ED->isComplete() && "enum with type should be complete");
  13676. }
  13677. } else {
  13678. // struct/union/class
  13679. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13680. // struct X { int A; } D; D should chain to X.
  13681. if (getLangOpts().CPlusPlus) {
  13682. // FIXME: Look for a way to use RecordDecl for simple structs.
  13683. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13684. cast_or_null<CXXRecordDecl>(PrevDecl));
  13685. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13686. StdBadAlloc = cast<CXXRecordDecl>(New);
  13687. } else
  13688. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13689. cast_or_null<RecordDecl>(PrevDecl));
  13690. }
  13691. // C++11 [dcl.type]p3:
  13692. // A type-specifier-seq shall not define a class or enumeration [...].
  13693. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13694. TUK == TUK_Definition) {
  13695. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13696. << Context.getTagDeclType(New);
  13697. Invalid = true;
  13698. }
  13699. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13700. DC->getDeclKind() == Decl::Enum) {
  13701. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13702. << Context.getTagDeclType(New);
  13703. Invalid = true;
  13704. }
  13705. // Maybe add qualifier info.
  13706. if (SS.isNotEmpty()) {
  13707. if (SS.isSet()) {
  13708. // If this is either a declaration or a definition, check the
  13709. // nested-name-specifier against the current context.
  13710. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13711. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13712. isMemberSpecialization))
  13713. Invalid = true;
  13714. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13715. if (TemplateParameterLists.size() > 0) {
  13716. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13717. }
  13718. }
  13719. else
  13720. Invalid = true;
  13721. }
  13722. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13723. // Add alignment attributes if necessary; these attributes are checked when
  13724. // the ASTContext lays out the structure.
  13725. //
  13726. // It is important for implementing the correct semantics that this
  13727. // happen here (in ActOnTag). The #pragma pack stack is
  13728. // maintained as a result of parser callbacks which can occur at
  13729. // many points during the parsing of a struct declaration (because
  13730. // the #pragma tokens are effectively skipped over during the
  13731. // parsing of the struct).
  13732. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13733. AddAlignmentAttributesForRecord(RD);
  13734. AddMsStructLayoutForRecord(RD);
  13735. }
  13736. }
  13737. if (ModulePrivateLoc.isValid()) {
  13738. if (isMemberSpecialization)
  13739. Diag(New->getLocation(), diag::err_module_private_specialization)
  13740. << 2
  13741. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13742. // __module_private__ does not apply to local classes. However, we only
  13743. // diagnose this as an error when the declaration specifiers are
  13744. // freestanding. Here, we just ignore the __module_private__.
  13745. else if (!SearchDC->isFunctionOrMethod())
  13746. New->setModulePrivate();
  13747. }
  13748. // If this is a specialization of a member class (of a class template),
  13749. // check the specialization.
  13750. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13751. Invalid = true;
  13752. // If we're declaring or defining a tag in function prototype scope in C,
  13753. // note that this type can only be used within the function and add it to
  13754. // the list of decls to inject into the function definition scope.
  13755. if ((Name || Kind == TTK_Enum) &&
  13756. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13757. if (getLangOpts().CPlusPlus) {
  13758. // C++ [dcl.fct]p6:
  13759. // Types shall not be defined in return or parameter types.
  13760. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13761. Diag(Loc, diag::err_type_defined_in_param_type)
  13762. << Name;
  13763. Invalid = true;
  13764. }
  13765. } else if (!PrevDecl) {
  13766. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13767. }
  13768. }
  13769. if (Invalid)
  13770. New->setInvalidDecl();
  13771. // Set the lexical context. If the tag has a C++ scope specifier, the
  13772. // lexical context will be different from the semantic context.
  13773. New->setLexicalDeclContext(CurContext);
  13774. // Mark this as a friend decl if applicable.
  13775. // In Microsoft mode, a friend declaration also acts as a forward
  13776. // declaration so we always pass true to setObjectOfFriendDecl to make
  13777. // the tag name visible.
  13778. if (TUK == TUK_Friend)
  13779. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13780. // Set the access specifier.
  13781. if (!Invalid && SearchDC->isRecord())
  13782. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13783. if (PrevDecl)
  13784. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13785. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13786. New->startDefinition();
  13787. ProcessDeclAttributeList(S, New, Attrs);
  13788. AddPragmaAttributes(S, New);
  13789. // If this has an identifier, add it to the scope stack.
  13790. if (TUK == TUK_Friend) {
  13791. // We might be replacing an existing declaration in the lookup tables;
  13792. // if so, borrow its access specifier.
  13793. if (PrevDecl)
  13794. New->setAccess(PrevDecl->getAccess());
  13795. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13796. DC->makeDeclVisibleInContext(New);
  13797. if (Name) // can be null along some error paths
  13798. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13799. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13800. } else if (Name) {
  13801. S = getNonFieldDeclScope(S);
  13802. PushOnScopeChains(New, S, true);
  13803. } else {
  13804. CurContext->addDecl(New);
  13805. }
  13806. // If this is the C FILE type, notify the AST context.
  13807. if (IdentifierInfo *II = New->getIdentifier())
  13808. if (!New->isInvalidDecl() &&
  13809. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13810. II->isStr("FILE"))
  13811. Context.setFILEDecl(New);
  13812. if (PrevDecl)
  13813. mergeDeclAttributes(New, PrevDecl);
  13814. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  13815. inferGslOwnerPointerAttribute(CXXRD);
  13816. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13817. // record.
  13818. AddPushedVisibilityAttribute(New);
  13819. if (isMemberSpecialization && !New->isInvalidDecl())
  13820. CompleteMemberSpecialization(New, Previous);
  13821. OwnedDecl = true;
  13822. // In C++, don't return an invalid declaration. We can't recover well from
  13823. // the cases where we make the type anonymous.
  13824. if (Invalid && getLangOpts().CPlusPlus) {
  13825. if (New->isBeingDefined())
  13826. if (auto RD = dyn_cast<RecordDecl>(New))
  13827. RD->completeDefinition();
  13828. return nullptr;
  13829. } else if (SkipBody && SkipBody->ShouldSkip) {
  13830. return SkipBody->Previous;
  13831. } else {
  13832. return New;
  13833. }
  13834. }
  13835. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13836. AdjustDeclIfTemplate(TagD);
  13837. TagDecl *Tag = cast<TagDecl>(TagD);
  13838. // Enter the tag context.
  13839. PushDeclContext(S, Tag);
  13840. ActOnDocumentableDecl(TagD);
  13841. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13842. // record.
  13843. AddPushedVisibilityAttribute(Tag);
  13844. }
  13845. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13846. SkipBodyInfo &SkipBody) {
  13847. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13848. return false;
  13849. // Make the previous decl visible.
  13850. makeMergedDefinitionVisible(SkipBody.Previous);
  13851. return true;
  13852. }
  13853. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13854. assert(isa<ObjCContainerDecl>(IDecl) &&
  13855. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13856. DeclContext *OCD = cast<DeclContext>(IDecl);
  13857. assert(getContainingDC(OCD) == CurContext &&
  13858. "The next DeclContext should be lexically contained in the current one.");
  13859. CurContext = OCD;
  13860. return IDecl;
  13861. }
  13862. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13863. SourceLocation FinalLoc,
  13864. bool IsFinalSpelledSealed,
  13865. SourceLocation LBraceLoc) {
  13866. AdjustDeclIfTemplate(TagD);
  13867. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13868. FieldCollector->StartClass();
  13869. if (!Record->getIdentifier())
  13870. return;
  13871. if (FinalLoc.isValid())
  13872. Record->addAttr(FinalAttr::Create(
  13873. Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
  13874. static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
  13875. // C++ [class]p2:
  13876. // [...] The class-name is also inserted into the scope of the
  13877. // class itself; this is known as the injected-class-name. For
  13878. // purposes of access checking, the injected-class-name is treated
  13879. // as if it were a public member name.
  13880. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13881. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13882. Record->getLocation(), Record->getIdentifier(),
  13883. /*PrevDecl=*/nullptr,
  13884. /*DelayTypeCreation=*/true);
  13885. Context.getTypeDeclType(InjectedClassName, Record);
  13886. InjectedClassName->setImplicit();
  13887. InjectedClassName->setAccess(AS_public);
  13888. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13889. InjectedClassName->setDescribedClassTemplate(Template);
  13890. PushOnScopeChains(InjectedClassName, S);
  13891. assert(InjectedClassName->isInjectedClassName() &&
  13892. "Broken injected-class-name");
  13893. }
  13894. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13895. SourceRange BraceRange) {
  13896. AdjustDeclIfTemplate(TagD);
  13897. TagDecl *Tag = cast<TagDecl>(TagD);
  13898. Tag->setBraceRange(BraceRange);
  13899. // Make sure we "complete" the definition even it is invalid.
  13900. if (Tag->isBeingDefined()) {
  13901. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13902. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13903. RD->completeDefinition();
  13904. }
  13905. if (isa<CXXRecordDecl>(Tag)) {
  13906. FieldCollector->FinishClass();
  13907. }
  13908. // Exit this scope of this tag's definition.
  13909. PopDeclContext();
  13910. if (getCurLexicalContext()->isObjCContainer() &&
  13911. Tag->getDeclContext()->isFileContext())
  13912. Tag->setTopLevelDeclInObjCContainer();
  13913. // Notify the consumer that we've defined a tag.
  13914. if (!Tag->isInvalidDecl())
  13915. Consumer.HandleTagDeclDefinition(Tag);
  13916. }
  13917. void Sema::ActOnObjCContainerFinishDefinition() {
  13918. // Exit this scope of this interface definition.
  13919. PopDeclContext();
  13920. }
  13921. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13922. assert(DC == CurContext && "Mismatch of container contexts");
  13923. OriginalLexicalContext = DC;
  13924. ActOnObjCContainerFinishDefinition();
  13925. }
  13926. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13927. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13928. OriginalLexicalContext = nullptr;
  13929. }
  13930. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13931. AdjustDeclIfTemplate(TagD);
  13932. TagDecl *Tag = cast<TagDecl>(TagD);
  13933. Tag->setInvalidDecl();
  13934. // Make sure we "complete" the definition even it is invalid.
  13935. if (Tag->isBeingDefined()) {
  13936. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13937. RD->completeDefinition();
  13938. }
  13939. // We're undoing ActOnTagStartDefinition here, not
  13940. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13941. // the FieldCollector.
  13942. PopDeclContext();
  13943. }
  13944. // Note that FieldName may be null for anonymous bitfields.
  13945. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13946. IdentifierInfo *FieldName,
  13947. QualType FieldTy, bool IsMsStruct,
  13948. Expr *BitWidth, bool *ZeroWidth) {
  13949. // Default to true; that shouldn't confuse checks for emptiness
  13950. if (ZeroWidth)
  13951. *ZeroWidth = true;
  13952. // C99 6.7.2.1p4 - verify the field type.
  13953. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13954. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13955. // Handle incomplete types with specific error.
  13956. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13957. return ExprError();
  13958. if (FieldName)
  13959. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13960. << FieldName << FieldTy << BitWidth->getSourceRange();
  13961. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13962. << FieldTy << BitWidth->getSourceRange();
  13963. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13964. UPPC_BitFieldWidth))
  13965. return ExprError();
  13966. // If the bit-width is type- or value-dependent, don't try to check
  13967. // it now.
  13968. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13969. return BitWidth;
  13970. llvm::APSInt Value;
  13971. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13972. if (ICE.isInvalid())
  13973. return ICE;
  13974. BitWidth = ICE.get();
  13975. if (Value != 0 && ZeroWidth)
  13976. *ZeroWidth = false;
  13977. // Zero-width bitfield is ok for anonymous field.
  13978. if (Value == 0 && FieldName)
  13979. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13980. if (Value.isSigned() && Value.isNegative()) {
  13981. if (FieldName)
  13982. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13983. << FieldName << Value.toString(10);
  13984. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13985. << Value.toString(10);
  13986. }
  13987. if (!FieldTy->isDependentType()) {
  13988. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13989. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13990. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13991. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13992. // ABI.
  13993. bool CStdConstraintViolation =
  13994. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13995. bool MSBitfieldViolation =
  13996. Value.ugt(TypeStorageSize) &&
  13997. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13998. if (CStdConstraintViolation || MSBitfieldViolation) {
  13999. unsigned DiagWidth =
  14000. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  14001. if (FieldName)
  14002. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  14003. << FieldName << (unsigned)Value.getZExtValue()
  14004. << !CStdConstraintViolation << DiagWidth;
  14005. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  14006. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  14007. << DiagWidth;
  14008. }
  14009. // Warn on types where the user might conceivably expect to get all
  14010. // specified bits as value bits: that's all integral types other than
  14011. // 'bool'.
  14012. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  14013. if (FieldName)
  14014. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  14015. << FieldName << (unsigned)Value.getZExtValue()
  14016. << (unsigned)TypeWidth;
  14017. else
  14018. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  14019. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  14020. }
  14021. }
  14022. return BitWidth;
  14023. }
  14024. /// ActOnField - Each field of a C struct/union is passed into this in order
  14025. /// to create a FieldDecl object for it.
  14026. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  14027. Declarator &D, Expr *BitfieldWidth) {
  14028. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  14029. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  14030. /*InitStyle=*/ICIS_NoInit, AS_public);
  14031. return Res;
  14032. }
  14033. /// HandleField - Analyze a field of a C struct or a C++ data member.
  14034. ///
  14035. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  14036. SourceLocation DeclStart,
  14037. Declarator &D, Expr *BitWidth,
  14038. InClassInitStyle InitStyle,
  14039. AccessSpecifier AS) {
  14040. if (D.isDecompositionDeclarator()) {
  14041. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  14042. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  14043. << Decomp.getSourceRange();
  14044. return nullptr;
  14045. }
  14046. IdentifierInfo *II = D.getIdentifier();
  14047. SourceLocation Loc = DeclStart;
  14048. if (II) Loc = D.getIdentifierLoc();
  14049. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14050. QualType T = TInfo->getType();
  14051. if (getLangOpts().CPlusPlus) {
  14052. CheckExtraCXXDefaultArguments(D);
  14053. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14054. UPPC_DataMemberType)) {
  14055. D.setInvalidType();
  14056. T = Context.IntTy;
  14057. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  14058. }
  14059. }
  14060. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  14061. if (D.getDeclSpec().isInlineSpecified())
  14062. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  14063. << getLangOpts().CPlusPlus17;
  14064. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  14065. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  14066. diag::err_invalid_thread)
  14067. << DeclSpec::getSpecifierName(TSCS);
  14068. // Check to see if this name was declared as a member previously
  14069. NamedDecl *PrevDecl = nullptr;
  14070. LookupResult Previous(*this, II, Loc, LookupMemberName,
  14071. ForVisibleRedeclaration);
  14072. LookupName(Previous, S);
  14073. switch (Previous.getResultKind()) {
  14074. case LookupResult::Found:
  14075. case LookupResult::FoundUnresolvedValue:
  14076. PrevDecl = Previous.getAsSingle<NamedDecl>();
  14077. break;
  14078. case LookupResult::FoundOverloaded:
  14079. PrevDecl = Previous.getRepresentativeDecl();
  14080. break;
  14081. case LookupResult::NotFound:
  14082. case LookupResult::NotFoundInCurrentInstantiation:
  14083. case LookupResult::Ambiguous:
  14084. break;
  14085. }
  14086. Previous.suppressDiagnostics();
  14087. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14088. // Maybe we will complain about the shadowed template parameter.
  14089. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  14090. // Just pretend that we didn't see the previous declaration.
  14091. PrevDecl = nullptr;
  14092. }
  14093. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  14094. PrevDecl = nullptr;
  14095. bool Mutable
  14096. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  14097. SourceLocation TSSL = D.getBeginLoc();
  14098. FieldDecl *NewFD
  14099. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  14100. TSSL, AS, PrevDecl, &D);
  14101. if (NewFD->isInvalidDecl())
  14102. Record->setInvalidDecl();
  14103. if (D.getDeclSpec().isModulePrivateSpecified())
  14104. NewFD->setModulePrivate();
  14105. if (NewFD->isInvalidDecl() && PrevDecl) {
  14106. // Don't introduce NewFD into scope; there's already something
  14107. // with the same name in the same scope.
  14108. } else if (II) {
  14109. PushOnScopeChains(NewFD, S);
  14110. } else
  14111. Record->addDecl(NewFD);
  14112. return NewFD;
  14113. }
  14114. /// Build a new FieldDecl and check its well-formedness.
  14115. ///
  14116. /// This routine builds a new FieldDecl given the fields name, type,
  14117. /// record, etc. \p PrevDecl should refer to any previous declaration
  14118. /// with the same name and in the same scope as the field to be
  14119. /// created.
  14120. ///
  14121. /// \returns a new FieldDecl.
  14122. ///
  14123. /// \todo The Declarator argument is a hack. It will be removed once
  14124. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  14125. TypeSourceInfo *TInfo,
  14126. RecordDecl *Record, SourceLocation Loc,
  14127. bool Mutable, Expr *BitWidth,
  14128. InClassInitStyle InitStyle,
  14129. SourceLocation TSSL,
  14130. AccessSpecifier AS, NamedDecl *PrevDecl,
  14131. Declarator *D) {
  14132. IdentifierInfo *II = Name.getAsIdentifierInfo();
  14133. bool InvalidDecl = false;
  14134. if (D) InvalidDecl = D->isInvalidType();
  14135. // If we receive a broken type, recover by assuming 'int' and
  14136. // marking this declaration as invalid.
  14137. if (T.isNull()) {
  14138. InvalidDecl = true;
  14139. T = Context.IntTy;
  14140. }
  14141. QualType EltTy = Context.getBaseElementType(T);
  14142. if (!EltTy->isDependentType()) {
  14143. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  14144. // Fields of incomplete type force their record to be invalid.
  14145. Record->setInvalidDecl();
  14146. InvalidDecl = true;
  14147. } else {
  14148. NamedDecl *Def;
  14149. EltTy->isIncompleteType(&Def);
  14150. if (Def && Def->isInvalidDecl()) {
  14151. Record->setInvalidDecl();
  14152. InvalidDecl = true;
  14153. }
  14154. }
  14155. }
  14156. // TR 18037 does not allow fields to be declared with address space
  14157. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  14158. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  14159. Diag(Loc, diag::err_field_with_address_space);
  14160. Record->setInvalidDecl();
  14161. InvalidDecl = true;
  14162. }
  14163. if (LangOpts.OpenCL) {
  14164. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  14165. // used as structure or union field: image, sampler, event or block types.
  14166. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  14167. T->isBlockPointerType()) {
  14168. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  14169. Record->setInvalidDecl();
  14170. InvalidDecl = true;
  14171. }
  14172. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  14173. if (BitWidth) {
  14174. Diag(Loc, diag::err_opencl_bitfields);
  14175. InvalidDecl = true;
  14176. }
  14177. }
  14178. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  14179. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  14180. T.hasQualifiers()) {
  14181. InvalidDecl = true;
  14182. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  14183. }
  14184. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14185. // than a variably modified type.
  14186. if (!InvalidDecl && T->isVariablyModifiedType()) {
  14187. bool SizeIsNegative;
  14188. llvm::APSInt Oversized;
  14189. TypeSourceInfo *FixedTInfo =
  14190. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  14191. SizeIsNegative,
  14192. Oversized);
  14193. if (FixedTInfo) {
  14194. Diag(Loc, diag::warn_illegal_constant_array_size);
  14195. TInfo = FixedTInfo;
  14196. T = FixedTInfo->getType();
  14197. } else {
  14198. if (SizeIsNegative)
  14199. Diag(Loc, diag::err_typecheck_negative_array_size);
  14200. else if (Oversized.getBoolValue())
  14201. Diag(Loc, diag::err_array_too_large)
  14202. << Oversized.toString(10);
  14203. else
  14204. Diag(Loc, diag::err_typecheck_field_variable_size);
  14205. InvalidDecl = true;
  14206. }
  14207. }
  14208. // Fields can not have abstract class types
  14209. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  14210. diag::err_abstract_type_in_decl,
  14211. AbstractFieldType))
  14212. InvalidDecl = true;
  14213. bool ZeroWidth = false;
  14214. if (InvalidDecl)
  14215. BitWidth = nullptr;
  14216. // If this is declared as a bit-field, check the bit-field.
  14217. if (BitWidth) {
  14218. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  14219. &ZeroWidth).get();
  14220. if (!BitWidth) {
  14221. InvalidDecl = true;
  14222. BitWidth = nullptr;
  14223. ZeroWidth = false;
  14224. }
  14225. }
  14226. // Check that 'mutable' is consistent with the type of the declaration.
  14227. if (!InvalidDecl && Mutable) {
  14228. unsigned DiagID = 0;
  14229. if (T->isReferenceType())
  14230. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  14231. : diag::err_mutable_reference;
  14232. else if (T.isConstQualified())
  14233. DiagID = diag::err_mutable_const;
  14234. if (DiagID) {
  14235. SourceLocation ErrLoc = Loc;
  14236. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  14237. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  14238. Diag(ErrLoc, DiagID);
  14239. if (DiagID != diag::ext_mutable_reference) {
  14240. Mutable = false;
  14241. InvalidDecl = true;
  14242. }
  14243. }
  14244. }
  14245. // C++11 [class.union]p8 (DR1460):
  14246. // At most one variant member of a union may have a
  14247. // brace-or-equal-initializer.
  14248. if (InitStyle != ICIS_NoInit)
  14249. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  14250. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  14251. BitWidth, Mutable, InitStyle);
  14252. if (InvalidDecl)
  14253. NewFD->setInvalidDecl();
  14254. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  14255. Diag(Loc, diag::err_duplicate_member) << II;
  14256. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14257. NewFD->setInvalidDecl();
  14258. }
  14259. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  14260. if (Record->isUnion()) {
  14261. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14262. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14263. if (RDecl->getDefinition()) {
  14264. // C++ [class.union]p1: An object of a class with a non-trivial
  14265. // constructor, a non-trivial copy constructor, a non-trivial
  14266. // destructor, or a non-trivial copy assignment operator
  14267. // cannot be a member of a union, nor can an array of such
  14268. // objects.
  14269. if (CheckNontrivialField(NewFD))
  14270. NewFD->setInvalidDecl();
  14271. }
  14272. }
  14273. // C++ [class.union]p1: If a union contains a member of reference type,
  14274. // the program is ill-formed, except when compiling with MSVC extensions
  14275. // enabled.
  14276. if (EltTy->isReferenceType()) {
  14277. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  14278. diag::ext_union_member_of_reference_type :
  14279. diag::err_union_member_of_reference_type)
  14280. << NewFD->getDeclName() << EltTy;
  14281. if (!getLangOpts().MicrosoftExt)
  14282. NewFD->setInvalidDecl();
  14283. }
  14284. }
  14285. }
  14286. // FIXME: We need to pass in the attributes given an AST
  14287. // representation, not a parser representation.
  14288. if (D) {
  14289. // FIXME: The current scope is almost... but not entirely... correct here.
  14290. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  14291. if (NewFD->hasAttrs())
  14292. CheckAlignasUnderalignment(NewFD);
  14293. }
  14294. // In auto-retain/release, infer strong retension for fields of
  14295. // retainable type.
  14296. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  14297. NewFD->setInvalidDecl();
  14298. if (T.isObjCGCWeak())
  14299. Diag(Loc, diag::warn_attribute_weak_on_field);
  14300. NewFD->setAccess(AS);
  14301. return NewFD;
  14302. }
  14303. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  14304. assert(FD);
  14305. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  14306. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  14307. return false;
  14308. QualType EltTy = Context.getBaseElementType(FD->getType());
  14309. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  14310. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  14311. if (RDecl->getDefinition()) {
  14312. // We check for copy constructors before constructors
  14313. // because otherwise we'll never get complaints about
  14314. // copy constructors.
  14315. CXXSpecialMember member = CXXInvalid;
  14316. // We're required to check for any non-trivial constructors. Since the
  14317. // implicit default constructor is suppressed if there are any
  14318. // user-declared constructors, we just need to check that there is a
  14319. // trivial default constructor and a trivial copy constructor. (We don't
  14320. // worry about move constructors here, since this is a C++98 check.)
  14321. if (RDecl->hasNonTrivialCopyConstructor())
  14322. member = CXXCopyConstructor;
  14323. else if (!RDecl->hasTrivialDefaultConstructor())
  14324. member = CXXDefaultConstructor;
  14325. else if (RDecl->hasNonTrivialCopyAssignment())
  14326. member = CXXCopyAssignment;
  14327. else if (RDecl->hasNonTrivialDestructor())
  14328. member = CXXDestructor;
  14329. if (member != CXXInvalid) {
  14330. if (!getLangOpts().CPlusPlus11 &&
  14331. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  14332. // Objective-C++ ARC: it is an error to have a non-trivial field of
  14333. // a union. However, system headers in Objective-C programs
  14334. // occasionally have Objective-C lifetime objects within unions,
  14335. // and rather than cause the program to fail, we make those
  14336. // members unavailable.
  14337. SourceLocation Loc = FD->getLocation();
  14338. if (getSourceManager().isInSystemHeader(Loc)) {
  14339. if (!FD->hasAttr<UnavailableAttr>())
  14340. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14341. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  14342. return false;
  14343. }
  14344. }
  14345. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  14346. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  14347. diag::err_illegal_union_or_anon_struct_member)
  14348. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  14349. DiagnoseNontrivial(RDecl, member);
  14350. return !getLangOpts().CPlusPlus11;
  14351. }
  14352. }
  14353. }
  14354. return false;
  14355. }
  14356. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  14357. /// AST enum value.
  14358. static ObjCIvarDecl::AccessControl
  14359. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  14360. switch (ivarVisibility) {
  14361. default: llvm_unreachable("Unknown visitibility kind");
  14362. case tok::objc_private: return ObjCIvarDecl::Private;
  14363. case tok::objc_public: return ObjCIvarDecl::Public;
  14364. case tok::objc_protected: return ObjCIvarDecl::Protected;
  14365. case tok::objc_package: return ObjCIvarDecl::Package;
  14366. }
  14367. }
  14368. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  14369. /// in order to create an IvarDecl object for it.
  14370. Decl *Sema::ActOnIvar(Scope *S,
  14371. SourceLocation DeclStart,
  14372. Declarator &D, Expr *BitfieldWidth,
  14373. tok::ObjCKeywordKind Visibility) {
  14374. IdentifierInfo *II = D.getIdentifier();
  14375. Expr *BitWidth = (Expr*)BitfieldWidth;
  14376. SourceLocation Loc = DeclStart;
  14377. if (II) Loc = D.getIdentifierLoc();
  14378. // FIXME: Unnamed fields can be handled in various different ways, for
  14379. // example, unnamed unions inject all members into the struct namespace!
  14380. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14381. QualType T = TInfo->getType();
  14382. if (BitWidth) {
  14383. // 6.7.2.1p3, 6.7.2.1p4
  14384. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  14385. if (!BitWidth)
  14386. D.setInvalidType();
  14387. } else {
  14388. // Not a bitfield.
  14389. // validate II.
  14390. }
  14391. if (T->isReferenceType()) {
  14392. Diag(Loc, diag::err_ivar_reference_type);
  14393. D.setInvalidType();
  14394. }
  14395. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  14396. // than a variably modified type.
  14397. else if (T->isVariablyModifiedType()) {
  14398. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  14399. D.setInvalidType();
  14400. }
  14401. // Get the visibility (access control) for this ivar.
  14402. ObjCIvarDecl::AccessControl ac =
  14403. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  14404. : ObjCIvarDecl::None;
  14405. // Must set ivar's DeclContext to its enclosing interface.
  14406. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  14407. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  14408. return nullptr;
  14409. ObjCContainerDecl *EnclosingContext;
  14410. if (ObjCImplementationDecl *IMPDecl =
  14411. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14412. if (LangOpts.ObjCRuntime.isFragile()) {
  14413. // Case of ivar declared in an implementation. Context is that of its class.
  14414. EnclosingContext = IMPDecl->getClassInterface();
  14415. assert(EnclosingContext && "Implementation has no class interface!");
  14416. }
  14417. else
  14418. EnclosingContext = EnclosingDecl;
  14419. } else {
  14420. if (ObjCCategoryDecl *CDecl =
  14421. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14422. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  14423. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  14424. return nullptr;
  14425. }
  14426. }
  14427. EnclosingContext = EnclosingDecl;
  14428. }
  14429. // Construct the decl.
  14430. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  14431. DeclStart, Loc, II, T,
  14432. TInfo, ac, (Expr *)BitfieldWidth);
  14433. if (II) {
  14434. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  14435. ForVisibleRedeclaration);
  14436. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  14437. && !isa<TagDecl>(PrevDecl)) {
  14438. Diag(Loc, diag::err_duplicate_member) << II;
  14439. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  14440. NewID->setInvalidDecl();
  14441. }
  14442. }
  14443. // Process attributes attached to the ivar.
  14444. ProcessDeclAttributes(S, NewID, D);
  14445. if (D.isInvalidType())
  14446. NewID->setInvalidDecl();
  14447. // In ARC, infer 'retaining' for ivars of retainable type.
  14448. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  14449. NewID->setInvalidDecl();
  14450. if (D.getDeclSpec().isModulePrivateSpecified())
  14451. NewID->setModulePrivate();
  14452. if (II) {
  14453. // FIXME: When interfaces are DeclContexts, we'll need to add
  14454. // these to the interface.
  14455. S->AddDecl(NewID);
  14456. IdResolver.AddDecl(NewID);
  14457. }
  14458. if (LangOpts.ObjCRuntime.isNonFragile() &&
  14459. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  14460. Diag(Loc, diag::warn_ivars_in_interface);
  14461. return NewID;
  14462. }
  14463. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  14464. /// class and class extensions. For every class \@interface and class
  14465. /// extension \@interface, if the last ivar is a bitfield of any type,
  14466. /// then add an implicit `char :0` ivar to the end of that interface.
  14467. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  14468. SmallVectorImpl<Decl *> &AllIvarDecls) {
  14469. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  14470. return;
  14471. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  14472. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  14473. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  14474. return;
  14475. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  14476. if (!ID) {
  14477. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  14478. if (!CD->IsClassExtension())
  14479. return;
  14480. }
  14481. // No need to add this to end of @implementation.
  14482. else
  14483. return;
  14484. }
  14485. // All conditions are met. Add a new bitfield to the tail end of ivars.
  14486. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  14487. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  14488. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  14489. DeclLoc, DeclLoc, nullptr,
  14490. Context.CharTy,
  14491. Context.getTrivialTypeSourceInfo(Context.CharTy,
  14492. DeclLoc),
  14493. ObjCIvarDecl::Private, BW,
  14494. true);
  14495. AllIvarDecls.push_back(Ivar);
  14496. }
  14497. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  14498. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  14499. SourceLocation RBrac,
  14500. const ParsedAttributesView &Attrs) {
  14501. assert(EnclosingDecl && "missing record or interface decl");
  14502. // If this is an Objective-C @implementation or category and we have
  14503. // new fields here we should reset the layout of the interface since
  14504. // it will now change.
  14505. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  14506. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  14507. switch (DC->getKind()) {
  14508. default: break;
  14509. case Decl::ObjCCategory:
  14510. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  14511. break;
  14512. case Decl::ObjCImplementation:
  14513. Context.
  14514. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  14515. break;
  14516. }
  14517. }
  14518. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  14519. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  14520. // Start counting up the number of named members; make sure to include
  14521. // members of anonymous structs and unions in the total.
  14522. unsigned NumNamedMembers = 0;
  14523. if (Record) {
  14524. for (const auto *I : Record->decls()) {
  14525. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  14526. if (IFD->getDeclName())
  14527. ++NumNamedMembers;
  14528. }
  14529. }
  14530. // Verify that all the fields are okay.
  14531. SmallVector<FieldDecl*, 32> RecFields;
  14532. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  14533. i != end; ++i) {
  14534. FieldDecl *FD = cast<FieldDecl>(*i);
  14535. // Get the type for the field.
  14536. const Type *FDTy = FD->getType().getTypePtr();
  14537. if (!FD->isAnonymousStructOrUnion()) {
  14538. // Remember all fields written by the user.
  14539. RecFields.push_back(FD);
  14540. }
  14541. // If the field is already invalid for some reason, don't emit more
  14542. // diagnostics about it.
  14543. if (FD->isInvalidDecl()) {
  14544. EnclosingDecl->setInvalidDecl();
  14545. continue;
  14546. }
  14547. // C99 6.7.2.1p2:
  14548. // A structure or union shall not contain a member with
  14549. // incomplete or function type (hence, a structure shall not
  14550. // contain an instance of itself, but may contain a pointer to
  14551. // an instance of itself), except that the last member of a
  14552. // structure with more than one named member may have incomplete
  14553. // array type; such a structure (and any union containing,
  14554. // possibly recursively, a member that is such a structure)
  14555. // shall not be a member of a structure or an element of an
  14556. // array.
  14557. bool IsLastField = (i + 1 == Fields.end());
  14558. if (FDTy->isFunctionType()) {
  14559. // Field declared as a function.
  14560. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  14561. << FD->getDeclName();
  14562. FD->setInvalidDecl();
  14563. EnclosingDecl->setInvalidDecl();
  14564. continue;
  14565. } else if (FDTy->isIncompleteArrayType() &&
  14566. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  14567. if (Record) {
  14568. // Flexible array member.
  14569. // Microsoft and g++ is more permissive regarding flexible array.
  14570. // It will accept flexible array in union and also
  14571. // as the sole element of a struct/class.
  14572. unsigned DiagID = 0;
  14573. if (!Record->isUnion() && !IsLastField) {
  14574. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  14575. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  14576. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  14577. FD->setInvalidDecl();
  14578. EnclosingDecl->setInvalidDecl();
  14579. continue;
  14580. } else if (Record->isUnion())
  14581. DiagID = getLangOpts().MicrosoftExt
  14582. ? diag::ext_flexible_array_union_ms
  14583. : getLangOpts().CPlusPlus
  14584. ? diag::ext_flexible_array_union_gnu
  14585. : diag::err_flexible_array_union;
  14586. else if (NumNamedMembers < 1)
  14587. DiagID = getLangOpts().MicrosoftExt
  14588. ? diag::ext_flexible_array_empty_aggregate_ms
  14589. : getLangOpts().CPlusPlus
  14590. ? diag::ext_flexible_array_empty_aggregate_gnu
  14591. : diag::err_flexible_array_empty_aggregate;
  14592. if (DiagID)
  14593. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14594. << Record->getTagKind();
  14595. // While the layout of types that contain virtual bases is not specified
  14596. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14597. // virtual bases after the derived members. This would make a flexible
  14598. // array member declared at the end of an object not adjacent to the end
  14599. // of the type.
  14600. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14601. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14602. << FD->getDeclName() << Record->getTagKind();
  14603. if (!getLangOpts().C99)
  14604. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14605. << FD->getDeclName() << Record->getTagKind();
  14606. // If the element type has a non-trivial destructor, we would not
  14607. // implicitly destroy the elements, so disallow it for now.
  14608. //
  14609. // FIXME: GCC allows this. We should probably either implicitly delete
  14610. // the destructor of the containing class, or just allow this.
  14611. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14612. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14613. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14614. << FD->getDeclName() << FD->getType();
  14615. FD->setInvalidDecl();
  14616. EnclosingDecl->setInvalidDecl();
  14617. continue;
  14618. }
  14619. // Okay, we have a legal flexible array member at the end of the struct.
  14620. Record->setHasFlexibleArrayMember(true);
  14621. } else {
  14622. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14623. // unless they are followed by another ivar. That check is done
  14624. // elsewhere, after synthesized ivars are known.
  14625. }
  14626. } else if (!FDTy->isDependentType() &&
  14627. RequireCompleteType(FD->getLocation(), FD->getType(),
  14628. diag::err_field_incomplete)) {
  14629. // Incomplete type
  14630. FD->setInvalidDecl();
  14631. EnclosingDecl->setInvalidDecl();
  14632. continue;
  14633. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14634. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14635. // A type which contains a flexible array member is considered to be a
  14636. // flexible array member.
  14637. Record->setHasFlexibleArrayMember(true);
  14638. if (!Record->isUnion()) {
  14639. // If this is a struct/class and this is not the last element, reject
  14640. // it. Note that GCC supports variable sized arrays in the middle of
  14641. // structures.
  14642. if (!IsLastField)
  14643. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14644. << FD->getDeclName() << FD->getType();
  14645. else {
  14646. // We support flexible arrays at the end of structs in
  14647. // other structs as an extension.
  14648. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14649. << FD->getDeclName();
  14650. }
  14651. }
  14652. }
  14653. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14654. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14655. diag::err_abstract_type_in_decl,
  14656. AbstractIvarType)) {
  14657. // Ivars can not have abstract class types
  14658. FD->setInvalidDecl();
  14659. }
  14660. if (Record && FDTTy->getDecl()->hasObjectMember())
  14661. Record->setHasObjectMember(true);
  14662. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14663. Record->setHasVolatileMember(true);
  14664. } else if (FDTy->isObjCObjectType()) {
  14665. /// A field cannot be an Objective-c object
  14666. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14667. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14668. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14669. FD->setType(T);
  14670. } else if (Record && Record->isUnion() &&
  14671. FD->getType().hasNonTrivialObjCLifetime() &&
  14672. getSourceManager().isInSystemHeader(FD->getLocation()) &&
  14673. !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
  14674. (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
  14675. !Context.hasDirectOwnershipQualifier(FD->getType()))) {
  14676. // For backward compatibility, fields of C unions declared in system
  14677. // headers that have non-trivial ObjC ownership qualifications are marked
  14678. // as unavailable unless the qualifier is explicit and __strong. This can
  14679. // break ABI compatibility between programs compiled with ARC and MRR, but
  14680. // is a better option than rejecting programs using those unions under
  14681. // ARC.
  14682. FD->addAttr(UnavailableAttr::CreateImplicit(
  14683. Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
  14684. FD->getLocation()));
  14685. } else if (getLangOpts().ObjC &&
  14686. getLangOpts().getGC() != LangOptions::NonGC &&
  14687. Record && !Record->hasObjectMember()) {
  14688. if (FD->getType()->isObjCObjectPointerType() ||
  14689. FD->getType().isObjCGCStrong())
  14690. Record->setHasObjectMember(true);
  14691. else if (Context.getAsArrayType(FD->getType())) {
  14692. QualType BaseType = Context.getBaseElementType(FD->getType());
  14693. if (BaseType->isRecordType() &&
  14694. BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
  14695. Record->setHasObjectMember(true);
  14696. else if (BaseType->isObjCObjectPointerType() ||
  14697. BaseType.isObjCGCStrong())
  14698. Record->setHasObjectMember(true);
  14699. }
  14700. }
  14701. if (Record && !getLangOpts().CPlusPlus &&
  14702. !shouldIgnoreForRecordTriviality(FD)) {
  14703. QualType FT = FD->getType();
  14704. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  14705. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14706. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  14707. Record->isUnion())
  14708. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  14709. }
  14710. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14711. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  14712. Record->setNonTrivialToPrimitiveCopy(true);
  14713. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  14714. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  14715. }
  14716. if (FT.isDestructedType()) {
  14717. Record->setNonTrivialToPrimitiveDestroy(true);
  14718. Record->setParamDestroyedInCallee(true);
  14719. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  14720. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  14721. }
  14722. if (const auto *RT = FT->getAs<RecordType>()) {
  14723. if (RT->getDecl()->getArgPassingRestrictions() ==
  14724. RecordDecl::APK_CanNeverPassInRegs)
  14725. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14726. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14727. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14728. }
  14729. if (Record && FD->getType().isVolatileQualified())
  14730. Record->setHasVolatileMember(true);
  14731. // Keep track of the number of named members.
  14732. if (FD->getIdentifier())
  14733. ++NumNamedMembers;
  14734. }
  14735. // Okay, we successfully defined 'Record'.
  14736. if (Record) {
  14737. bool Completed = false;
  14738. if (CXXRecord) {
  14739. if (!CXXRecord->isInvalidDecl()) {
  14740. // Set access bits correctly on the directly-declared conversions.
  14741. for (CXXRecordDecl::conversion_iterator
  14742. I = CXXRecord->conversion_begin(),
  14743. E = CXXRecord->conversion_end(); I != E; ++I)
  14744. I.setAccess((*I)->getAccess());
  14745. }
  14746. if (!CXXRecord->isDependentType()) {
  14747. // Add any implicitly-declared members to this class.
  14748. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14749. if (!CXXRecord->isInvalidDecl()) {
  14750. // If we have virtual base classes, we may end up finding multiple
  14751. // final overriders for a given virtual function. Check for this
  14752. // problem now.
  14753. if (CXXRecord->getNumVBases()) {
  14754. CXXFinalOverriderMap FinalOverriders;
  14755. CXXRecord->getFinalOverriders(FinalOverriders);
  14756. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14757. MEnd = FinalOverriders.end();
  14758. M != MEnd; ++M) {
  14759. for (OverridingMethods::iterator SO = M->second.begin(),
  14760. SOEnd = M->second.end();
  14761. SO != SOEnd; ++SO) {
  14762. assert(SO->second.size() > 0 &&
  14763. "Virtual function without overriding functions?");
  14764. if (SO->second.size() == 1)
  14765. continue;
  14766. // C++ [class.virtual]p2:
  14767. // In a derived class, if a virtual member function of a base
  14768. // class subobject has more than one final overrider the
  14769. // program is ill-formed.
  14770. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14771. << (const NamedDecl *)M->first << Record;
  14772. Diag(M->first->getLocation(),
  14773. diag::note_overridden_virtual_function);
  14774. for (OverridingMethods::overriding_iterator
  14775. OM = SO->second.begin(),
  14776. OMEnd = SO->second.end();
  14777. OM != OMEnd; ++OM)
  14778. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14779. << (const NamedDecl *)M->first << OM->Method->getParent();
  14780. Record->setInvalidDecl();
  14781. }
  14782. }
  14783. CXXRecord->completeDefinition(&FinalOverriders);
  14784. Completed = true;
  14785. }
  14786. }
  14787. }
  14788. }
  14789. if (!Completed)
  14790. Record->completeDefinition();
  14791. // Handle attributes before checking the layout.
  14792. ProcessDeclAttributeList(S, Record, Attrs);
  14793. // We may have deferred checking for a deleted destructor. Check now.
  14794. if (CXXRecord) {
  14795. auto *Dtor = CXXRecord->getDestructor();
  14796. if (Dtor && Dtor->isImplicit() &&
  14797. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14798. CXXRecord->setImplicitDestructorIsDeleted();
  14799. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14800. }
  14801. }
  14802. if (Record->hasAttrs()) {
  14803. CheckAlignasUnderalignment(Record);
  14804. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14805. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14806. IA->getRange(), IA->getBestCase(),
  14807. IA->getSemanticSpelling());
  14808. }
  14809. // Check if the structure/union declaration is a type that can have zero
  14810. // size in C. For C this is a language extension, for C++ it may cause
  14811. // compatibility problems.
  14812. bool CheckForZeroSize;
  14813. if (!getLangOpts().CPlusPlus) {
  14814. CheckForZeroSize = true;
  14815. } else {
  14816. // For C++ filter out types that cannot be referenced in C code.
  14817. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14818. CheckForZeroSize =
  14819. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14820. !CXXRecord->isDependentType() &&
  14821. CXXRecord->isCLike();
  14822. }
  14823. if (CheckForZeroSize) {
  14824. bool ZeroSize = true;
  14825. bool IsEmpty = true;
  14826. unsigned NonBitFields = 0;
  14827. for (RecordDecl::field_iterator I = Record->field_begin(),
  14828. E = Record->field_end();
  14829. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14830. IsEmpty = false;
  14831. if (I->isUnnamedBitfield()) {
  14832. if (!I->isZeroLengthBitField(Context))
  14833. ZeroSize = false;
  14834. } else {
  14835. ++NonBitFields;
  14836. QualType FieldType = I->getType();
  14837. if (FieldType->isIncompleteType() ||
  14838. !Context.getTypeSizeInChars(FieldType).isZero())
  14839. ZeroSize = false;
  14840. }
  14841. }
  14842. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14843. // allowed in C++, but warn if its declaration is inside
  14844. // extern "C" block.
  14845. if (ZeroSize) {
  14846. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14847. diag::warn_zero_size_struct_union_in_extern_c :
  14848. diag::warn_zero_size_struct_union_compat)
  14849. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14850. }
  14851. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14852. // but are accepted by GCC.
  14853. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14854. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14855. diag::ext_no_named_members_in_struct_union)
  14856. << Record->isUnion();
  14857. }
  14858. }
  14859. } else {
  14860. ObjCIvarDecl **ClsFields =
  14861. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14862. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14863. ID->setEndOfDefinitionLoc(RBrac);
  14864. // Add ivar's to class's DeclContext.
  14865. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14866. ClsFields[i]->setLexicalDeclContext(ID);
  14867. ID->addDecl(ClsFields[i]);
  14868. }
  14869. // Must enforce the rule that ivars in the base classes may not be
  14870. // duplicates.
  14871. if (ID->getSuperClass())
  14872. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14873. } else if (ObjCImplementationDecl *IMPDecl =
  14874. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14875. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14876. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14877. // Ivar declared in @implementation never belongs to the implementation.
  14878. // Only it is in implementation's lexical context.
  14879. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14880. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14881. IMPDecl->setIvarLBraceLoc(LBrac);
  14882. IMPDecl->setIvarRBraceLoc(RBrac);
  14883. } else if (ObjCCategoryDecl *CDecl =
  14884. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14885. // case of ivars in class extension; all other cases have been
  14886. // reported as errors elsewhere.
  14887. // FIXME. Class extension does not have a LocEnd field.
  14888. // CDecl->setLocEnd(RBrac);
  14889. // Add ivar's to class extension's DeclContext.
  14890. // Diagnose redeclaration of private ivars.
  14891. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14892. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14893. if (IDecl) {
  14894. if (const ObjCIvarDecl *ClsIvar =
  14895. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14896. Diag(ClsFields[i]->getLocation(),
  14897. diag::err_duplicate_ivar_declaration);
  14898. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14899. continue;
  14900. }
  14901. for (const auto *Ext : IDecl->known_extensions()) {
  14902. if (const ObjCIvarDecl *ClsExtIvar
  14903. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14904. Diag(ClsFields[i]->getLocation(),
  14905. diag::err_duplicate_ivar_declaration);
  14906. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14907. continue;
  14908. }
  14909. }
  14910. }
  14911. ClsFields[i]->setLexicalDeclContext(CDecl);
  14912. CDecl->addDecl(ClsFields[i]);
  14913. }
  14914. CDecl->setIvarLBraceLoc(LBrac);
  14915. CDecl->setIvarRBraceLoc(RBrac);
  14916. }
  14917. }
  14918. }
  14919. /// Determine whether the given integral value is representable within
  14920. /// the given type T.
  14921. static bool isRepresentableIntegerValue(ASTContext &Context,
  14922. llvm::APSInt &Value,
  14923. QualType T) {
  14924. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14925. "Integral type required!");
  14926. unsigned BitWidth = Context.getIntWidth(T);
  14927. if (Value.isUnsigned() || Value.isNonNegative()) {
  14928. if (T->isSignedIntegerOrEnumerationType())
  14929. --BitWidth;
  14930. return Value.getActiveBits() <= BitWidth;
  14931. }
  14932. return Value.getMinSignedBits() <= BitWidth;
  14933. }
  14934. // Given an integral type, return the next larger integral type
  14935. // (or a NULL type of no such type exists).
  14936. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14937. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14938. // enum checking below.
  14939. assert((T->isIntegralType(Context) ||
  14940. T->isEnumeralType()) && "Integral type required!");
  14941. const unsigned NumTypes = 4;
  14942. QualType SignedIntegralTypes[NumTypes] = {
  14943. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14944. };
  14945. QualType UnsignedIntegralTypes[NumTypes] = {
  14946. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14947. Context.UnsignedLongLongTy
  14948. };
  14949. unsigned BitWidth = Context.getTypeSize(T);
  14950. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14951. : UnsignedIntegralTypes;
  14952. for (unsigned I = 0; I != NumTypes; ++I)
  14953. if (Context.getTypeSize(Types[I]) > BitWidth)
  14954. return Types[I];
  14955. return QualType();
  14956. }
  14957. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14958. EnumConstantDecl *LastEnumConst,
  14959. SourceLocation IdLoc,
  14960. IdentifierInfo *Id,
  14961. Expr *Val) {
  14962. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14963. llvm::APSInt EnumVal(IntWidth);
  14964. QualType EltTy;
  14965. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14966. Val = nullptr;
  14967. if (Val)
  14968. Val = DefaultLvalueConversion(Val).get();
  14969. if (Val) {
  14970. if (Enum->isDependentType() || Val->isTypeDependent())
  14971. EltTy = Context.DependentTy;
  14972. else {
  14973. if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
  14974. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14975. // constant-expression in the enumerator-definition shall be a converted
  14976. // constant expression of the underlying type.
  14977. EltTy = Enum->getIntegerType();
  14978. ExprResult Converted =
  14979. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14980. CCEK_Enumerator);
  14981. if (Converted.isInvalid())
  14982. Val = nullptr;
  14983. else
  14984. Val = Converted.get();
  14985. } else if (!Val->isValueDependent() &&
  14986. !(Val = VerifyIntegerConstantExpression(Val,
  14987. &EnumVal).get())) {
  14988. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14989. } else {
  14990. if (Enum->isComplete()) {
  14991. EltTy = Enum->getIntegerType();
  14992. // In Obj-C and Microsoft mode, require the enumeration value to be
  14993. // representable in the underlying type of the enumeration. In C++11,
  14994. // we perform a non-narrowing conversion as part of converted constant
  14995. // expression checking.
  14996. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14997. if (Context.getTargetInfo()
  14998. .getTriple()
  14999. .isWindowsMSVCEnvironment()) {
  15000. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  15001. } else {
  15002. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  15003. }
  15004. }
  15005. // Cast to the underlying type.
  15006. Val = ImpCastExprToType(Val, EltTy,
  15007. EltTy->isBooleanType() ? CK_IntegralToBoolean
  15008. : CK_IntegralCast)
  15009. .get();
  15010. } else if (getLangOpts().CPlusPlus) {
  15011. // C++11 [dcl.enum]p5:
  15012. // If the underlying type is not fixed, the type of each enumerator
  15013. // is the type of its initializing value:
  15014. // - If an initializer is specified for an enumerator, the
  15015. // initializing value has the same type as the expression.
  15016. EltTy = Val->getType();
  15017. } else {
  15018. // C99 6.7.2.2p2:
  15019. // The expression that defines the value of an enumeration constant
  15020. // shall be an integer constant expression that has a value
  15021. // representable as an int.
  15022. // Complain if the value is not representable in an int.
  15023. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  15024. Diag(IdLoc, diag::ext_enum_value_not_int)
  15025. << EnumVal.toString(10) << Val->getSourceRange()
  15026. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  15027. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  15028. // Force the type of the expression to 'int'.
  15029. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  15030. }
  15031. EltTy = Val->getType();
  15032. }
  15033. }
  15034. }
  15035. }
  15036. if (!Val) {
  15037. if (Enum->isDependentType())
  15038. EltTy = Context.DependentTy;
  15039. else if (!LastEnumConst) {
  15040. // C++0x [dcl.enum]p5:
  15041. // If the underlying type is not fixed, the type of each enumerator
  15042. // is the type of its initializing value:
  15043. // - If no initializer is specified for the first enumerator, the
  15044. // initializing value has an unspecified integral type.
  15045. //
  15046. // GCC uses 'int' for its unspecified integral type, as does
  15047. // C99 6.7.2.2p3.
  15048. if (Enum->isFixed()) {
  15049. EltTy = Enum->getIntegerType();
  15050. }
  15051. else {
  15052. EltTy = Context.IntTy;
  15053. }
  15054. } else {
  15055. // Assign the last value + 1.
  15056. EnumVal = LastEnumConst->getInitVal();
  15057. ++EnumVal;
  15058. EltTy = LastEnumConst->getType();
  15059. // Check for overflow on increment.
  15060. if (EnumVal < LastEnumConst->getInitVal()) {
  15061. // C++0x [dcl.enum]p5:
  15062. // If the underlying type is not fixed, the type of each enumerator
  15063. // is the type of its initializing value:
  15064. //
  15065. // - Otherwise the type of the initializing value is the same as
  15066. // the type of the initializing value of the preceding enumerator
  15067. // unless the incremented value is not representable in that type,
  15068. // in which case the type is an unspecified integral type
  15069. // sufficient to contain the incremented value. If no such type
  15070. // exists, the program is ill-formed.
  15071. QualType T = getNextLargerIntegralType(Context, EltTy);
  15072. if (T.isNull() || Enum->isFixed()) {
  15073. // There is no integral type larger enough to represent this
  15074. // value. Complain, then allow the value to wrap around.
  15075. EnumVal = LastEnumConst->getInitVal();
  15076. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  15077. ++EnumVal;
  15078. if (Enum->isFixed())
  15079. // When the underlying type is fixed, this is ill-formed.
  15080. Diag(IdLoc, diag::err_enumerator_wrapped)
  15081. << EnumVal.toString(10)
  15082. << EltTy;
  15083. else
  15084. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  15085. << EnumVal.toString(10);
  15086. } else {
  15087. EltTy = T;
  15088. }
  15089. // Retrieve the last enumerator's value, extent that type to the
  15090. // type that is supposed to be large enough to represent the incremented
  15091. // value, then increment.
  15092. EnumVal = LastEnumConst->getInitVal();
  15093. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15094. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  15095. ++EnumVal;
  15096. // If we're not in C++, diagnose the overflow of enumerator values,
  15097. // which in C99 means that the enumerator value is not representable in
  15098. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  15099. // permits enumerator values that are representable in some larger
  15100. // integral type.
  15101. if (!getLangOpts().CPlusPlus && !T.isNull())
  15102. Diag(IdLoc, diag::warn_enum_value_overflow);
  15103. } else if (!getLangOpts().CPlusPlus &&
  15104. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  15105. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  15106. Diag(IdLoc, diag::ext_enum_value_not_int)
  15107. << EnumVal.toString(10) << 1;
  15108. }
  15109. }
  15110. }
  15111. if (!EltTy->isDependentType()) {
  15112. // Make the enumerator value match the signedness and size of the
  15113. // enumerator's type.
  15114. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  15115. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  15116. }
  15117. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  15118. Val, EnumVal);
  15119. }
  15120. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  15121. SourceLocation IILoc) {
  15122. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  15123. !getLangOpts().CPlusPlus)
  15124. return SkipBodyInfo();
  15125. // We have an anonymous enum definition. Look up the first enumerator to
  15126. // determine if we should merge the definition with an existing one and
  15127. // skip the body.
  15128. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  15129. forRedeclarationInCurContext());
  15130. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  15131. if (!PrevECD)
  15132. return SkipBodyInfo();
  15133. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  15134. NamedDecl *Hidden;
  15135. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  15136. SkipBodyInfo Skip;
  15137. Skip.Previous = Hidden;
  15138. return Skip;
  15139. }
  15140. return SkipBodyInfo();
  15141. }
  15142. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  15143. SourceLocation IdLoc, IdentifierInfo *Id,
  15144. const ParsedAttributesView &Attrs,
  15145. SourceLocation EqualLoc, Expr *Val) {
  15146. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  15147. EnumConstantDecl *LastEnumConst =
  15148. cast_or_null<EnumConstantDecl>(lastEnumConst);
  15149. // The scope passed in may not be a decl scope. Zip up the scope tree until
  15150. // we find one that is.
  15151. S = getNonFieldDeclScope(S);
  15152. // Verify that there isn't already something declared with this name in this
  15153. // scope.
  15154. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  15155. LookupName(R, S);
  15156. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  15157. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15158. // Maybe we will complain about the shadowed template parameter.
  15159. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  15160. // Just pretend that we didn't see the previous declaration.
  15161. PrevDecl = nullptr;
  15162. }
  15163. // C++ [class.mem]p15:
  15164. // If T is the name of a class, then each of the following shall have a name
  15165. // different from T:
  15166. // - every enumerator of every member of class T that is an unscoped
  15167. // enumerated type
  15168. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  15169. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  15170. DeclarationNameInfo(Id, IdLoc));
  15171. EnumConstantDecl *New =
  15172. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  15173. if (!New)
  15174. return nullptr;
  15175. if (PrevDecl) {
  15176. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  15177. // Check for other kinds of shadowing not already handled.
  15178. CheckShadow(New, PrevDecl, R);
  15179. }
  15180. // When in C++, we may get a TagDecl with the same name; in this case the
  15181. // enum constant will 'hide' the tag.
  15182. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  15183. "Received TagDecl when not in C++!");
  15184. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  15185. if (isa<EnumConstantDecl>(PrevDecl))
  15186. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  15187. else
  15188. Diag(IdLoc, diag::err_redefinition) << Id;
  15189. notePreviousDefinition(PrevDecl, IdLoc);
  15190. return nullptr;
  15191. }
  15192. }
  15193. // Process attributes.
  15194. ProcessDeclAttributeList(S, New, Attrs);
  15195. AddPragmaAttributes(S, New);
  15196. // Register this decl in the current scope stack.
  15197. New->setAccess(TheEnumDecl->getAccess());
  15198. PushOnScopeChains(New, S);
  15199. ActOnDocumentableDecl(New);
  15200. return New;
  15201. }
  15202. // Returns true when the enum initial expression does not trigger the
  15203. // duplicate enum warning. A few common cases are exempted as follows:
  15204. // Element2 = Element1
  15205. // Element2 = Element1 + 1
  15206. // Element2 = Element1 - 1
  15207. // Where Element2 and Element1 are from the same enum.
  15208. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  15209. Expr *InitExpr = ECD->getInitExpr();
  15210. if (!InitExpr)
  15211. return true;
  15212. InitExpr = InitExpr->IgnoreImpCasts();
  15213. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  15214. if (!BO->isAdditiveOp())
  15215. return true;
  15216. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  15217. if (!IL)
  15218. return true;
  15219. if (IL->getValue() != 1)
  15220. return true;
  15221. InitExpr = BO->getLHS();
  15222. }
  15223. // This checks if the elements are from the same enum.
  15224. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  15225. if (!DRE)
  15226. return true;
  15227. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  15228. if (!EnumConstant)
  15229. return true;
  15230. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  15231. Enum)
  15232. return true;
  15233. return false;
  15234. }
  15235. // Emits a warning when an element is implicitly set a value that
  15236. // a previous element has already been set to.
  15237. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  15238. EnumDecl *Enum, QualType EnumType) {
  15239. // Avoid anonymous enums
  15240. if (!Enum->getIdentifier())
  15241. return;
  15242. // Only check for small enums.
  15243. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  15244. return;
  15245. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  15246. return;
  15247. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  15248. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  15249. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  15250. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  15251. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  15252. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  15253. llvm::APSInt Val = D->getInitVal();
  15254. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  15255. };
  15256. DuplicatesVector DupVector;
  15257. ValueToVectorMap EnumMap;
  15258. // Populate the EnumMap with all values represented by enum constants without
  15259. // an initializer.
  15260. for (auto *Element : Elements) {
  15261. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  15262. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  15263. // this constant. Skip this enum since it may be ill-formed.
  15264. if (!ECD) {
  15265. return;
  15266. }
  15267. // Constants with initalizers are handled in the next loop.
  15268. if (ECD->getInitExpr())
  15269. continue;
  15270. // Duplicate values are handled in the next loop.
  15271. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  15272. }
  15273. if (EnumMap.size() == 0)
  15274. return;
  15275. // Create vectors for any values that has duplicates.
  15276. for (auto *Element : Elements) {
  15277. // The last loop returned if any constant was null.
  15278. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  15279. if (!ValidDuplicateEnum(ECD, Enum))
  15280. continue;
  15281. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  15282. if (Iter == EnumMap.end())
  15283. continue;
  15284. DeclOrVector& Entry = Iter->second;
  15285. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  15286. // Ensure constants are different.
  15287. if (D == ECD)
  15288. continue;
  15289. // Create new vector and push values onto it.
  15290. auto Vec = std::make_unique<ECDVector>();
  15291. Vec->push_back(D);
  15292. Vec->push_back(ECD);
  15293. // Update entry to point to the duplicates vector.
  15294. Entry = Vec.get();
  15295. // Store the vector somewhere we can consult later for quick emission of
  15296. // diagnostics.
  15297. DupVector.emplace_back(std::move(Vec));
  15298. continue;
  15299. }
  15300. ECDVector *Vec = Entry.get<ECDVector*>();
  15301. // Make sure constants are not added more than once.
  15302. if (*Vec->begin() == ECD)
  15303. continue;
  15304. Vec->push_back(ECD);
  15305. }
  15306. // Emit diagnostics.
  15307. for (const auto &Vec : DupVector) {
  15308. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  15309. // Emit warning for one enum constant.
  15310. auto *FirstECD = Vec->front();
  15311. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  15312. << FirstECD << FirstECD->getInitVal().toString(10)
  15313. << FirstECD->getSourceRange();
  15314. // Emit one note for each of the remaining enum constants with
  15315. // the same value.
  15316. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  15317. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  15318. << ECD << ECD->getInitVal().toString(10)
  15319. << ECD->getSourceRange();
  15320. }
  15321. }
  15322. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  15323. bool AllowMask) const {
  15324. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  15325. assert(ED->isCompleteDefinition() && "expected enum definition");
  15326. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  15327. llvm::APInt &FlagBits = R.first->second;
  15328. if (R.second) {
  15329. for (auto *E : ED->enumerators()) {
  15330. const auto &EVal = E->getInitVal();
  15331. // Only single-bit enumerators introduce new flag values.
  15332. if (EVal.isPowerOf2())
  15333. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  15334. }
  15335. }
  15336. // A value is in a flag enum if either its bits are a subset of the enum's
  15337. // flag bits (the first condition) or we are allowing masks and the same is
  15338. // true of its complement (the second condition). When masks are allowed, we
  15339. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  15340. //
  15341. // While it's true that any value could be used as a mask, the assumption is
  15342. // that a mask will have all of the insignificant bits set. Anything else is
  15343. // likely a logic error.
  15344. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  15345. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  15346. }
  15347. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  15348. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  15349. const ParsedAttributesView &Attrs) {
  15350. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  15351. QualType EnumType = Context.getTypeDeclType(Enum);
  15352. ProcessDeclAttributeList(S, Enum, Attrs);
  15353. if (Enum->isDependentType()) {
  15354. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15355. EnumConstantDecl *ECD =
  15356. cast_or_null<EnumConstantDecl>(Elements[i]);
  15357. if (!ECD) continue;
  15358. ECD->setType(EnumType);
  15359. }
  15360. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  15361. return;
  15362. }
  15363. // TODO: If the result value doesn't fit in an int, it must be a long or long
  15364. // long value. ISO C does not support this, but GCC does as an extension,
  15365. // emit a warning.
  15366. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15367. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  15368. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  15369. // Verify that all the values are okay, compute the size of the values, and
  15370. // reverse the list.
  15371. unsigned NumNegativeBits = 0;
  15372. unsigned NumPositiveBits = 0;
  15373. // Keep track of whether all elements have type int.
  15374. bool AllElementsInt = true;
  15375. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  15376. EnumConstantDecl *ECD =
  15377. cast_or_null<EnumConstantDecl>(Elements[i]);
  15378. if (!ECD) continue; // Already issued a diagnostic.
  15379. const llvm::APSInt &InitVal = ECD->getInitVal();
  15380. // Keep track of the size of positive and negative values.
  15381. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  15382. NumPositiveBits = std::max(NumPositiveBits,
  15383. (unsigned)InitVal.getActiveBits());
  15384. else
  15385. NumNegativeBits = std::max(NumNegativeBits,
  15386. (unsigned)InitVal.getMinSignedBits());
  15387. // Keep track of whether every enum element has type int (very common).
  15388. if (AllElementsInt)
  15389. AllElementsInt = ECD->getType() == Context.IntTy;
  15390. }
  15391. // Figure out the type that should be used for this enum.
  15392. QualType BestType;
  15393. unsigned BestWidth;
  15394. // C++0x N3000 [conv.prom]p3:
  15395. // An rvalue of an unscoped enumeration type whose underlying
  15396. // type is not fixed can be converted to an rvalue of the first
  15397. // of the following types that can represent all the values of
  15398. // the enumeration: int, unsigned int, long int, unsigned long
  15399. // int, long long int, or unsigned long long int.
  15400. // C99 6.4.4.3p2:
  15401. // An identifier declared as an enumeration constant has type int.
  15402. // The C99 rule is modified by a gcc extension
  15403. QualType BestPromotionType;
  15404. bool Packed = Enum->hasAttr<PackedAttr>();
  15405. // -fshort-enums is the equivalent to specifying the packed attribute on all
  15406. // enum definitions.
  15407. if (LangOpts.ShortEnums)
  15408. Packed = true;
  15409. // If the enum already has a type because it is fixed or dictated by the
  15410. // target, promote that type instead of analyzing the enumerators.
  15411. if (Enum->isComplete()) {
  15412. BestType = Enum->getIntegerType();
  15413. if (BestType->isPromotableIntegerType())
  15414. BestPromotionType = Context.getPromotedIntegerType(BestType);
  15415. else
  15416. BestPromotionType = BestType;
  15417. BestWidth = Context.getIntWidth(BestType);
  15418. }
  15419. else if (NumNegativeBits) {
  15420. // If there is a negative value, figure out the smallest integer type (of
  15421. // int/long/longlong) that fits.
  15422. // If it's packed, check also if it fits a char or a short.
  15423. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  15424. BestType = Context.SignedCharTy;
  15425. BestWidth = CharWidth;
  15426. } else if (Packed && NumNegativeBits <= ShortWidth &&
  15427. NumPositiveBits < ShortWidth) {
  15428. BestType = Context.ShortTy;
  15429. BestWidth = ShortWidth;
  15430. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  15431. BestType = Context.IntTy;
  15432. BestWidth = IntWidth;
  15433. } else {
  15434. BestWidth = Context.getTargetInfo().getLongWidth();
  15435. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  15436. BestType = Context.LongTy;
  15437. } else {
  15438. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15439. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  15440. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  15441. BestType = Context.LongLongTy;
  15442. }
  15443. }
  15444. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  15445. } else {
  15446. // If there is no negative value, figure out the smallest type that fits
  15447. // all of the enumerator values.
  15448. // If it's packed, check also if it fits a char or a short.
  15449. if (Packed && NumPositiveBits <= CharWidth) {
  15450. BestType = Context.UnsignedCharTy;
  15451. BestPromotionType = Context.IntTy;
  15452. BestWidth = CharWidth;
  15453. } else if (Packed && NumPositiveBits <= ShortWidth) {
  15454. BestType = Context.UnsignedShortTy;
  15455. BestPromotionType = Context.IntTy;
  15456. BestWidth = ShortWidth;
  15457. } else if (NumPositiveBits <= IntWidth) {
  15458. BestType = Context.UnsignedIntTy;
  15459. BestWidth = IntWidth;
  15460. BestPromotionType
  15461. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15462. ? Context.UnsignedIntTy : Context.IntTy;
  15463. } else if (NumPositiveBits <=
  15464. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  15465. BestType = Context.UnsignedLongTy;
  15466. BestPromotionType
  15467. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15468. ? Context.UnsignedLongTy : Context.LongTy;
  15469. } else {
  15470. BestWidth = Context.getTargetInfo().getLongLongWidth();
  15471. assert(NumPositiveBits <= BestWidth &&
  15472. "How could an initializer get larger than ULL?");
  15473. BestType = Context.UnsignedLongLongTy;
  15474. BestPromotionType
  15475. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  15476. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  15477. }
  15478. }
  15479. // Loop over all of the enumerator constants, changing their types to match
  15480. // the type of the enum if needed.
  15481. for (auto *D : Elements) {
  15482. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  15483. if (!ECD) continue; // Already issued a diagnostic.
  15484. // Standard C says the enumerators have int type, but we allow, as an
  15485. // extension, the enumerators to be larger than int size. If each
  15486. // enumerator value fits in an int, type it as an int, otherwise type it the
  15487. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  15488. // that X has type 'int', not 'unsigned'.
  15489. // Determine whether the value fits into an int.
  15490. llvm::APSInt InitVal = ECD->getInitVal();
  15491. // If it fits into an integer type, force it. Otherwise force it to match
  15492. // the enum decl type.
  15493. QualType NewTy;
  15494. unsigned NewWidth;
  15495. bool NewSign;
  15496. if (!getLangOpts().CPlusPlus &&
  15497. !Enum->isFixed() &&
  15498. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  15499. NewTy = Context.IntTy;
  15500. NewWidth = IntWidth;
  15501. NewSign = true;
  15502. } else if (ECD->getType() == BestType) {
  15503. // Already the right type!
  15504. if (getLangOpts().CPlusPlus)
  15505. // C++ [dcl.enum]p4: Following the closing brace of an
  15506. // enum-specifier, each enumerator has the type of its
  15507. // enumeration.
  15508. ECD->setType(EnumType);
  15509. continue;
  15510. } else {
  15511. NewTy = BestType;
  15512. NewWidth = BestWidth;
  15513. NewSign = BestType->isSignedIntegerOrEnumerationType();
  15514. }
  15515. // Adjust the APSInt value.
  15516. InitVal = InitVal.extOrTrunc(NewWidth);
  15517. InitVal.setIsSigned(NewSign);
  15518. ECD->setInitVal(InitVal);
  15519. // Adjust the Expr initializer and type.
  15520. if (ECD->getInitExpr() &&
  15521. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  15522. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  15523. CK_IntegralCast,
  15524. ECD->getInitExpr(),
  15525. /*base paths*/ nullptr,
  15526. VK_RValue));
  15527. if (getLangOpts().CPlusPlus)
  15528. // C++ [dcl.enum]p4: Following the closing brace of an
  15529. // enum-specifier, each enumerator has the type of its
  15530. // enumeration.
  15531. ECD->setType(EnumType);
  15532. else
  15533. ECD->setType(NewTy);
  15534. }
  15535. Enum->completeDefinition(BestType, BestPromotionType,
  15536. NumPositiveBits, NumNegativeBits);
  15537. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  15538. if (Enum->isClosedFlag()) {
  15539. for (Decl *D : Elements) {
  15540. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  15541. if (!ECD) continue; // Already issued a diagnostic.
  15542. llvm::APSInt InitVal = ECD->getInitVal();
  15543. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  15544. !IsValueInFlagEnum(Enum, InitVal, true))
  15545. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  15546. << ECD << Enum;
  15547. }
  15548. }
  15549. // Now that the enum type is defined, ensure it's not been underaligned.
  15550. if (Enum->hasAttrs())
  15551. CheckAlignasUnderalignment(Enum);
  15552. }
  15553. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  15554. SourceLocation StartLoc,
  15555. SourceLocation EndLoc) {
  15556. StringLiteral *AsmString = cast<StringLiteral>(expr);
  15557. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  15558. AsmString, StartLoc,
  15559. EndLoc);
  15560. CurContext->addDecl(New);
  15561. return New;
  15562. }
  15563. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15564. IdentifierInfo* AliasName,
  15565. SourceLocation PragmaLoc,
  15566. SourceLocation NameLoc,
  15567. SourceLocation AliasNameLoc) {
  15568. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15569. LookupOrdinaryName);
  15570. AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
  15571. AttributeCommonInfo::AS_Pragma);
  15572. AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
  15573. Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
  15574. // If a declaration that:
  15575. // 1) declares a function or a variable
  15576. // 2) has external linkage
  15577. // already exists, add a label attribute to it.
  15578. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15579. if (isDeclExternC(PrevDecl))
  15580. PrevDecl->addAttr(Attr);
  15581. else
  15582. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15583. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15584. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15585. } else
  15586. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15587. }
  15588. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15589. SourceLocation PragmaLoc,
  15590. SourceLocation NameLoc) {
  15591. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15592. if (PrevDecl) {
  15593. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
  15594. } else {
  15595. (void)WeakUndeclaredIdentifiers.insert(
  15596. std::pair<IdentifierInfo*,WeakInfo>
  15597. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15598. }
  15599. }
  15600. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15601. IdentifierInfo* AliasName,
  15602. SourceLocation PragmaLoc,
  15603. SourceLocation NameLoc,
  15604. SourceLocation AliasNameLoc) {
  15605. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15606. LookupOrdinaryName);
  15607. WeakInfo W = WeakInfo(Name, NameLoc);
  15608. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15609. if (!PrevDecl->hasAttr<AliasAttr>())
  15610. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15611. DeclApplyPragmaWeak(TUScope, ND, W);
  15612. } else {
  15613. (void)WeakUndeclaredIdentifiers.insert(
  15614. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15615. }
  15616. }
  15617. Decl *Sema::getObjCDeclContext() const {
  15618. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15619. }
  15620. Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) {
  15621. // Templates are emitted when they're instantiated.
  15622. if (FD->isDependentContext())
  15623. return FunctionEmissionStatus::TemplateDiscarded;
  15624. FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
  15625. if (LangOpts.OpenMPIsDevice) {
  15626. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15627. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  15628. if (DevTy.hasValue()) {
  15629. if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  15630. OMPES = FunctionEmissionStatus::OMPDiscarded;
  15631. else if (DeviceKnownEmittedFns.count(FD) > 0)
  15632. OMPES = FunctionEmissionStatus::Emitted;
  15633. }
  15634. } else if (LangOpts.OpenMP) {
  15635. // In OpenMP 4.5 all the functions are host functions.
  15636. if (LangOpts.OpenMP <= 45) {
  15637. OMPES = FunctionEmissionStatus::Emitted;
  15638. } else {
  15639. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  15640. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  15641. // In OpenMP 5.0 or above, DevTy may be changed later by
  15642. // #pragma omp declare target to(*) device_type(*). Therefore DevTy
  15643. // having no value does not imply host. The emission status will be
  15644. // checked again at the end of compilation unit.
  15645. if (DevTy.hasValue()) {
  15646. if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
  15647. OMPES = FunctionEmissionStatus::OMPDiscarded;
  15648. } else if (DeviceKnownEmittedFns.count(FD) > 0) {
  15649. OMPES = FunctionEmissionStatus::Emitted;
  15650. }
  15651. }
  15652. }
  15653. }
  15654. if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
  15655. (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
  15656. return OMPES;
  15657. if (LangOpts.CUDA) {
  15658. // When compiling for device, host functions are never emitted. Similarly,
  15659. // when compiling for host, device and global functions are never emitted.
  15660. // (Technically, we do emit a host-side stub for global functions, but this
  15661. // doesn't count for our purposes here.)
  15662. Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
  15663. if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
  15664. return FunctionEmissionStatus::CUDADiscarded;
  15665. if (!LangOpts.CUDAIsDevice &&
  15666. (T == Sema::CFT_Device || T == Sema::CFT_Global))
  15667. return FunctionEmissionStatus::CUDADiscarded;
  15668. // Check whether this function is externally visible -- if so, it's
  15669. // known-emitted.
  15670. //
  15671. // We have to check the GVA linkage of the function's *definition* -- if we
  15672. // only have a declaration, we don't know whether or not the function will
  15673. // be emitted, because (say) the definition could include "inline".
  15674. FunctionDecl *Def = FD->getDefinition();
  15675. if (Def &&
  15676. !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
  15677. && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
  15678. return FunctionEmissionStatus::Emitted;
  15679. }
  15680. // Otherwise, the function is known-emitted if it's in our set of
  15681. // known-emitted functions.
  15682. return (DeviceKnownEmittedFns.count(FD) > 0)
  15683. ? FunctionEmissionStatus::Emitted
  15684. : FunctionEmissionStatus::Unknown;
  15685. }
  15686. bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
  15687. // Host-side references to a __global__ function refer to the stub, so the
  15688. // function itself is never emitted and therefore should not be marked.
  15689. // If we have host fn calls kernel fn calls host+device, the HD function
  15690. // does not get instantiated on the host. We model this by omitting at the
  15691. // call to the kernel from the callgraph. This ensures that, when compiling
  15692. // for host, only HD functions actually called from the host get marked as
  15693. // known-emitted.
  15694. return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  15695. IdentifyCUDATarget(Callee) == CFT_Global;
  15696. }