SemaDecl.cpp 732 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809
  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/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/NonTrivialTypeVisitor.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/Basic/Builtins.h"
  28. #include "clang/Basic/PartialDiagnostic.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  33. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  35. #include "clang/Sema/CXXFieldCollector.h"
  36. #include "clang/Sema/DeclSpec.h"
  37. #include "clang/Sema/DelayedDiagnostic.h"
  38. #include "clang/Sema/Initialization.h"
  39. #include "clang/Sema/Lookup.h"
  40. #include "clang/Sema/ParsedTemplate.h"
  41. #include "clang/Sema/Scope.h"
  42. #include "clang/Sema/ScopeInfo.h"
  43. #include "clang/Sema/SemaInternal.h"
  44. #include "clang/Sema/Template.h"
  45. #include "llvm/ADT/SmallString.h"
  46. #include "llvm/ADT/Triple.h"
  47. #include <algorithm>
  48. #include <cstring>
  49. #include <functional>
  50. #include <unordered_map>
  51. using namespace clang;
  52. using namespace sema;
  53. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  54. if (OwnedType) {
  55. Decl *Group[2] = { OwnedType, Ptr };
  56. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  57. }
  58. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  59. }
  60. namespace {
  61. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  62. public:
  63. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  64. bool AllowTemplates = false,
  65. bool AllowNonTemplates = true)
  66. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  67. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  68. WantExpressionKeywords = false;
  69. WantCXXNamedCasts = false;
  70. WantRemainingKeywords = false;
  71. }
  72. bool ValidateCandidate(const TypoCorrection &candidate) override {
  73. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  74. if (!AllowInvalidDecl && ND->isInvalidDecl())
  75. return false;
  76. if (getAsTypeTemplateDecl(ND))
  77. return AllowTemplates;
  78. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  79. if (!IsType)
  80. return false;
  81. if (AllowNonTemplates)
  82. return true;
  83. // An injected-class-name of a class template (specialization) is valid
  84. // as a template or as a non-template.
  85. if (AllowTemplates) {
  86. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  87. if (!RD || !RD->isInjectedClassName())
  88. return false;
  89. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  90. return RD->getDescribedClassTemplate() ||
  91. isa<ClassTemplateSpecializationDecl>(RD);
  92. }
  93. return false;
  94. }
  95. return !WantClassName && candidate.isKeyword();
  96. }
  97. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  98. return std::make_unique<TypeNameValidatorCCC>(*this);
  99. }
  100. private:
  101. bool AllowInvalidDecl;
  102. bool WantClassName;
  103. bool AllowTemplates;
  104. bool AllowNonTemplates;
  105. };
  106. } // end anonymous namespace
  107. /// Determine whether the token kind starts a simple-type-specifier.
  108. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  109. switch (Kind) {
  110. // FIXME: Take into account the current language when deciding whether a
  111. // token kind is a valid type specifier
  112. case tok::kw_short:
  113. case tok::kw_long:
  114. case tok::kw___int64:
  115. case tok::kw___int128:
  116. case tok::kw_signed:
  117. case tok::kw_unsigned:
  118. case tok::kw_void:
  119. case tok::kw_char:
  120. case tok::kw_int:
  121. case tok::kw_half:
  122. case tok::kw_float:
  123. case tok::kw_double:
  124. case tok::kw___bf16:
  125. case tok::kw__Float16:
  126. case tok::kw___float128:
  127. case tok::kw___ibm128:
  128. case tok::kw_wchar_t:
  129. case tok::kw_bool:
  130. case tok::kw___underlying_type:
  131. case tok::kw___auto_type:
  132. return true;
  133. case tok::annot_typename:
  134. case tok::kw_char16_t:
  135. case tok::kw_char32_t:
  136. case tok::kw_typeof:
  137. case tok::annot_decltype:
  138. case tok::kw_decltype:
  139. return getLangOpts().CPlusPlus;
  140. case tok::kw_char8_t:
  141. return getLangOpts().Char8;
  142. default:
  143. break;
  144. }
  145. return false;
  146. }
  147. namespace {
  148. enum class UnqualifiedTypeNameLookupResult {
  149. NotFound,
  150. FoundNonType,
  151. FoundType
  152. };
  153. } // end anonymous namespace
  154. /// Tries to perform unqualified lookup of the type decls in bases for
  155. /// dependent class.
  156. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  157. /// type decl, \a FoundType if only type decls are found.
  158. static UnqualifiedTypeNameLookupResult
  159. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  160. SourceLocation NameLoc,
  161. const CXXRecordDecl *RD) {
  162. if (!RD->hasDefinition())
  163. return UnqualifiedTypeNameLookupResult::NotFound;
  164. // Look for type decls in base classes.
  165. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  166. UnqualifiedTypeNameLookupResult::NotFound;
  167. for (const auto &Base : RD->bases()) {
  168. const CXXRecordDecl *BaseRD = nullptr;
  169. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  170. BaseRD = BaseTT->getAsCXXRecordDecl();
  171. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  172. // Look for type decls in dependent base classes that have known primary
  173. // templates.
  174. if (!TST || !TST->isDependentType())
  175. continue;
  176. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  177. if (!TD)
  178. continue;
  179. if (auto *BasePrimaryTemplate =
  180. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  181. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  182. BaseRD = BasePrimaryTemplate;
  183. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  184. if (const ClassTemplatePartialSpecializationDecl *PS =
  185. CTD->findPartialSpecialization(Base.getType()))
  186. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  187. BaseRD = PS;
  188. }
  189. }
  190. }
  191. if (BaseRD) {
  192. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  193. if (!isa<TypeDecl>(ND))
  194. return UnqualifiedTypeNameLookupResult::FoundNonType;
  195. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  196. }
  197. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  198. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  199. case UnqualifiedTypeNameLookupResult::FoundNonType:
  200. return UnqualifiedTypeNameLookupResult::FoundNonType;
  201. case UnqualifiedTypeNameLookupResult::FoundType:
  202. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  203. break;
  204. case UnqualifiedTypeNameLookupResult::NotFound:
  205. break;
  206. }
  207. }
  208. }
  209. }
  210. return FoundTypeDecl;
  211. }
  212. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  213. const IdentifierInfo &II,
  214. SourceLocation NameLoc) {
  215. // Lookup in the parent class template context, if any.
  216. const CXXRecordDecl *RD = nullptr;
  217. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  218. UnqualifiedTypeNameLookupResult::NotFound;
  219. for (DeclContext *DC = S.CurContext;
  220. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  221. DC = DC->getParent()) {
  222. // Look for type decls in dependent base classes that have known primary
  223. // templates.
  224. RD = dyn_cast<CXXRecordDecl>(DC);
  225. if (RD && RD->getDescribedClassTemplate())
  226. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  227. }
  228. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  229. return nullptr;
  230. // We found some types in dependent base classes. Recover as if the user
  231. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  232. // lookup during template instantiation.
  233. S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
  234. ASTContext &Context = S.Context;
  235. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  236. cast<Type>(Context.getRecordType(RD)));
  237. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  238. CXXScopeSpec SS;
  239. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  240. TypeLocBuilder Builder;
  241. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  242. DepTL.setNameLoc(NameLoc);
  243. DepTL.setElaboratedKeywordLoc(SourceLocation());
  244. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  245. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  246. }
  247. /// If the identifier refers to a type name within this scope,
  248. /// return the declaration of that type.
  249. ///
  250. /// This routine performs ordinary name lookup of the identifier II
  251. /// within the given scope, with optional C++ scope specifier SS, to
  252. /// determine whether the name refers to a type. If so, returns an
  253. /// opaque pointer (actually a QualType) corresponding to that
  254. /// type. Otherwise, returns NULL.
  255. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  256. Scope *S, CXXScopeSpec *SS,
  257. bool isClassName, bool HasTrailingDot,
  258. ParsedType ObjectTypePtr,
  259. bool IsCtorOrDtorName,
  260. bool WantNontrivialTypeSourceInfo,
  261. bool IsClassTemplateDeductionContext,
  262. IdentifierInfo **CorrectedII) {
  263. // FIXME: Consider allowing this outside C++1z mode as an extension.
  264. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  265. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  266. !isClassName && !HasTrailingDot;
  267. // Determine where we will perform name lookup.
  268. DeclContext *LookupCtx = nullptr;
  269. if (ObjectTypePtr) {
  270. QualType ObjectType = ObjectTypePtr.get();
  271. if (ObjectType->isRecordType())
  272. LookupCtx = computeDeclContext(ObjectType);
  273. } else if (SS && SS->isNotEmpty()) {
  274. LookupCtx = computeDeclContext(*SS, false);
  275. if (!LookupCtx) {
  276. if (isDependentScopeSpecifier(*SS)) {
  277. // C++ [temp.res]p3:
  278. // A qualified-id that refers to a type and in which the
  279. // nested-name-specifier depends on a template-parameter (14.6.2)
  280. // shall be prefixed by the keyword typename to indicate that the
  281. // qualified-id denotes a type, forming an
  282. // elaborated-type-specifier (7.1.5.3).
  283. //
  284. // We therefore do not perform any name lookup if the result would
  285. // refer to a member of an unknown specialization.
  286. if (!isClassName && !IsCtorOrDtorName)
  287. return nullptr;
  288. // We know from the grammar that this name refers to a type,
  289. // so build a dependent node to describe the type.
  290. if (WantNontrivialTypeSourceInfo)
  291. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  292. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  293. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  294. II, NameLoc);
  295. return ParsedType::make(T);
  296. }
  297. return nullptr;
  298. }
  299. if (!LookupCtx->isDependentContext() &&
  300. RequireCompleteDeclContext(*SS, LookupCtx))
  301. return nullptr;
  302. }
  303. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  304. // lookup for class-names.
  305. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  306. LookupOrdinaryName;
  307. LookupResult Result(*this, &II, NameLoc, Kind);
  308. if (LookupCtx) {
  309. // Perform "qualified" name lookup into the declaration context we
  310. // computed, which is either the type of the base of a member access
  311. // expression or the declaration context associated with a prior
  312. // nested-name-specifier.
  313. LookupQualifiedName(Result, LookupCtx);
  314. if (ObjectTypePtr && Result.empty()) {
  315. // C++ [basic.lookup.classref]p3:
  316. // If the unqualified-id is ~type-name, the type-name is looked up
  317. // in the context of the entire postfix-expression. If the type T of
  318. // the object expression is of a class type C, the type-name is also
  319. // looked up in the scope of class C. At least one of the lookups shall
  320. // find a name that refers to (possibly cv-qualified) T.
  321. LookupName(Result, S);
  322. }
  323. } else {
  324. // Perform unqualified name lookup.
  325. LookupName(Result, S);
  326. // For unqualified lookup in a class template in MSVC mode, look into
  327. // dependent base classes where the primary class template is known.
  328. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  329. if (ParsedType TypeInBase =
  330. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  331. return TypeInBase;
  332. }
  333. }
  334. NamedDecl *IIDecl = nullptr;
  335. UsingShadowDecl *FoundUsingShadow = nullptr;
  336. switch (Result.getResultKind()) {
  337. case LookupResult::NotFound:
  338. case LookupResult::NotFoundInCurrentInstantiation:
  339. if (CorrectedII) {
  340. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  341. AllowDeducedTemplate);
  342. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  343. S, SS, CCC, CTK_ErrorRecovery);
  344. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  345. TemplateTy Template;
  346. bool MemberOfUnknownSpecialization;
  347. UnqualifiedId TemplateName;
  348. TemplateName.setIdentifier(NewII, NameLoc);
  349. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  350. CXXScopeSpec NewSS, *NewSSPtr = SS;
  351. if (SS && NNS) {
  352. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  353. NewSSPtr = &NewSS;
  354. }
  355. if (Correction && (NNS || NewII != &II) &&
  356. // Ignore a correction to a template type as the to-be-corrected
  357. // identifier is not a template (typo correction for template names
  358. // is handled elsewhere).
  359. !(getLangOpts().CPlusPlus && NewSSPtr &&
  360. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  361. Template, MemberOfUnknownSpecialization))) {
  362. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  363. isClassName, HasTrailingDot, ObjectTypePtr,
  364. IsCtorOrDtorName,
  365. WantNontrivialTypeSourceInfo,
  366. IsClassTemplateDeductionContext);
  367. if (Ty) {
  368. diagnoseTypo(Correction,
  369. PDiag(diag::err_unknown_type_or_class_name_suggest)
  370. << Result.getLookupName() << isClassName);
  371. if (SS && NNS)
  372. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  373. *CorrectedII = NewII;
  374. return Ty;
  375. }
  376. }
  377. }
  378. // If typo correction failed or was not performed, fall through
  379. LLVM_FALLTHROUGH;
  380. case LookupResult::FoundOverloaded:
  381. case LookupResult::FoundUnresolvedValue:
  382. Result.suppressDiagnostics();
  383. return nullptr;
  384. case LookupResult::Ambiguous:
  385. // Recover from type-hiding ambiguities by hiding the type. We'll
  386. // do the lookup again when looking for an object, and we can
  387. // diagnose the error then. If we don't do this, then the error
  388. // about hiding the type will be immediately followed by an error
  389. // that only makes sense if the identifier was treated like a type.
  390. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  391. Result.suppressDiagnostics();
  392. return nullptr;
  393. }
  394. // Look to see if we have a type anywhere in the list of results.
  395. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  396. Res != ResEnd; ++Res) {
  397. NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
  398. if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
  399. RealRes) ||
  400. (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
  401. if (!IIDecl ||
  402. // Make the selection of the recovery decl deterministic.
  403. RealRes->getLocation() < IIDecl->getLocation()) {
  404. IIDecl = RealRes;
  405. FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
  406. }
  407. }
  408. }
  409. if (!IIDecl) {
  410. // None of the entities we found is a type, so there is no way
  411. // to even assume that the result is a type. In this case, don't
  412. // complain about the ambiguity. The parser will either try to
  413. // perform this lookup again (e.g., as an object name), which
  414. // will produce the ambiguity, or will complain that it expected
  415. // a type name.
  416. Result.suppressDiagnostics();
  417. return nullptr;
  418. }
  419. // We found a type within the ambiguous lookup; diagnose the
  420. // ambiguity and then return that type. This might be the right
  421. // answer, or it might not be, but it suppresses any attempt to
  422. // perform the name lookup again.
  423. break;
  424. case LookupResult::Found:
  425. IIDecl = Result.getFoundDecl();
  426. FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
  427. break;
  428. }
  429. assert(IIDecl && "Didn't find decl");
  430. QualType T;
  431. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  432. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  433. // instead names the constructors of the class, except when naming a class.
  434. // This is ill-formed when we're not actually forming a ctor or dtor name.
  435. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  436. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  437. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  438. FoundRD->isInjectedClassName() &&
  439. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  440. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  441. << &II << /*Type*/1;
  442. DiagnoseUseOfDecl(IIDecl, NameLoc);
  443. T = Context.getTypeDeclType(TD);
  444. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  445. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  446. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  447. if (!HasTrailingDot)
  448. T = Context.getObjCInterfaceType(IDecl);
  449. FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
  450. } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
  451. (void)DiagnoseUseOfDecl(UD, NameLoc);
  452. // Recover with 'int'
  453. T = Context.IntTy;
  454. FoundUsingShadow = nullptr;
  455. } else if (AllowDeducedTemplate) {
  456. if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
  457. // FIXME: TemplateName should include FoundUsingShadow sugar.
  458. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  459. QualType(), false);
  460. // Don't wrap in a further UsingType.
  461. FoundUsingShadow = nullptr;
  462. }
  463. }
  464. if (T.isNull()) {
  465. // If it's not plausibly a type, suppress diagnostics.
  466. Result.suppressDiagnostics();
  467. return nullptr;
  468. }
  469. if (FoundUsingShadow)
  470. T = Context.getUsingType(FoundUsingShadow, T);
  471. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  472. // constructor or destructor name (in such a case, the scope specifier
  473. // will be attached to the enclosing Expr or Decl node).
  474. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  475. !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
  476. if (WantNontrivialTypeSourceInfo) {
  477. // Construct a type with type-source information.
  478. TypeLocBuilder Builder;
  479. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  480. T = getElaboratedType(ETK_None, *SS, T);
  481. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  482. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  483. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  484. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  485. } else {
  486. T = getElaboratedType(ETK_None, *SS, T);
  487. }
  488. }
  489. return ParsedType::make(T);
  490. }
  491. // Builds a fake NNS for the given decl context.
  492. static NestedNameSpecifier *
  493. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  494. for (;; DC = DC->getLookupParent()) {
  495. DC = DC->getPrimaryContext();
  496. auto *ND = dyn_cast<NamespaceDecl>(DC);
  497. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  498. return NestedNameSpecifier::Create(Context, nullptr, ND);
  499. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  500. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  501. RD->getTypeForDecl());
  502. else if (isa<TranslationUnitDecl>(DC))
  503. return NestedNameSpecifier::GlobalSpecifier(Context);
  504. }
  505. llvm_unreachable("something isn't in TU scope?");
  506. }
  507. /// Find the parent class with dependent bases of the innermost enclosing method
  508. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  509. /// up allowing unqualified dependent type names at class-level, which MSVC
  510. /// correctly rejects.
  511. static const CXXRecordDecl *
  512. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  513. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  514. DC = DC->getPrimaryContext();
  515. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  516. if (MD->getParent()->hasAnyDependentBases())
  517. return MD->getParent();
  518. }
  519. return nullptr;
  520. }
  521. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  522. SourceLocation NameLoc,
  523. bool IsTemplateTypeArg) {
  524. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  525. NestedNameSpecifier *NNS = nullptr;
  526. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  527. // If we weren't able to parse a default template argument, delay lookup
  528. // until instantiation time by making a non-dependent DependentTypeName. We
  529. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  530. // lookup is retried.
  531. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  532. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  533. // name specifiers.
  534. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  535. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  536. } else if (const CXXRecordDecl *RD =
  537. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  538. // Build a DependentNameType that will perform lookup into RD at
  539. // instantiation time.
  540. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  541. RD->getTypeForDecl());
  542. // Diagnose that this identifier was undeclared, and retry the lookup during
  543. // template instantiation.
  544. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  545. << RD;
  546. } else {
  547. // This is not a situation that we should recover from.
  548. return ParsedType();
  549. }
  550. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  551. // Build type location information. We synthesized the qualifier, so we have
  552. // to build a fake NestedNameSpecifierLoc.
  553. NestedNameSpecifierLocBuilder NNSLocBuilder;
  554. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  555. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  556. TypeLocBuilder Builder;
  557. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  558. DepTL.setNameLoc(NameLoc);
  559. DepTL.setElaboratedKeywordLoc(SourceLocation());
  560. DepTL.setQualifierLoc(QualifierLoc);
  561. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  562. }
  563. /// isTagName() - This method is called *for error recovery purposes only*
  564. /// to determine if the specified name is a valid tag name ("struct foo"). If
  565. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  566. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  567. /// cases in C where the user forgot to specify the tag.
  568. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  569. // Do a tag name lookup in this scope.
  570. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  571. LookupName(R, S, false);
  572. R.suppressDiagnostics();
  573. if (R.getResultKind() == LookupResult::Found)
  574. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  575. switch (TD->getTagKind()) {
  576. case TTK_Struct: return DeclSpec::TST_struct;
  577. case TTK_Interface: return DeclSpec::TST_interface;
  578. case TTK_Union: return DeclSpec::TST_union;
  579. case TTK_Class: return DeclSpec::TST_class;
  580. case TTK_Enum: return DeclSpec::TST_enum;
  581. }
  582. }
  583. return DeclSpec::TST_unspecified;
  584. }
  585. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  586. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  587. /// then downgrade the missing typename error to a warning.
  588. /// This is needed for MSVC compatibility; Example:
  589. /// @code
  590. /// template<class T> class A {
  591. /// public:
  592. /// typedef int TYPE;
  593. /// };
  594. /// template<class T> class B : public A<T> {
  595. /// public:
  596. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  597. /// };
  598. /// @endcode
  599. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  600. if (CurContext->isRecord()) {
  601. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  602. return true;
  603. const Type *Ty = SS->getScopeRep()->getAsType();
  604. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  605. for (const auto &Base : RD->bases())
  606. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  607. return true;
  608. return S->isFunctionPrototypeScope();
  609. }
  610. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  611. }
  612. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  613. SourceLocation IILoc,
  614. Scope *S,
  615. CXXScopeSpec *SS,
  616. ParsedType &SuggestedType,
  617. bool IsTemplateName) {
  618. // Don't report typename errors for editor placeholders.
  619. if (II->isEditorPlaceholder())
  620. return;
  621. // We don't have anything to suggest (yet).
  622. SuggestedType = nullptr;
  623. // There may have been a typo in the name of the type. Look up typo
  624. // results, in case we have something that we can suggest.
  625. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  626. /*AllowTemplates=*/IsTemplateName,
  627. /*AllowNonTemplates=*/!IsTemplateName);
  628. if (TypoCorrection Corrected =
  629. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  630. CCC, CTK_ErrorRecovery)) {
  631. // FIXME: Support error recovery for the template-name case.
  632. bool CanRecover = !IsTemplateName;
  633. if (Corrected.isKeyword()) {
  634. // We corrected to a keyword.
  635. diagnoseTypo(Corrected,
  636. PDiag(IsTemplateName ? diag::err_no_template_suggest
  637. : diag::err_unknown_typename_suggest)
  638. << II);
  639. II = Corrected.getCorrectionAsIdentifierInfo();
  640. } else {
  641. // We found a similarly-named type or interface; suggest that.
  642. if (!SS || !SS->isSet()) {
  643. diagnoseTypo(Corrected,
  644. PDiag(IsTemplateName ? diag::err_no_template_suggest
  645. : diag::err_unknown_typename_suggest)
  646. << II, CanRecover);
  647. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  648. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  649. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  650. II->getName().equals(CorrectedStr);
  651. diagnoseTypo(Corrected,
  652. PDiag(IsTemplateName
  653. ? diag::err_no_member_template_suggest
  654. : diag::err_unknown_nested_typename_suggest)
  655. << II << DC << DroppedSpecifier << SS->getRange(),
  656. CanRecover);
  657. } else {
  658. llvm_unreachable("could not have corrected a typo here");
  659. }
  660. if (!CanRecover)
  661. return;
  662. CXXScopeSpec tmpSS;
  663. if (Corrected.getCorrectionSpecifier())
  664. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  665. SourceRange(IILoc));
  666. // FIXME: Support class template argument deduction here.
  667. SuggestedType =
  668. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  669. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  670. /*IsCtorOrDtorName=*/false,
  671. /*WantNontrivialTypeSourceInfo=*/true);
  672. }
  673. return;
  674. }
  675. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  676. // See if II is a class template that the user forgot to pass arguments to.
  677. UnqualifiedId Name;
  678. Name.setIdentifier(II, IILoc);
  679. CXXScopeSpec EmptySS;
  680. TemplateTy TemplateResult;
  681. bool MemberOfUnknownSpecialization;
  682. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  683. Name, nullptr, true, TemplateResult,
  684. MemberOfUnknownSpecialization) == TNK_Type_template) {
  685. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  686. return;
  687. }
  688. }
  689. // FIXME: Should we move the logic that tries to recover from a missing tag
  690. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  691. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  692. Diag(IILoc, IsTemplateName ? diag::err_no_template
  693. : diag::err_unknown_typename)
  694. << II;
  695. else if (DeclContext *DC = computeDeclContext(*SS, false))
  696. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  697. : diag::err_typename_nested_not_found)
  698. << II << DC << SS->getRange();
  699. else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
  700. SuggestedType =
  701. ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
  702. } else if (isDependentScopeSpecifier(*SS)) {
  703. unsigned DiagID = diag::err_typename_missing;
  704. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  705. DiagID = diag::ext_typename_missing;
  706. Diag(SS->getRange().getBegin(), DiagID)
  707. << SS->getScopeRep() << II->getName()
  708. << SourceRange(SS->getRange().getBegin(), IILoc)
  709. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  710. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  711. *SS, *II, IILoc).get();
  712. } else {
  713. assert(SS && SS->isInvalid() &&
  714. "Invalid scope specifier has already been diagnosed");
  715. }
  716. }
  717. /// Determine whether the given result set contains either a type name
  718. /// or
  719. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  720. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  721. NextToken.is(tok::less);
  722. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  723. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  724. return true;
  725. if (CheckTemplate && isa<TemplateDecl>(*I))
  726. return true;
  727. }
  728. return false;
  729. }
  730. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  731. Scope *S, CXXScopeSpec &SS,
  732. IdentifierInfo *&Name,
  733. SourceLocation NameLoc) {
  734. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  735. SemaRef.LookupParsedName(R, S, &SS);
  736. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  737. StringRef FixItTagName;
  738. switch (Tag->getTagKind()) {
  739. case TTK_Class:
  740. FixItTagName = "class ";
  741. break;
  742. case TTK_Enum:
  743. FixItTagName = "enum ";
  744. break;
  745. case TTK_Struct:
  746. FixItTagName = "struct ";
  747. break;
  748. case TTK_Interface:
  749. FixItTagName = "__interface ";
  750. break;
  751. case TTK_Union:
  752. FixItTagName = "union ";
  753. break;
  754. }
  755. StringRef TagName = FixItTagName.drop_back();
  756. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  757. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  758. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  759. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  760. I != IEnd; ++I)
  761. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  762. << Name << TagName;
  763. // Replace lookup results with just the tag decl.
  764. Result.clear(Sema::LookupTagName);
  765. SemaRef.LookupParsedName(Result, S, &SS);
  766. return true;
  767. }
  768. return false;
  769. }
  770. Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
  771. IdentifierInfo *&Name,
  772. SourceLocation NameLoc,
  773. const Token &NextToken,
  774. CorrectionCandidateCallback *CCC) {
  775. DeclarationNameInfo NameInfo(Name, NameLoc);
  776. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  777. assert(NextToken.isNot(tok::coloncolon) &&
  778. "parse nested name specifiers before calling ClassifyName");
  779. if (getLangOpts().CPlusPlus && SS.isSet() &&
  780. isCurrentClassName(*Name, S, &SS)) {
  781. // Per [class.qual]p2, this names the constructors of SS, not the
  782. // injected-class-name. We don't have a classification for that.
  783. // There's not much point caching this result, since the parser
  784. // will reject it later.
  785. return NameClassification::Unknown();
  786. }
  787. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  788. LookupParsedName(Result, S, &SS, !CurMethod);
  789. if (SS.isInvalid())
  790. return NameClassification::Error();
  791. // For unqualified lookup in a class template in MSVC mode, look into
  792. // dependent base classes where the primary class template is known.
  793. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  794. if (ParsedType TypeInBase =
  795. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  796. return TypeInBase;
  797. }
  798. // Perform lookup for Objective-C instance variables (including automatically
  799. // synthesized instance variables), if we're in an Objective-C method.
  800. // FIXME: This lookup really, really needs to be folded in to the normal
  801. // unqualified lookup mechanism.
  802. if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  803. DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
  804. if (Ivar.isInvalid())
  805. return NameClassification::Error();
  806. if (Ivar.isUsable())
  807. return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
  808. // We defer builtin creation until after ivar lookup inside ObjC methods.
  809. if (Result.empty())
  810. LookupBuiltin(Result);
  811. }
  812. bool SecondTry = false;
  813. bool IsFilteredTemplateName = false;
  814. Corrected:
  815. switch (Result.getResultKind()) {
  816. case LookupResult::NotFound:
  817. // If an unqualified-id is followed by a '(', then we have a function
  818. // call.
  819. if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
  820. // In C++, this is an ADL-only call.
  821. // FIXME: Reference?
  822. if (getLangOpts().CPlusPlus)
  823. return NameClassification::UndeclaredNonType();
  824. // C90 6.3.2.2:
  825. // If the expression that precedes the parenthesized argument list in a
  826. // function call consists solely of an identifier, and if no
  827. // declaration is visible for this identifier, the identifier is
  828. // implicitly declared exactly as if, in the innermost block containing
  829. // the function call, the declaration
  830. //
  831. // extern int identifier ();
  832. //
  833. // appeared.
  834. //
  835. // We also allow this in C99 as an extension.
  836. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
  837. return NameClassification::NonType(D);
  838. }
  839. if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
  840. // In C++20 onwards, this could be an ADL-only call to a function
  841. // template, and we're required to assume that this is a template name.
  842. //
  843. // FIXME: Find a way to still do typo correction in this case.
  844. TemplateName Template =
  845. Context.getAssumedTemplateName(NameInfo.getName());
  846. return NameClassification::UndeclaredTemplate(Template);
  847. }
  848. // In C, we first see whether there is a tag type by the same name, in
  849. // which case it's likely that the user just forgot to write "enum",
  850. // "struct", or "union".
  851. if (!getLangOpts().CPlusPlus && !SecondTry &&
  852. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  853. break;
  854. }
  855. // Perform typo correction to determine if there is another name that is
  856. // close to this name.
  857. if (!SecondTry && CCC) {
  858. SecondTry = true;
  859. if (TypoCorrection Corrected =
  860. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  861. &SS, *CCC, CTK_ErrorRecovery)) {
  862. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  863. unsigned QualifiedDiag = diag::err_no_member_suggest;
  864. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  865. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  866. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  867. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  868. UnqualifiedDiag = diag::err_no_template_suggest;
  869. QualifiedDiag = diag::err_no_member_template_suggest;
  870. } else if (UnderlyingFirstDecl &&
  871. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  872. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  873. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  874. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  875. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  876. }
  877. if (SS.isEmpty()) {
  878. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  879. } else {// FIXME: is this even reachable? Test it.
  880. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  881. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  882. Name->getName().equals(CorrectedStr);
  883. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  884. << Name << computeDeclContext(SS, false)
  885. << DroppedSpecifier << SS.getRange());
  886. }
  887. // Update the name, so that the caller has the new name.
  888. Name = Corrected.getCorrectionAsIdentifierInfo();
  889. // Typo correction corrected to a keyword.
  890. if (Corrected.isKeyword())
  891. return Name;
  892. // Also update the LookupResult...
  893. // FIXME: This should probably go away at some point
  894. Result.clear();
  895. Result.setLookupName(Corrected.getCorrection());
  896. if (FirstDecl)
  897. Result.addDecl(FirstDecl);
  898. // If we found an Objective-C instance variable, let
  899. // LookupInObjCMethod build the appropriate expression to
  900. // reference the ivar.
  901. // FIXME: This is a gross hack.
  902. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  903. DeclResult R =
  904. LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
  905. if (R.isInvalid())
  906. return NameClassification::Error();
  907. if (R.isUsable())
  908. return NameClassification::NonType(Ivar);
  909. }
  910. goto Corrected;
  911. }
  912. }
  913. // We failed to correct; just fall through and let the parser deal with it.
  914. Result.suppressDiagnostics();
  915. return NameClassification::Unknown();
  916. case LookupResult::NotFoundInCurrentInstantiation: {
  917. // We performed name lookup into the current instantiation, and there were
  918. // dependent bases, so we treat this result the same way as any other
  919. // dependent nested-name-specifier.
  920. // C++ [temp.res]p2:
  921. // A name used in a template declaration or definition and that is
  922. // dependent on a template-parameter is assumed not to name a type
  923. // unless the applicable name lookup finds a type name or the name is
  924. // qualified by the keyword typename.
  925. //
  926. // FIXME: If the next token is '<', we might want to ask the parser to
  927. // perform some heroics to see if we actually have a
  928. // template-argument-list, which would indicate a missing 'template'
  929. // keyword here.
  930. return NameClassification::DependentNonType();
  931. }
  932. case LookupResult::Found:
  933. case LookupResult::FoundOverloaded:
  934. case LookupResult::FoundUnresolvedValue:
  935. break;
  936. case LookupResult::Ambiguous:
  937. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  938. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  939. /*AllowDependent=*/false)) {
  940. // C++ [temp.local]p3:
  941. // A lookup that finds an injected-class-name (10.2) can result in an
  942. // ambiguity in certain cases (for example, if it is found in more than
  943. // one base class). If all of the injected-class-names that are found
  944. // refer to specializations of the same class template, and if the name
  945. // is followed by a template-argument-list, the reference refers to the
  946. // class template itself and not a specialization thereof, and is not
  947. // ambiguous.
  948. //
  949. // This filtering can make an ambiguous result into an unambiguous one,
  950. // so try again after filtering out template names.
  951. FilterAcceptableTemplateNames(Result);
  952. if (!Result.isAmbiguous()) {
  953. IsFilteredTemplateName = true;
  954. break;
  955. }
  956. }
  957. // Diagnose the ambiguity and return an error.
  958. return NameClassification::Error();
  959. }
  960. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  961. (IsFilteredTemplateName ||
  962. hasAnyAcceptableTemplateNames(
  963. Result, /*AllowFunctionTemplates=*/true,
  964. /*AllowDependent=*/false,
  965. /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
  966. getLangOpts().CPlusPlus20))) {
  967. // C++ [temp.names]p3:
  968. // After name lookup (3.4) finds that a name is a template-name or that
  969. // an operator-function-id or a literal- operator-id refers to a set of
  970. // overloaded functions any member of which is a function template if
  971. // this is followed by a <, the < is always taken as the delimiter of a
  972. // template-argument-list and never as the less-than operator.
  973. // C++2a [temp.names]p2:
  974. // A name is also considered to refer to a template if it is an
  975. // unqualified-id followed by a < and name lookup finds either one
  976. // or more functions or finds nothing.
  977. if (!IsFilteredTemplateName)
  978. FilterAcceptableTemplateNames(Result);
  979. bool IsFunctionTemplate;
  980. bool IsVarTemplate;
  981. TemplateName Template;
  982. if (Result.end() - Result.begin() > 1) {
  983. IsFunctionTemplate = true;
  984. Template = Context.getOverloadedTemplateName(Result.begin(),
  985. Result.end());
  986. } else if (!Result.empty()) {
  987. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  988. *Result.begin(), /*AllowFunctionTemplates=*/true,
  989. /*AllowDependent=*/false));
  990. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  991. IsVarTemplate = isa<VarTemplateDecl>(TD);
  992. if (SS.isNotEmpty())
  993. Template =
  994. Context.getQualifiedTemplateName(SS.getScopeRep(),
  995. /*TemplateKeyword=*/false, TD);
  996. else
  997. Template = TemplateName(TD);
  998. } else {
  999. // All results were non-template functions. This is a function template
  1000. // name.
  1001. IsFunctionTemplate = true;
  1002. Template = Context.getAssumedTemplateName(NameInfo.getName());
  1003. }
  1004. if (IsFunctionTemplate) {
  1005. // Function templates always go through overload resolution, at which
  1006. // point we'll perform the various checks (e.g., accessibility) we need
  1007. // to based on which function we selected.
  1008. Result.suppressDiagnostics();
  1009. return NameClassification::FunctionTemplate(Template);
  1010. }
  1011. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  1012. : NameClassification::TypeTemplate(Template);
  1013. }
  1014. auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
  1015. QualType T = Context.getTypeDeclType(Type);
  1016. if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
  1017. T = Context.getUsingType(USD, T);
  1018. if (SS.isEmpty()) // No elaborated type, trivial location info
  1019. return ParsedType::make(T);
  1020. TypeLocBuilder Builder;
  1021. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  1022. T = getElaboratedType(ETK_None, SS, T);
  1023. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  1024. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  1025. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  1026. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  1027. };
  1028. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  1029. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  1030. DiagnoseUseOfDecl(Type, NameLoc);
  1031. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1032. return BuildTypeFor(Type, *Result.begin());
  1033. }
  1034. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1035. if (!Class) {
  1036. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1037. if (ObjCCompatibleAliasDecl *Alias =
  1038. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1039. Class = Alias->getClassInterface();
  1040. }
  1041. if (Class) {
  1042. DiagnoseUseOfDecl(Class, NameLoc);
  1043. if (NextToken.is(tok::period)) {
  1044. // Interface. <something> is parsed as a property reference expression.
  1045. // Just return "unknown" as a fall-through for now.
  1046. Result.suppressDiagnostics();
  1047. return NameClassification::Unknown();
  1048. }
  1049. QualType T = Context.getObjCInterfaceType(Class);
  1050. return ParsedType::make(T);
  1051. }
  1052. if (isa<ConceptDecl>(FirstDecl))
  1053. return NameClassification::Concept(
  1054. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1055. if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
  1056. (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
  1057. return NameClassification::Error();
  1058. }
  1059. // We can have a type template here if we're classifying a template argument.
  1060. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1061. !isa<VarTemplateDecl>(FirstDecl))
  1062. return NameClassification::TypeTemplate(
  1063. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1064. // Check for a tag type hidden by a non-type decl in a few cases where it
  1065. // seems likely a type is wanted instead of the non-type that was found.
  1066. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1067. if ((NextToken.is(tok::identifier) ||
  1068. (NextIsOp &&
  1069. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1070. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1071. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1072. DiagnoseUseOfDecl(Type, NameLoc);
  1073. return BuildTypeFor(Type, *Result.begin());
  1074. }
  1075. // If we already know which single declaration is referenced, just annotate
  1076. // that declaration directly. Defer resolving even non-overloaded class
  1077. // member accesses, as we need to defer certain access checks until we know
  1078. // the context.
  1079. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1080. if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
  1081. return NameClassification::NonType(Result.getRepresentativeDecl());
  1082. // Otherwise, this is an overload set that we will need to resolve later.
  1083. Result.suppressDiagnostics();
  1084. return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
  1085. Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
  1086. Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
  1087. Result.begin(), Result.end()));
  1088. }
  1089. ExprResult
  1090. Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
  1091. SourceLocation NameLoc) {
  1092. assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
  1093. CXXScopeSpec SS;
  1094. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  1095. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  1096. }
  1097. ExprResult
  1098. Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
  1099. IdentifierInfo *Name,
  1100. SourceLocation NameLoc,
  1101. bool IsAddressOfOperand) {
  1102. DeclarationNameInfo NameInfo(Name, NameLoc);
  1103. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  1104. NameInfo, IsAddressOfOperand,
  1105. /*TemplateArgs=*/nullptr);
  1106. }
  1107. ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
  1108. NamedDecl *Found,
  1109. SourceLocation NameLoc,
  1110. const Token &NextToken) {
  1111. if (getCurMethodDecl() && SS.isEmpty())
  1112. if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
  1113. return BuildIvarRefExpr(S, NameLoc, Ivar);
  1114. // Reconstruct the lookup result.
  1115. LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
  1116. Result.addDecl(Found);
  1117. Result.resolveKind();
  1118. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1119. return BuildDeclarationNameExpr(SS, Result, ADL);
  1120. }
  1121. ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
  1122. // For an implicit class member access, transform the result into a member
  1123. // access expression if necessary.
  1124. auto *ULE = cast<UnresolvedLookupExpr>(E);
  1125. if ((*ULE->decls_begin())->isCXXClassMember()) {
  1126. CXXScopeSpec SS;
  1127. SS.Adopt(ULE->getQualifierLoc());
  1128. // Reconstruct the lookup result.
  1129. LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
  1130. LookupOrdinaryName);
  1131. Result.setNamingClass(ULE->getNamingClass());
  1132. for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
  1133. Result.addDecl(*I, I.getAccess());
  1134. Result.resolveKind();
  1135. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1136. nullptr, S);
  1137. }
  1138. // Otherwise, this is already in the form we needed, and no further checks
  1139. // are necessary.
  1140. return ULE;
  1141. }
  1142. Sema::TemplateNameKindForDiagnostics
  1143. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1144. auto *TD = Name.getAsTemplateDecl();
  1145. if (!TD)
  1146. return TemplateNameKindForDiagnostics::DependentTemplate;
  1147. if (isa<ClassTemplateDecl>(TD))
  1148. return TemplateNameKindForDiagnostics::ClassTemplate;
  1149. if (isa<FunctionTemplateDecl>(TD))
  1150. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1151. if (isa<VarTemplateDecl>(TD))
  1152. return TemplateNameKindForDiagnostics::VarTemplate;
  1153. if (isa<TypeAliasTemplateDecl>(TD))
  1154. return TemplateNameKindForDiagnostics::AliasTemplate;
  1155. if (isa<TemplateTemplateParmDecl>(TD))
  1156. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1157. if (isa<ConceptDecl>(TD))
  1158. return TemplateNameKindForDiagnostics::Concept;
  1159. return TemplateNameKindForDiagnostics::DependentTemplate;
  1160. }
  1161. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1162. assert(DC->getLexicalParent() == CurContext &&
  1163. "The next DeclContext should be lexically contained in the current one.");
  1164. CurContext = DC;
  1165. S->setEntity(DC);
  1166. }
  1167. void Sema::PopDeclContext() {
  1168. assert(CurContext && "DeclContext imbalance!");
  1169. CurContext = CurContext->getLexicalParent();
  1170. assert(CurContext && "Popped translation unit!");
  1171. }
  1172. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1173. Decl *D) {
  1174. // Unlike PushDeclContext, the context to which we return is not necessarily
  1175. // the containing DC of TD, because the new context will be some pre-existing
  1176. // TagDecl definition instead of a fresh one.
  1177. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1178. CurContext = cast<TagDecl>(D)->getDefinition();
  1179. assert(CurContext && "skipping definition of undefined tag");
  1180. // Start lookups from the parent of the current context; we don't want to look
  1181. // into the pre-existing complete definition.
  1182. S->setEntity(CurContext->getLookupParent());
  1183. return Result;
  1184. }
  1185. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1186. CurContext = static_cast<decltype(CurContext)>(Context);
  1187. }
  1188. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1189. /// of a declarator's nested name specifier.
  1190. ///
  1191. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1192. // C++0x [basic.lookup.unqual]p13:
  1193. // A name used in the definition of a static data member of class
  1194. // X (after the qualified-id of the static member) is looked up as
  1195. // if the name was used in a member function of X.
  1196. // C++0x [basic.lookup.unqual]p14:
  1197. // If a variable member of a namespace is defined outside of the
  1198. // scope of its namespace then any name used in the definition of
  1199. // the variable member (after the declarator-id) is looked up as
  1200. // if the definition of the variable member occurred in its
  1201. // namespace.
  1202. // Both of these imply that we should push a scope whose context
  1203. // is the semantic context of the declaration. We can't use
  1204. // PushDeclContext here because that context is not necessarily
  1205. // lexically contained in the current context. Fortunately,
  1206. // the containing scope should have the appropriate information.
  1207. assert(!S->getEntity() && "scope already has entity");
  1208. #ifndef NDEBUG
  1209. Scope *Ancestor = S->getParent();
  1210. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1211. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1212. #endif
  1213. CurContext = DC;
  1214. S->setEntity(DC);
  1215. if (S->getParent()->isTemplateParamScope()) {
  1216. // Also set the corresponding entities for all immediately-enclosing
  1217. // template parameter scopes.
  1218. EnterTemplatedContext(S->getParent(), DC);
  1219. }
  1220. }
  1221. void Sema::ExitDeclaratorContext(Scope *S) {
  1222. assert(S->getEntity() == CurContext && "Context imbalance!");
  1223. // Switch back to the lexical context. The safety of this is
  1224. // enforced by an assert in EnterDeclaratorContext.
  1225. Scope *Ancestor = S->getParent();
  1226. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1227. CurContext = Ancestor->getEntity();
  1228. // We don't need to do anything with the scope, which is going to
  1229. // disappear.
  1230. }
  1231. void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
  1232. assert(S->isTemplateParamScope() &&
  1233. "expected to be initializing a template parameter scope");
  1234. // C++20 [temp.local]p7:
  1235. // In the definition of a member of a class template that appears outside
  1236. // of the class template definition, the name of a member of the class
  1237. // template hides the name of a template-parameter of any enclosing class
  1238. // templates (but not a template-parameter of the member if the member is a
  1239. // class or function template).
  1240. // C++20 [temp.local]p9:
  1241. // In the definition of a class template or in the definition of a member
  1242. // of such a template that appears outside of the template definition, for
  1243. // each non-dependent base class (13.8.2.1), if the name of the base class
  1244. // or the name of a member of the base class is the same as the name of a
  1245. // template-parameter, the base class name or member name hides the
  1246. // template-parameter name (6.4.10).
  1247. //
  1248. // This means that a template parameter scope should be searched immediately
  1249. // after searching the DeclContext for which it is a template parameter
  1250. // scope. For example, for
  1251. // template<typename T> template<typename U> template<typename V>
  1252. // void N::A<T>::B<U>::f(...)
  1253. // we search V then B<U> (and base classes) then U then A<T> (and base
  1254. // classes) then T then N then ::.
  1255. unsigned ScopeDepth = getTemplateDepth(S);
  1256. for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
  1257. DeclContext *SearchDCAfterScope = DC;
  1258. for (; DC; DC = DC->getLookupParent()) {
  1259. if (const TemplateParameterList *TPL =
  1260. cast<Decl>(DC)->getDescribedTemplateParams()) {
  1261. unsigned DCDepth = TPL->getDepth() + 1;
  1262. if (DCDepth > ScopeDepth)
  1263. continue;
  1264. if (ScopeDepth == DCDepth)
  1265. SearchDCAfterScope = DC = DC->getLookupParent();
  1266. break;
  1267. }
  1268. }
  1269. S->setLookupEntity(SearchDCAfterScope);
  1270. }
  1271. }
  1272. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1273. // We assume that the caller has already called
  1274. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1275. FunctionDecl *FD = D->getAsFunction();
  1276. if (!FD)
  1277. return;
  1278. // Same implementation as PushDeclContext, but enters the context
  1279. // from the lexical parent, rather than the top-level class.
  1280. assert(CurContext == FD->getLexicalParent() &&
  1281. "The next DeclContext should be lexically contained in the current one.");
  1282. CurContext = FD;
  1283. S->setEntity(CurContext);
  1284. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1285. ParmVarDecl *Param = FD->getParamDecl(P);
  1286. // If the parameter has an identifier, then add it to the scope
  1287. if (Param->getIdentifier()) {
  1288. S->AddDecl(Param);
  1289. IdResolver.AddDecl(Param);
  1290. }
  1291. }
  1292. }
  1293. void Sema::ActOnExitFunctionContext() {
  1294. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1295. // rather than the top-level class.
  1296. assert(CurContext && "DeclContext imbalance!");
  1297. CurContext = CurContext->getLexicalParent();
  1298. assert(CurContext && "Popped translation unit!");
  1299. }
  1300. /// Determine whether we allow overloading of the function
  1301. /// PrevDecl with another declaration.
  1302. ///
  1303. /// This routine determines whether overloading is possible, not
  1304. /// whether some new function is actually an overload. It will return
  1305. /// true in C++ (where we can always provide overloads) or, as an
  1306. /// extension, in C when the previous function is already an
  1307. /// overloaded function declaration or has the "overloadable"
  1308. /// attribute.
  1309. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1310. ASTContext &Context,
  1311. const FunctionDecl *New) {
  1312. if (Context.getLangOpts().CPlusPlus)
  1313. return true;
  1314. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1315. return true;
  1316. return Previous.getResultKind() == LookupResult::Found &&
  1317. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1318. New->hasAttr<OverloadableAttr>());
  1319. }
  1320. /// Add this decl to the scope shadowed decl chains.
  1321. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1322. // Move up the scope chain until we find the nearest enclosing
  1323. // non-transparent context. The declaration will be introduced into this
  1324. // scope.
  1325. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1326. S = S->getParent();
  1327. // Add scoped declarations into their context, so that they can be
  1328. // found later. Declarations without a context won't be inserted
  1329. // into any context.
  1330. if (AddToContext)
  1331. CurContext->addDecl(D);
  1332. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1333. // are function-local declarations.
  1334. if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
  1335. return;
  1336. // Template instantiations should also not be pushed into scope.
  1337. if (isa<FunctionDecl>(D) &&
  1338. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1339. return;
  1340. // If this replaces anything in the current scope,
  1341. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1342. IEnd = IdResolver.end();
  1343. for (; I != IEnd; ++I) {
  1344. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1345. S->RemoveDecl(*I);
  1346. IdResolver.RemoveDecl(*I);
  1347. // Should only need to replace one decl.
  1348. break;
  1349. }
  1350. }
  1351. S->AddDecl(D);
  1352. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1353. // Implicitly-generated labels may end up getting generated in an order that
  1354. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1355. // the label at the appropriate place in the identifier chain.
  1356. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1357. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1358. if (IDC == CurContext) {
  1359. if (!S->isDeclScope(*I))
  1360. continue;
  1361. } else if (IDC->Encloses(CurContext))
  1362. break;
  1363. }
  1364. IdResolver.InsertDeclAfter(I, D);
  1365. } else {
  1366. IdResolver.AddDecl(D);
  1367. }
  1368. warnOnReservedIdentifier(D);
  1369. }
  1370. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1371. bool AllowInlineNamespace) {
  1372. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1373. }
  1374. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1375. DeclContext *TargetDC = DC->getPrimaryContext();
  1376. do {
  1377. if (DeclContext *ScopeDC = S->getEntity())
  1378. if (ScopeDC->getPrimaryContext() == TargetDC)
  1379. return S;
  1380. } while ((S = S->getParent()));
  1381. return nullptr;
  1382. }
  1383. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1384. DeclContext*,
  1385. ASTContext&);
  1386. /// Filters out lookup results that don't fall within the given scope
  1387. /// as determined by isDeclInScope.
  1388. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1389. bool ConsiderLinkage,
  1390. bool AllowInlineNamespace) {
  1391. LookupResult::Filter F = R.makeFilter();
  1392. while (F.hasNext()) {
  1393. NamedDecl *D = F.next();
  1394. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1395. continue;
  1396. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1397. continue;
  1398. F.erase();
  1399. }
  1400. F.done();
  1401. }
  1402. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1403. /// have compatible owning modules.
  1404. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1405. // [module.interface]p7:
  1406. // A declaration is attached to a module as follows:
  1407. // - If the declaration is a non-dependent friend declaration that nominates a
  1408. // function with a declarator-id that is a qualified-id or template-id or that
  1409. // nominates a class other than with an elaborated-type-specifier with neither
  1410. // a nested-name-specifier nor a simple-template-id, it is attached to the
  1411. // module to which the friend is attached ([basic.link]).
  1412. if (New->getFriendObjectKind() &&
  1413. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1414. New->setLocalOwningModule(Old->getOwningModule());
  1415. makeMergedDefinitionVisible(New);
  1416. return false;
  1417. }
  1418. Module *NewM = New->getOwningModule();
  1419. Module *OldM = Old->getOwningModule();
  1420. if (NewM && NewM->Kind == Module::PrivateModuleFragment)
  1421. NewM = NewM->Parent;
  1422. if (OldM && OldM->Kind == Module::PrivateModuleFragment)
  1423. OldM = OldM->Parent;
  1424. if (NewM == OldM)
  1425. return false;
  1426. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1427. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1428. if (NewIsModuleInterface || OldIsModuleInterface) {
  1429. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1430. // if a declaration of D [...] appears in the purview of a module, all
  1431. // other such declarations shall appear in the purview of the same module
  1432. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1433. << New
  1434. << NewIsModuleInterface
  1435. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1436. << OldIsModuleInterface
  1437. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1438. Diag(Old->getLocation(), diag::note_previous_declaration);
  1439. New->setInvalidDecl();
  1440. return true;
  1441. }
  1442. return false;
  1443. }
  1444. // [module.interface]p6:
  1445. // A redeclaration of an entity X is implicitly exported if X was introduced by
  1446. // an exported declaration; otherwise it shall not be exported.
  1447. bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
  1448. // [module.interface]p1:
  1449. // An export-declaration shall inhabit a namespace scope.
  1450. //
  1451. // So it is meaningless to talk about redeclaration which is not at namespace
  1452. // scope.
  1453. if (!New->getLexicalDeclContext()
  1454. ->getNonTransparentContext()
  1455. ->isFileContext() ||
  1456. !Old->getLexicalDeclContext()
  1457. ->getNonTransparentContext()
  1458. ->isFileContext())
  1459. return false;
  1460. bool IsNewExported = New->isInExportDeclContext();
  1461. bool IsOldExported = Old->isInExportDeclContext();
  1462. // It should be irrevelant if both of them are not exported.
  1463. if (!IsNewExported && !IsOldExported)
  1464. return false;
  1465. if (IsOldExported)
  1466. return false;
  1467. assert(IsNewExported);
  1468. Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
  1469. Diag(Old->getLocation(), diag::note_previous_declaration);
  1470. return true;
  1471. }
  1472. // A wrapper function for checking the semantic restrictions of
  1473. // a redeclaration within a module.
  1474. bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
  1475. if (CheckRedeclarationModuleOwnership(New, Old))
  1476. return true;
  1477. if (CheckRedeclarationExported(New, Old))
  1478. return true;
  1479. return false;
  1480. }
  1481. static bool isUsingDecl(NamedDecl *D) {
  1482. return isa<UsingShadowDecl>(D) ||
  1483. isa<UnresolvedUsingTypenameDecl>(D) ||
  1484. isa<UnresolvedUsingValueDecl>(D);
  1485. }
  1486. /// Removes using shadow declarations from the lookup results.
  1487. static void RemoveUsingDecls(LookupResult &R) {
  1488. LookupResult::Filter F = R.makeFilter();
  1489. while (F.hasNext())
  1490. if (isUsingDecl(F.next()))
  1491. F.erase();
  1492. F.done();
  1493. }
  1494. /// Check for this common pattern:
  1495. /// @code
  1496. /// class S {
  1497. /// S(const S&); // DO NOT IMPLEMENT
  1498. /// void operator=(const S&); // DO NOT IMPLEMENT
  1499. /// };
  1500. /// @endcode
  1501. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1502. // FIXME: Should check for private access too but access is set after we get
  1503. // the decl here.
  1504. if (D->doesThisDeclarationHaveABody())
  1505. return false;
  1506. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1507. return CD->isCopyConstructor();
  1508. return D->isCopyAssignmentOperator();
  1509. }
  1510. // We need this to handle
  1511. //
  1512. // typedef struct {
  1513. // void *foo() { return 0; }
  1514. // } A;
  1515. //
  1516. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1517. // for example. If 'A', foo will have external linkage. If we have '*A',
  1518. // foo will have no linkage. Since we can't know until we get to the end
  1519. // of the typedef, this function finds out if D might have non-external linkage.
  1520. // Callers should verify at the end of the TU if it D has external linkage or
  1521. // not.
  1522. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1523. const DeclContext *DC = D->getDeclContext();
  1524. while (!DC->isTranslationUnit()) {
  1525. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1526. if (!RD->hasNameForLinkage())
  1527. return true;
  1528. }
  1529. DC = DC->getParent();
  1530. }
  1531. return !D->isExternallyVisible();
  1532. }
  1533. // FIXME: This needs to be refactored; some other isInMainFile users want
  1534. // these semantics.
  1535. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1536. if (S.TUKind != TU_Complete)
  1537. return false;
  1538. return S.SourceMgr.isInMainFile(Loc);
  1539. }
  1540. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1541. assert(D);
  1542. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1543. return false;
  1544. // Ignore all entities declared within templates, and out-of-line definitions
  1545. // of members of class templates.
  1546. if (D->getDeclContext()->isDependentContext() ||
  1547. D->getLexicalDeclContext()->isDependentContext())
  1548. return false;
  1549. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1550. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1551. return false;
  1552. // A non-out-of-line declaration of a member specialization was implicitly
  1553. // instantiated; it's the out-of-line declaration that we're interested in.
  1554. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1555. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1556. return false;
  1557. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1558. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1559. return false;
  1560. } else {
  1561. // 'static inline' functions are defined in headers; don't warn.
  1562. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1563. return false;
  1564. }
  1565. if (FD->doesThisDeclarationHaveABody() &&
  1566. Context.DeclMustBeEmitted(FD))
  1567. return false;
  1568. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1569. // Constants and utility variables are defined in headers with internal
  1570. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1571. // like "inline".)
  1572. if (!isMainFileLoc(*this, VD->getLocation()))
  1573. return false;
  1574. if (Context.DeclMustBeEmitted(VD))
  1575. return false;
  1576. if (VD->isStaticDataMember() &&
  1577. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1578. return false;
  1579. if (VD->isStaticDataMember() &&
  1580. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1581. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1582. return false;
  1583. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1584. return false;
  1585. } else {
  1586. return false;
  1587. }
  1588. // Only warn for unused decls internal to the translation unit.
  1589. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1590. // for inline functions defined in the main source file, for instance.
  1591. return mightHaveNonExternalLinkage(D);
  1592. }
  1593. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1594. if (!D)
  1595. return;
  1596. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1597. const FunctionDecl *First = FD->getFirstDecl();
  1598. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1599. return; // First should already be in the vector.
  1600. }
  1601. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1602. const VarDecl *First = VD->getFirstDecl();
  1603. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1604. return; // First should already be in the vector.
  1605. }
  1606. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1607. UnusedFileScopedDecls.push_back(D);
  1608. }
  1609. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1610. if (D->isInvalidDecl())
  1611. return false;
  1612. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1613. // For a decomposition declaration, warn if none of the bindings are
  1614. // referenced, instead of if the variable itself is referenced (which
  1615. // it is, by the bindings' expressions).
  1616. for (auto *BD : DD->bindings())
  1617. if (BD->isReferenced())
  1618. return false;
  1619. } else if (!D->getDeclName()) {
  1620. return false;
  1621. } else if (D->isReferenced() || D->isUsed()) {
  1622. return false;
  1623. }
  1624. if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
  1625. return false;
  1626. if (isa<LabelDecl>(D))
  1627. return true;
  1628. // Except for labels, we only care about unused decls that are local to
  1629. // functions.
  1630. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1631. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1632. // For dependent types, the diagnostic is deferred.
  1633. WithinFunction =
  1634. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1635. if (!WithinFunction)
  1636. return false;
  1637. if (isa<TypedefNameDecl>(D))
  1638. return true;
  1639. // White-list anything that isn't a local variable.
  1640. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1641. return false;
  1642. // Types of valid local variables should be complete, so this should succeed.
  1643. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1644. // White-list anything with an __attribute__((unused)) type.
  1645. const auto *Ty = VD->getType().getTypePtr();
  1646. // Only look at the outermost level of typedef.
  1647. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1648. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1649. return false;
  1650. }
  1651. // If we failed to complete the type for some reason, or if the type is
  1652. // dependent, don't diagnose the variable.
  1653. if (Ty->isIncompleteType() || Ty->isDependentType())
  1654. return false;
  1655. // Look at the element type to ensure that the warning behaviour is
  1656. // consistent for both scalars and arrays.
  1657. Ty = Ty->getBaseElementTypeUnsafe();
  1658. if (const TagType *TT = Ty->getAs<TagType>()) {
  1659. const TagDecl *Tag = TT->getDecl();
  1660. if (Tag->hasAttr<UnusedAttr>())
  1661. return false;
  1662. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1663. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1664. return false;
  1665. if (const Expr *Init = VD->getInit()) {
  1666. if (const ExprWithCleanups *Cleanups =
  1667. dyn_cast<ExprWithCleanups>(Init))
  1668. Init = Cleanups->getSubExpr();
  1669. const CXXConstructExpr *Construct =
  1670. dyn_cast<CXXConstructExpr>(Init);
  1671. if (Construct && !Construct->isElidable()) {
  1672. CXXConstructorDecl *CD = Construct->getConstructor();
  1673. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1674. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1675. return false;
  1676. }
  1677. // Suppress the warning if we don't know how this is constructed, and
  1678. // it could possibly be non-trivial constructor.
  1679. if (Init->isTypeDependent())
  1680. for (const CXXConstructorDecl *Ctor : RD->ctors())
  1681. if (!Ctor->isTrivial())
  1682. return false;
  1683. }
  1684. }
  1685. }
  1686. // TODO: __attribute__((unused)) templates?
  1687. }
  1688. return true;
  1689. }
  1690. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1691. FixItHint &Hint) {
  1692. if (isa<LabelDecl>(D)) {
  1693. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1694. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1695. true);
  1696. if (AfterColon.isInvalid())
  1697. return;
  1698. Hint = FixItHint::CreateRemoval(
  1699. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1700. }
  1701. }
  1702. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1703. if (D->getTypeForDecl()->isDependentType())
  1704. return;
  1705. for (auto *TmpD : D->decls()) {
  1706. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1707. DiagnoseUnusedDecl(T);
  1708. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1709. DiagnoseUnusedNestedTypedefs(R);
  1710. }
  1711. }
  1712. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1713. /// unless they are marked attr(unused).
  1714. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1715. if (!ShouldDiagnoseUnusedDecl(D))
  1716. return;
  1717. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1718. // typedefs can be referenced later on, so the diagnostics are emitted
  1719. // at end-of-translation-unit.
  1720. UnusedLocalTypedefNameCandidates.insert(TD);
  1721. return;
  1722. }
  1723. FixItHint Hint;
  1724. GenerateFixForUnusedDecl(D, Context, Hint);
  1725. unsigned DiagID;
  1726. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1727. DiagID = diag::warn_unused_exception_param;
  1728. else if (isa<LabelDecl>(D))
  1729. DiagID = diag::warn_unused_label;
  1730. else
  1731. DiagID = diag::warn_unused_variable;
  1732. Diag(D->getLocation(), DiagID) << D << Hint;
  1733. }
  1734. void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
  1735. // If it's not referenced, it can't be set. If it has the Cleanup attribute,
  1736. // it's not really unused.
  1737. if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
  1738. VD->hasAttr<CleanupAttr>())
  1739. return;
  1740. const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
  1741. if (Ty->isReferenceType() || Ty->isDependentType())
  1742. return;
  1743. if (const TagType *TT = Ty->getAs<TagType>()) {
  1744. const TagDecl *Tag = TT->getDecl();
  1745. if (Tag->hasAttr<UnusedAttr>())
  1746. return;
  1747. // In C++, don't warn for record types that don't have WarnUnusedAttr, to
  1748. // mimic gcc's behavior.
  1749. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1750. if (!RD->hasAttr<WarnUnusedAttr>())
  1751. return;
  1752. }
  1753. }
  1754. // Don't warn about __block Objective-C pointer variables, as they might
  1755. // be assigned in the block but not used elsewhere for the purpose of lifetime
  1756. // extension.
  1757. if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
  1758. return;
  1759. auto iter = RefsMinusAssignments.find(VD);
  1760. if (iter == RefsMinusAssignments.end())
  1761. return;
  1762. assert(iter->getSecond() >= 0 &&
  1763. "Found a negative number of references to a VarDecl");
  1764. if (iter->getSecond() != 0)
  1765. return;
  1766. unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
  1767. : diag::warn_unused_but_set_variable;
  1768. Diag(VD->getLocation(), DiagID) << VD;
  1769. }
  1770. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1771. // Verify that we have no forward references left. If so, there was a goto
  1772. // or address of a label taken, but no definition of it. Label fwd
  1773. // definitions are indicated with a null substmt which is also not a resolved
  1774. // MS inline assembly label name.
  1775. bool Diagnose = false;
  1776. if (L->isMSAsmLabel())
  1777. Diagnose = !L->isResolvedMSAsmLabel();
  1778. else
  1779. Diagnose = L->getStmt() == nullptr;
  1780. if (Diagnose)
  1781. S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
  1782. }
  1783. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1784. S->mergeNRVOIntoParent();
  1785. if (S->decl_empty()) return;
  1786. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1787. "Scope shouldn't contain decls!");
  1788. for (auto *TmpD : S->decls()) {
  1789. assert(TmpD && "This decl didn't get pushed??");
  1790. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1791. NamedDecl *D = cast<NamedDecl>(TmpD);
  1792. // Diagnose unused variables in this scope.
  1793. if (!S->hasUnrecoverableErrorOccurred()) {
  1794. DiagnoseUnusedDecl(D);
  1795. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1796. DiagnoseUnusedNestedTypedefs(RD);
  1797. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1798. DiagnoseUnusedButSetDecl(VD);
  1799. RefsMinusAssignments.erase(VD);
  1800. }
  1801. }
  1802. if (!D->getDeclName()) continue;
  1803. // If this was a forward reference to a label, verify it was defined.
  1804. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1805. CheckPoppedLabel(LD, *this);
  1806. // Remove this name from our lexical scope, and warn on it if we haven't
  1807. // already.
  1808. IdResolver.RemoveDecl(D);
  1809. auto ShadowI = ShadowingDecls.find(D);
  1810. if (ShadowI != ShadowingDecls.end()) {
  1811. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1812. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1813. << D << FD << FD->getParent();
  1814. Diag(FD->getLocation(), diag::note_previous_declaration);
  1815. }
  1816. ShadowingDecls.erase(ShadowI);
  1817. }
  1818. }
  1819. }
  1820. /// Look for an Objective-C class in the translation unit.
  1821. ///
  1822. /// \param Id The name of the Objective-C class we're looking for. If
  1823. /// typo-correction fixes this name, the Id will be updated
  1824. /// to the fixed name.
  1825. ///
  1826. /// \param IdLoc The location of the name in the translation unit.
  1827. ///
  1828. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1829. /// if there is no class with the given name.
  1830. ///
  1831. /// \returns The declaration of the named Objective-C class, or NULL if the
  1832. /// class could not be found.
  1833. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1834. SourceLocation IdLoc,
  1835. bool DoTypoCorrection) {
  1836. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1837. // creation from this context.
  1838. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1839. if (!IDecl && DoTypoCorrection) {
  1840. // Perform typo correction at the given location, but only if we
  1841. // find an Objective-C class name.
  1842. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  1843. if (TypoCorrection C =
  1844. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  1845. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  1846. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1847. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1848. Id = IDecl->getIdentifier();
  1849. }
  1850. }
  1851. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1852. // This routine must always return a class definition, if any.
  1853. if (Def && Def->getDefinition())
  1854. Def = Def->getDefinition();
  1855. return Def;
  1856. }
  1857. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1858. /// from S, where a non-field would be declared. This routine copes
  1859. /// with the difference between C and C++ scoping rules in structs and
  1860. /// unions. For example, the following code is well-formed in C but
  1861. /// ill-formed in C++:
  1862. /// @code
  1863. /// struct S6 {
  1864. /// enum { BAR } e;
  1865. /// };
  1866. ///
  1867. /// void test_S6() {
  1868. /// struct S6 a;
  1869. /// a.e = BAR;
  1870. /// }
  1871. /// @endcode
  1872. /// For the declaration of BAR, this routine will return a different
  1873. /// scope. The scope S will be the scope of the unnamed enumeration
  1874. /// within S6. In C++, this routine will return the scope associated
  1875. /// with S6, because the enumeration's scope is a transparent
  1876. /// context but structures can contain non-field names. In C, this
  1877. /// routine will return the translation unit scope, since the
  1878. /// enumeration's scope is a transparent context and structures cannot
  1879. /// contain non-field names.
  1880. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1881. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1882. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1883. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1884. S = S->getParent();
  1885. return S;
  1886. }
  1887. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1888. ASTContext::GetBuiltinTypeError Error) {
  1889. switch (Error) {
  1890. case ASTContext::GE_None:
  1891. return "";
  1892. case ASTContext::GE_Missing_type:
  1893. return BuiltinInfo.getHeaderName(ID);
  1894. case ASTContext::GE_Missing_stdio:
  1895. return "stdio.h";
  1896. case ASTContext::GE_Missing_setjmp:
  1897. return "setjmp.h";
  1898. case ASTContext::GE_Missing_ucontext:
  1899. return "ucontext.h";
  1900. }
  1901. llvm_unreachable("unhandled error kind");
  1902. }
  1903. FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
  1904. unsigned ID, SourceLocation Loc) {
  1905. DeclContext *Parent = Context.getTranslationUnitDecl();
  1906. if (getLangOpts().CPlusPlus) {
  1907. LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
  1908. Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
  1909. CLinkageDecl->setImplicit();
  1910. Parent->addDecl(CLinkageDecl);
  1911. Parent = CLinkageDecl;
  1912. }
  1913. FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
  1914. /*TInfo=*/nullptr, SC_Extern,
  1915. getCurFPFeatures().isFPConstrained(),
  1916. false, Type->isFunctionProtoType());
  1917. New->setImplicit();
  1918. New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
  1919. // Create Decl objects for each parameter, adding them to the
  1920. // FunctionDecl.
  1921. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
  1922. SmallVector<ParmVarDecl *, 16> Params;
  1923. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1924. ParmVarDecl *parm = ParmVarDecl::Create(
  1925. Context, New, SourceLocation(), SourceLocation(), nullptr,
  1926. FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
  1927. parm->setScopeInfo(0, i);
  1928. Params.push_back(parm);
  1929. }
  1930. New->setParams(Params);
  1931. }
  1932. AddKnownFunctionAttributes(New);
  1933. return New;
  1934. }
  1935. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1936. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1937. /// if we're creating this built-in in anticipation of redeclaring the
  1938. /// built-in.
  1939. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1940. Scope *S, bool ForRedeclaration,
  1941. SourceLocation Loc) {
  1942. LookupNecessaryTypesForBuiltin(S, ID);
  1943. ASTContext::GetBuiltinTypeError Error;
  1944. QualType R = Context.GetBuiltinType(ID, Error);
  1945. if (Error) {
  1946. if (!ForRedeclaration)
  1947. return nullptr;
  1948. // If we have a builtin without an associated type we should not emit a
  1949. // warning when we were not able to find a type for it.
  1950. if (Error == ASTContext::GE_Missing_type ||
  1951. Context.BuiltinInfo.allowTypeMismatch(ID))
  1952. return nullptr;
  1953. // If we could not find a type for setjmp it is because the jmp_buf type was
  1954. // not defined prior to the setjmp declaration.
  1955. if (Error == ASTContext::GE_Missing_setjmp) {
  1956. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  1957. << Context.BuiltinInfo.getName(ID);
  1958. return nullptr;
  1959. }
  1960. // Generally, we emit a warning that the declaration requires the
  1961. // appropriate header.
  1962. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1963. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1964. << Context.BuiltinInfo.getName(ID);
  1965. return nullptr;
  1966. }
  1967. if (!ForRedeclaration &&
  1968. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1969. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1970. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1971. << Context.BuiltinInfo.getName(ID) << R;
  1972. if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
  1973. Diag(Loc, diag::note_include_header_or_declare)
  1974. << Header << Context.BuiltinInfo.getName(ID);
  1975. }
  1976. if (R.isNull())
  1977. return nullptr;
  1978. FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
  1979. RegisterLocallyScopedExternCDecl(New, S);
  1980. // TUScope is the translation-unit scope to insert this function into.
  1981. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1982. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1983. // entirely, but we're not there yet.
  1984. DeclContext *SavedContext = CurContext;
  1985. CurContext = New->getDeclContext();
  1986. PushOnScopeChains(New, TUScope);
  1987. CurContext = SavedContext;
  1988. return New;
  1989. }
  1990. /// Typedef declarations don't have linkage, but they still denote the same
  1991. /// entity if their types are the same.
  1992. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1993. /// isSameEntity.
  1994. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1995. TypedefNameDecl *Decl,
  1996. LookupResult &Previous) {
  1997. // This is only interesting when modules are enabled.
  1998. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1999. return;
  2000. // Empty sets are uninteresting.
  2001. if (Previous.empty())
  2002. return;
  2003. LookupResult::Filter Filter = Previous.makeFilter();
  2004. while (Filter.hasNext()) {
  2005. NamedDecl *Old = Filter.next();
  2006. // Non-hidden declarations are never ignored.
  2007. if (S.isVisible(Old))
  2008. continue;
  2009. // Declarations of the same entity are not ignored, even if they have
  2010. // different linkages.
  2011. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  2012. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  2013. Decl->getUnderlyingType()))
  2014. continue;
  2015. // If both declarations give a tag declaration a typedef name for linkage
  2016. // purposes, then they declare the same entity.
  2017. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  2018. Decl->getAnonDeclWithTypedefName())
  2019. continue;
  2020. }
  2021. Filter.erase();
  2022. }
  2023. Filter.done();
  2024. }
  2025. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  2026. QualType OldType;
  2027. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  2028. OldType = OldTypedef->getUnderlyingType();
  2029. else
  2030. OldType = Context.getTypeDeclType(Old);
  2031. QualType NewType = New->getUnderlyingType();
  2032. if (NewType->isVariablyModifiedType()) {
  2033. // Must not redefine a typedef with a variably-modified type.
  2034. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  2035. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  2036. << Kind << NewType;
  2037. if (Old->getLocation().isValid())
  2038. notePreviousDefinition(Old, New->getLocation());
  2039. New->setInvalidDecl();
  2040. return true;
  2041. }
  2042. if (OldType != NewType &&
  2043. !OldType->isDependentType() &&
  2044. !NewType->isDependentType() &&
  2045. !Context.hasSameType(OldType, NewType)) {
  2046. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  2047. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  2048. << Kind << NewType << OldType;
  2049. if (Old->getLocation().isValid())
  2050. notePreviousDefinition(Old, New->getLocation());
  2051. New->setInvalidDecl();
  2052. return true;
  2053. }
  2054. return false;
  2055. }
  2056. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  2057. /// same name and scope as a previous declaration 'Old'. Figure out
  2058. /// how to resolve this situation, merging decls or emitting
  2059. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  2060. ///
  2061. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  2062. LookupResult &OldDecls) {
  2063. // If the new decl is known invalid already, don't bother doing any
  2064. // merging checks.
  2065. if (New->isInvalidDecl()) return;
  2066. // Allow multiple definitions for ObjC built-in typedefs.
  2067. // FIXME: Verify the underlying types are equivalent!
  2068. if (getLangOpts().ObjC) {
  2069. const IdentifierInfo *TypeID = New->getIdentifier();
  2070. switch (TypeID->getLength()) {
  2071. default: break;
  2072. case 2:
  2073. {
  2074. if (!TypeID->isStr("id"))
  2075. break;
  2076. QualType T = New->getUnderlyingType();
  2077. if (!T->isPointerType())
  2078. break;
  2079. if (!T->isVoidPointerType()) {
  2080. QualType PT = T->castAs<PointerType>()->getPointeeType();
  2081. if (!PT->isStructureType())
  2082. break;
  2083. }
  2084. Context.setObjCIdRedefinitionType(T);
  2085. // Install the built-in type for 'id', ignoring the current definition.
  2086. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  2087. return;
  2088. }
  2089. case 5:
  2090. if (!TypeID->isStr("Class"))
  2091. break;
  2092. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  2093. // Install the built-in type for 'Class', ignoring the current definition.
  2094. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  2095. return;
  2096. case 3:
  2097. if (!TypeID->isStr("SEL"))
  2098. break;
  2099. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  2100. // Install the built-in type for 'SEL', ignoring the current definition.
  2101. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  2102. return;
  2103. }
  2104. // Fall through - the typedef name was not a builtin type.
  2105. }
  2106. // Verify the old decl was also a type.
  2107. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  2108. if (!Old) {
  2109. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2110. << New->getDeclName();
  2111. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  2112. if (OldD->getLocation().isValid())
  2113. notePreviousDefinition(OldD, New->getLocation());
  2114. return New->setInvalidDecl();
  2115. }
  2116. // If the old declaration is invalid, just give up here.
  2117. if (Old->isInvalidDecl())
  2118. return New->setInvalidDecl();
  2119. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  2120. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  2121. auto *NewTag = New->getAnonDeclWithTypedefName();
  2122. NamedDecl *Hidden = nullptr;
  2123. if (OldTag && NewTag &&
  2124. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  2125. !hasVisibleDefinition(OldTag, &Hidden)) {
  2126. // There is a definition of this tag, but it is not visible. Use it
  2127. // instead of our tag.
  2128. New->setTypeForDecl(OldTD->getTypeForDecl());
  2129. if (OldTD->isModed())
  2130. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  2131. OldTD->getUnderlyingType());
  2132. else
  2133. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  2134. // Make the old tag definition visible.
  2135. makeMergedDefinitionVisible(Hidden);
  2136. // If this was an unscoped enumeration, yank all of its enumerators
  2137. // out of the scope.
  2138. if (isa<EnumDecl>(NewTag)) {
  2139. Scope *EnumScope = getNonFieldDeclScope(S);
  2140. for (auto *D : NewTag->decls()) {
  2141. auto *ED = cast<EnumConstantDecl>(D);
  2142. assert(EnumScope->isDeclScope(ED));
  2143. EnumScope->RemoveDecl(ED);
  2144. IdResolver.RemoveDecl(ED);
  2145. ED->getLexicalDeclContext()->removeDecl(ED);
  2146. }
  2147. }
  2148. }
  2149. }
  2150. // If the typedef types are not identical, reject them in all languages and
  2151. // with any extensions enabled.
  2152. if (isIncompatibleTypedef(Old, New))
  2153. return;
  2154. // The types match. Link up the redeclaration chain and merge attributes if
  2155. // the old declaration was a typedef.
  2156. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  2157. New->setPreviousDecl(Typedef);
  2158. mergeDeclAttributes(New, Old);
  2159. }
  2160. if (getLangOpts().MicrosoftExt)
  2161. return;
  2162. if (getLangOpts().CPlusPlus) {
  2163. // C++ [dcl.typedef]p2:
  2164. // In a given non-class scope, a typedef specifier can be used to
  2165. // redefine the name of any type declared in that scope to refer
  2166. // to the type to which it already refers.
  2167. if (!isa<CXXRecordDecl>(CurContext))
  2168. return;
  2169. // C++0x [dcl.typedef]p4:
  2170. // In a given class scope, a typedef specifier can be used to redefine
  2171. // any class-name declared in that scope that is not also a typedef-name
  2172. // to refer to the type to which it already refers.
  2173. //
  2174. // This wording came in via DR424, which was a correction to the
  2175. // wording in DR56, which accidentally banned code like:
  2176. //
  2177. // struct S {
  2178. // typedef struct A { } A;
  2179. // };
  2180. //
  2181. // in the C++03 standard. We implement the C++0x semantics, which
  2182. // allow the above but disallow
  2183. //
  2184. // struct S {
  2185. // typedef int I;
  2186. // typedef int I;
  2187. // };
  2188. //
  2189. // since that was the intent of DR56.
  2190. if (!isa<TypedefNameDecl>(Old))
  2191. return;
  2192. Diag(New->getLocation(), diag::err_redefinition)
  2193. << New->getDeclName();
  2194. notePreviousDefinition(Old, New->getLocation());
  2195. return New->setInvalidDecl();
  2196. }
  2197. // Modules always permit redefinition of typedefs, as does C11.
  2198. if (getLangOpts().Modules || getLangOpts().C11)
  2199. return;
  2200. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2201. // is normally mapped to an error, but can be controlled with
  2202. // -Wtypedef-redefinition. If either the original or the redefinition is
  2203. // in a system header, don't emit this for compatibility with GCC.
  2204. if (getDiagnostics().getSuppressSystemWarnings() &&
  2205. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2206. (Old->isImplicit() ||
  2207. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2208. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2209. return;
  2210. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2211. << New->getDeclName();
  2212. notePreviousDefinition(Old, New->getLocation());
  2213. }
  2214. /// DeclhasAttr - returns true if decl Declaration already has the target
  2215. /// attribute.
  2216. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2217. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2218. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2219. for (const auto *i : D->attrs())
  2220. if (i->getKind() == A->getKind()) {
  2221. if (Ann) {
  2222. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2223. return true;
  2224. continue;
  2225. }
  2226. // FIXME: Don't hardcode this check
  2227. if (OA && isa<OwnershipAttr>(i))
  2228. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2229. return true;
  2230. }
  2231. return false;
  2232. }
  2233. static bool isAttributeTargetADefinition(Decl *D) {
  2234. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2235. return VD->isThisDeclarationADefinition();
  2236. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2237. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2238. return true;
  2239. }
  2240. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2241. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2242. ///
  2243. /// \return \c true if any attributes were added to \p New.
  2244. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2245. // Look for alignas attributes on Old, and pick out whichever attribute
  2246. // specifies the strictest alignment requirement.
  2247. AlignedAttr *OldAlignasAttr = nullptr;
  2248. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2249. unsigned OldAlign = 0;
  2250. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2251. // FIXME: We have no way of representing inherited dependent alignments
  2252. // in a case like:
  2253. // template<int A, int B> struct alignas(A) X;
  2254. // template<int A, int B> struct alignas(B) X {};
  2255. // For now, we just ignore any alignas attributes which are not on the
  2256. // definition in such a case.
  2257. if (I->isAlignmentDependent())
  2258. return false;
  2259. if (I->isAlignas())
  2260. OldAlignasAttr = I;
  2261. unsigned Align = I->getAlignment(S.Context);
  2262. if (Align > OldAlign) {
  2263. OldAlign = Align;
  2264. OldStrictestAlignAttr = I;
  2265. }
  2266. }
  2267. // Look for alignas attributes on New.
  2268. AlignedAttr *NewAlignasAttr = nullptr;
  2269. unsigned NewAlign = 0;
  2270. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2271. if (I->isAlignmentDependent())
  2272. return false;
  2273. if (I->isAlignas())
  2274. NewAlignasAttr = I;
  2275. unsigned Align = I->getAlignment(S.Context);
  2276. if (Align > NewAlign)
  2277. NewAlign = Align;
  2278. }
  2279. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2280. // Both declarations have 'alignas' attributes. We require them to match.
  2281. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2282. // fall short. (If two declarations both have alignas, they must both match
  2283. // every definition, and so must match each other if there is a definition.)
  2284. // If either declaration only contains 'alignas(0)' specifiers, then it
  2285. // specifies the natural alignment for the type.
  2286. if (OldAlign == 0 || NewAlign == 0) {
  2287. QualType Ty;
  2288. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2289. Ty = VD->getType();
  2290. else
  2291. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2292. if (OldAlign == 0)
  2293. OldAlign = S.Context.getTypeAlign(Ty);
  2294. if (NewAlign == 0)
  2295. NewAlign = S.Context.getTypeAlign(Ty);
  2296. }
  2297. if (OldAlign != NewAlign) {
  2298. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2299. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2300. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2301. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2302. }
  2303. }
  2304. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2305. // C++11 [dcl.align]p6:
  2306. // if any declaration of an entity has an alignment-specifier,
  2307. // every defining declaration of that entity shall specify an
  2308. // equivalent alignment.
  2309. // C11 6.7.5/7:
  2310. // If the definition of an object does not have an alignment
  2311. // specifier, any other declaration of that object shall also
  2312. // have no alignment specifier.
  2313. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2314. << OldAlignasAttr;
  2315. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2316. << OldAlignasAttr;
  2317. }
  2318. bool AnyAdded = false;
  2319. // Ensure we have an attribute representing the strictest alignment.
  2320. if (OldAlign > NewAlign) {
  2321. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2322. Clone->setInherited(true);
  2323. New->addAttr(Clone);
  2324. AnyAdded = true;
  2325. }
  2326. // Ensure we have an alignas attribute if the old declaration had one.
  2327. if (OldAlignasAttr && !NewAlignasAttr &&
  2328. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2329. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2330. Clone->setInherited(true);
  2331. New->addAttr(Clone);
  2332. AnyAdded = true;
  2333. }
  2334. return AnyAdded;
  2335. }
  2336. #define WANT_DECL_MERGE_LOGIC
  2337. #include "clang/Sema/AttrParsedAttrImpl.inc"
  2338. #undef WANT_DECL_MERGE_LOGIC
  2339. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2340. const InheritableAttr *Attr,
  2341. Sema::AvailabilityMergeKind AMK) {
  2342. // Diagnose any mutual exclusions between the attribute that we want to add
  2343. // and attributes that already exist on the declaration.
  2344. if (!DiagnoseMutualExclusions(S, D, Attr))
  2345. return false;
  2346. // This function copies an attribute Attr from a previous declaration to the
  2347. // new declaration D if the new declaration doesn't itself have that attribute
  2348. // yet or if that attribute allows duplicates.
  2349. // If you're adding a new attribute that requires logic different from
  2350. // "use explicit attribute on decl if present, else use attribute from
  2351. // previous decl", for example if the attribute needs to be consistent
  2352. // between redeclarations, you need to call a custom merge function here.
  2353. InheritableAttr *NewAttr = nullptr;
  2354. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2355. NewAttr = S.mergeAvailabilityAttr(
  2356. D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
  2357. AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
  2358. AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
  2359. AA->getPriority());
  2360. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2361. NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
  2362. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2363. NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
  2364. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2365. NewAttr = S.mergeDLLImportAttr(D, *ImportA);
  2366. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2367. NewAttr = S.mergeDLLExportAttr(D, *ExportA);
  2368. else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
  2369. NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
  2370. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2371. NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
  2372. FA->getFirstArg());
  2373. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2374. NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
  2375. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2376. NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
  2377. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2378. NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
  2379. IA->getInheritanceModel());
  2380. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2381. NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
  2382. &S.Context.Idents.get(AA->getSpelling()));
  2383. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2384. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2385. isa<CUDAGlobalAttr>(Attr))) {
  2386. // CUDA target attributes are part of function signature for
  2387. // overloading purposes and must not be merged.
  2388. return false;
  2389. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2390. NewAttr = S.mergeMinSizeAttr(D, *MA);
  2391. else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
  2392. NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
  2393. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2394. NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
  2395. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2396. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2397. else if (isa<AlignedAttr>(Attr))
  2398. // AlignedAttrs are handled separately, because we need to handle all
  2399. // such attributes on a declaration at the same time.
  2400. NewAttr = nullptr;
  2401. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2402. (AMK == Sema::AMK_Override ||
  2403. AMK == Sema::AMK_ProtocolImplementation ||
  2404. AMK == Sema::AMK_OptionalProtocolImplementation))
  2405. NewAttr = nullptr;
  2406. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2407. NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
  2408. else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
  2409. NewAttr = S.mergeImportModuleAttr(D, *IMA);
  2410. else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
  2411. NewAttr = S.mergeImportNameAttr(D, *INA);
  2412. else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
  2413. NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
  2414. else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
  2415. NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
  2416. else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
  2417. NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
  2418. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2419. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2420. if (NewAttr) {
  2421. NewAttr->setInherited(true);
  2422. D->addAttr(NewAttr);
  2423. if (isa<MSInheritanceAttr>(NewAttr))
  2424. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2425. return true;
  2426. }
  2427. return false;
  2428. }
  2429. static const NamedDecl *getDefinition(const Decl *D) {
  2430. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2431. return TD->getDefinition();
  2432. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2433. const VarDecl *Def = VD->getDefinition();
  2434. if (Def)
  2435. return Def;
  2436. return VD->getActingDefinition();
  2437. }
  2438. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2439. const FunctionDecl *Def = nullptr;
  2440. if (FD->isDefined(Def, true))
  2441. return Def;
  2442. }
  2443. return nullptr;
  2444. }
  2445. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2446. for (const auto *Attribute : D->attrs())
  2447. if (Attribute->getKind() == Kind)
  2448. return true;
  2449. return false;
  2450. }
  2451. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2452. /// there are no new attributes in this declaration.
  2453. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2454. if (!New->hasAttrs())
  2455. return;
  2456. const NamedDecl *Def = getDefinition(Old);
  2457. if (!Def || Def == New)
  2458. return;
  2459. AttrVec &NewAttributes = New->getAttrs();
  2460. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2461. const Attr *NewAttribute = NewAttributes[I];
  2462. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2463. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2464. Sema::SkipBodyInfo SkipBody;
  2465. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2466. // If we're skipping this definition, drop the "alias" attribute.
  2467. if (SkipBody.ShouldSkip) {
  2468. NewAttributes.erase(NewAttributes.begin() + I);
  2469. --E;
  2470. continue;
  2471. }
  2472. } else {
  2473. VarDecl *VD = cast<VarDecl>(New);
  2474. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2475. VarDecl::TentativeDefinition
  2476. ? diag::err_alias_after_tentative
  2477. : diag::err_redefinition;
  2478. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2479. if (Diag == diag::err_redefinition)
  2480. S.notePreviousDefinition(Def, VD->getLocation());
  2481. else
  2482. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2483. VD->setInvalidDecl();
  2484. }
  2485. ++I;
  2486. continue;
  2487. }
  2488. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2489. // Tentative definitions are only interesting for the alias check above.
  2490. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2491. ++I;
  2492. continue;
  2493. }
  2494. }
  2495. if (hasAttribute(Def, NewAttribute->getKind())) {
  2496. ++I;
  2497. continue; // regular attr merging will take care of validating this.
  2498. }
  2499. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2500. // C's _Noreturn is allowed to be added to a function after it is defined.
  2501. ++I;
  2502. continue;
  2503. } else if (isa<UuidAttr>(NewAttribute)) {
  2504. // msvc will allow a subsequent definition to add an uuid to a class
  2505. ++I;
  2506. continue;
  2507. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2508. if (AA->isAlignas()) {
  2509. // C++11 [dcl.align]p6:
  2510. // if any declaration of an entity has an alignment-specifier,
  2511. // every defining declaration of that entity shall specify an
  2512. // equivalent alignment.
  2513. // C11 6.7.5/7:
  2514. // If the definition of an object does not have an alignment
  2515. // specifier, any other declaration of that object shall also
  2516. // have no alignment specifier.
  2517. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2518. << AA;
  2519. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2520. << AA;
  2521. NewAttributes.erase(NewAttributes.begin() + I);
  2522. --E;
  2523. continue;
  2524. }
  2525. } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
  2526. // If there is a C definition followed by a redeclaration with this
  2527. // attribute then there are two different definitions. In C++, prefer the
  2528. // standard diagnostics.
  2529. if (!S.getLangOpts().CPlusPlus) {
  2530. S.Diag(NewAttribute->getLocation(),
  2531. diag::err_loader_uninitialized_redeclaration);
  2532. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2533. NewAttributes.erase(NewAttributes.begin() + I);
  2534. --E;
  2535. continue;
  2536. }
  2537. } else if (isa<SelectAnyAttr>(NewAttribute) &&
  2538. cast<VarDecl>(New)->isInline() &&
  2539. !cast<VarDecl>(New)->isInlineSpecified()) {
  2540. // Don't warn about applying selectany to implicitly inline variables.
  2541. // Older compilers and language modes would require the use of selectany
  2542. // to make such variables inline, and it would have no effect if we
  2543. // honored it.
  2544. ++I;
  2545. continue;
  2546. } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
  2547. // We allow to add OMP[Begin]DeclareVariantAttr to be added to
  2548. // declarations after defintions.
  2549. ++I;
  2550. continue;
  2551. }
  2552. S.Diag(NewAttribute->getLocation(),
  2553. diag::warn_attribute_precede_definition);
  2554. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2555. NewAttributes.erase(NewAttributes.begin() + I);
  2556. --E;
  2557. }
  2558. }
  2559. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2560. const ConstInitAttr *CIAttr,
  2561. bool AttrBeforeInit) {
  2562. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2563. // Figure out a good way to write this specifier on the old declaration.
  2564. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2565. // enough of the attribute list spelling information to extract that without
  2566. // heroics.
  2567. std::string SuitableSpelling;
  2568. if (S.getLangOpts().CPlusPlus20)
  2569. SuitableSpelling = std::string(
  2570. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
  2571. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2572. SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
  2573. InsertLoc, {tok::l_square, tok::l_square,
  2574. S.PP.getIdentifierInfo("clang"), tok::coloncolon,
  2575. S.PP.getIdentifierInfo("require_constant_initialization"),
  2576. tok::r_square, tok::r_square}));
  2577. if (SuitableSpelling.empty())
  2578. SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
  2579. InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2580. S.PP.getIdentifierInfo("require_constant_initialization"),
  2581. tok::r_paren, tok::r_paren}));
  2582. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
  2583. SuitableSpelling = "constinit";
  2584. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2585. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2586. if (SuitableSpelling.empty())
  2587. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2588. SuitableSpelling += " ";
  2589. if (AttrBeforeInit) {
  2590. // extern constinit int a;
  2591. // int a = 0; // error (missing 'constinit'), accepted as extension
  2592. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2593. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2594. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2595. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2596. } else {
  2597. // int a = 0;
  2598. // constinit extern int a; // error (missing 'constinit')
  2599. S.Diag(CIAttr->getLocation(),
  2600. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2601. : diag::warn_require_const_init_added_too_late)
  2602. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2603. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2604. << CIAttr->isConstinit()
  2605. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2606. }
  2607. }
  2608. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2609. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2610. AvailabilityMergeKind AMK) {
  2611. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2612. UsedAttr *NewAttr = OldAttr->clone(Context);
  2613. NewAttr->setInherited(true);
  2614. New->addAttr(NewAttr);
  2615. }
  2616. if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
  2617. RetainAttr *NewAttr = OldAttr->clone(Context);
  2618. NewAttr->setInherited(true);
  2619. New->addAttr(NewAttr);
  2620. }
  2621. if (!Old->hasAttrs() && !New->hasAttrs())
  2622. return;
  2623. // [dcl.constinit]p1:
  2624. // If the [constinit] specifier is applied to any declaration of a
  2625. // variable, it shall be applied to the initializing declaration.
  2626. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2627. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2628. if (bool(OldConstInit) != bool(NewConstInit)) {
  2629. const auto *OldVD = cast<VarDecl>(Old);
  2630. auto *NewVD = cast<VarDecl>(New);
  2631. // Find the initializing declaration. Note that we might not have linked
  2632. // the new declaration into the redeclaration chain yet.
  2633. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2634. if (!InitDecl &&
  2635. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2636. InitDecl = NewVD;
  2637. if (InitDecl == NewVD) {
  2638. // This is the initializing declaration. If it would inherit 'constinit',
  2639. // that's ill-formed. (Note that we do not apply this to the attribute
  2640. // form).
  2641. if (OldConstInit && OldConstInit->isConstinit())
  2642. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2643. /*AttrBeforeInit=*/true);
  2644. } else if (NewConstInit) {
  2645. // This is the first time we've been told that this declaration should
  2646. // have a constant initializer. If we already saw the initializing
  2647. // declaration, this is too late.
  2648. if (InitDecl && InitDecl != NewVD) {
  2649. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2650. /*AttrBeforeInit=*/false);
  2651. NewVD->dropAttr<ConstInitAttr>();
  2652. }
  2653. }
  2654. }
  2655. // Attributes declared post-definition are currently ignored.
  2656. checkNewAttributesAfterDef(*this, New, Old);
  2657. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2658. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2659. if (!OldA->isEquivalent(NewA)) {
  2660. // This redeclaration changes __asm__ label.
  2661. Diag(New->getLocation(), diag::err_different_asm_label);
  2662. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2663. }
  2664. } else if (Old->isUsed()) {
  2665. // This redeclaration adds an __asm__ label to a declaration that has
  2666. // already been ODR-used.
  2667. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2668. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2669. }
  2670. }
  2671. // Re-declaration cannot add abi_tag's.
  2672. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2673. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2674. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2675. if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
  2676. Diag(NewAbiTagAttr->getLocation(),
  2677. diag::err_new_abi_tag_on_redeclaration)
  2678. << NewTag;
  2679. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2680. }
  2681. }
  2682. } else {
  2683. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2684. Diag(Old->getLocation(), diag::note_previous_declaration);
  2685. }
  2686. }
  2687. // This redeclaration adds a section attribute.
  2688. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2689. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2690. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2691. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2692. Diag(Old->getLocation(), diag::note_previous_declaration);
  2693. }
  2694. }
  2695. }
  2696. // Redeclaration adds code-seg attribute.
  2697. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2698. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2699. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2700. Diag(New->getLocation(), diag::warn_mismatched_section)
  2701. << 0 /*codeseg*/;
  2702. Diag(Old->getLocation(), diag::note_previous_declaration);
  2703. }
  2704. if (!Old->hasAttrs())
  2705. return;
  2706. bool foundAny = New->hasAttrs();
  2707. // Ensure that any moving of objects within the allocated map is done before
  2708. // we process them.
  2709. if (!foundAny) New->setAttrs(AttrVec());
  2710. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2711. // Ignore deprecated/unavailable/availability attributes if requested.
  2712. AvailabilityMergeKind LocalAMK = AMK_None;
  2713. if (isa<DeprecatedAttr>(I) ||
  2714. isa<UnavailableAttr>(I) ||
  2715. isa<AvailabilityAttr>(I)) {
  2716. switch (AMK) {
  2717. case AMK_None:
  2718. continue;
  2719. case AMK_Redeclaration:
  2720. case AMK_Override:
  2721. case AMK_ProtocolImplementation:
  2722. case AMK_OptionalProtocolImplementation:
  2723. LocalAMK = AMK;
  2724. break;
  2725. }
  2726. }
  2727. // Already handled.
  2728. if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
  2729. continue;
  2730. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2731. foundAny = true;
  2732. }
  2733. if (mergeAlignedAttrs(*this, New, Old))
  2734. foundAny = true;
  2735. if (!foundAny) New->dropAttrs();
  2736. }
  2737. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2738. /// to the new one.
  2739. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2740. const ParmVarDecl *oldDecl,
  2741. Sema &S) {
  2742. // C++11 [dcl.attr.depend]p2:
  2743. // The first declaration of a function shall specify the
  2744. // carries_dependency attribute for its declarator-id if any declaration
  2745. // of the function specifies the carries_dependency attribute.
  2746. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2747. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2748. S.Diag(CDA->getLocation(),
  2749. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2750. // Find the first declaration of the parameter.
  2751. // FIXME: Should we build redeclaration chains for function parameters?
  2752. const FunctionDecl *FirstFD =
  2753. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2754. const ParmVarDecl *FirstVD =
  2755. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2756. S.Diag(FirstVD->getLocation(),
  2757. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2758. }
  2759. if (!oldDecl->hasAttrs())
  2760. return;
  2761. bool foundAny = newDecl->hasAttrs();
  2762. // Ensure that any moving of objects within the allocated map is
  2763. // done before we process them.
  2764. if (!foundAny) newDecl->setAttrs(AttrVec());
  2765. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2766. if (!DeclHasAttr(newDecl, I)) {
  2767. InheritableAttr *newAttr =
  2768. cast<InheritableParamAttr>(I->clone(S.Context));
  2769. newAttr->setInherited(true);
  2770. newDecl->addAttr(newAttr);
  2771. foundAny = true;
  2772. }
  2773. }
  2774. if (!foundAny) newDecl->dropAttrs();
  2775. }
  2776. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2777. const ParmVarDecl *OldParam,
  2778. Sema &S) {
  2779. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2780. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2781. if (*Oldnullability != *Newnullability) {
  2782. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2783. << DiagNullabilityKind(
  2784. *Newnullability,
  2785. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2786. != 0))
  2787. << DiagNullabilityKind(
  2788. *Oldnullability,
  2789. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2790. != 0));
  2791. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2792. }
  2793. } else {
  2794. QualType NewT = NewParam->getType();
  2795. NewT = S.Context.getAttributedType(
  2796. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2797. NewT, NewT);
  2798. NewParam->setType(NewT);
  2799. }
  2800. }
  2801. }
  2802. namespace {
  2803. /// Used in MergeFunctionDecl to keep track of function parameters in
  2804. /// C.
  2805. struct GNUCompatibleParamWarning {
  2806. ParmVarDecl *OldParm;
  2807. ParmVarDecl *NewParm;
  2808. QualType PromotedType;
  2809. };
  2810. } // end anonymous namespace
  2811. // Determine whether the previous declaration was a definition, implicit
  2812. // declaration, or a declaration.
  2813. template <typename T>
  2814. static std::pair<diag::kind, SourceLocation>
  2815. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2816. diag::kind PrevDiag;
  2817. SourceLocation OldLocation = Old->getLocation();
  2818. if (Old->isThisDeclarationADefinition())
  2819. PrevDiag = diag::note_previous_definition;
  2820. else if (Old->isImplicit()) {
  2821. PrevDiag = diag::note_previous_implicit_declaration;
  2822. if (OldLocation.isInvalid())
  2823. OldLocation = New->getLocation();
  2824. } else
  2825. PrevDiag = diag::note_previous_declaration;
  2826. return std::make_pair(PrevDiag, OldLocation);
  2827. }
  2828. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2829. /// only extern inline functions can be redefined, and even then only in
  2830. /// GNU89 mode.
  2831. static bool canRedefineFunction(const FunctionDecl *FD,
  2832. const LangOptions& LangOpts) {
  2833. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2834. !LangOpts.CPlusPlus &&
  2835. FD->isInlineSpecified() &&
  2836. FD->getStorageClass() == SC_Extern);
  2837. }
  2838. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2839. const AttributedType *AT = T->getAs<AttributedType>();
  2840. while (AT && !AT->isCallingConv())
  2841. AT = AT->getModifiedType()->getAs<AttributedType>();
  2842. return AT;
  2843. }
  2844. template <typename T>
  2845. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2846. const DeclContext *DC = Old->getDeclContext();
  2847. if (DC->isRecord())
  2848. return false;
  2849. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2850. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2851. return true;
  2852. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2853. return true;
  2854. return false;
  2855. }
  2856. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2857. static bool isExternC(VarTemplateDecl *) { return false; }
  2858. static bool isExternC(FunctionTemplateDecl *) { return false; }
  2859. /// Check whether a redeclaration of an entity introduced by a
  2860. /// using-declaration is valid, given that we know it's not an overload
  2861. /// (nor a hidden tag declaration).
  2862. template<typename ExpectedDecl>
  2863. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2864. ExpectedDecl *New) {
  2865. // C++11 [basic.scope.declarative]p4:
  2866. // Given a set of declarations in a single declarative region, each of
  2867. // which specifies the same unqualified name,
  2868. // -- they shall all refer to the same entity, or all refer to functions
  2869. // and function templates; or
  2870. // -- exactly one declaration shall declare a class name or enumeration
  2871. // name that is not a typedef name and the other declarations shall all
  2872. // refer to the same variable or enumerator, or all refer to functions
  2873. // and function templates; in this case the class name or enumeration
  2874. // name is hidden (3.3.10).
  2875. // C++11 [namespace.udecl]p14:
  2876. // If a function declaration in namespace scope or block scope has the
  2877. // same name and the same parameter-type-list as a function introduced
  2878. // by a using-declaration, and the declarations do not declare the same
  2879. // function, the program is ill-formed.
  2880. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2881. if (Old &&
  2882. !Old->getDeclContext()->getRedeclContext()->Equals(
  2883. New->getDeclContext()->getRedeclContext()) &&
  2884. !(isExternC(Old) && isExternC(New)))
  2885. Old = nullptr;
  2886. if (!Old) {
  2887. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2888. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2889. S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
  2890. return true;
  2891. }
  2892. return false;
  2893. }
  2894. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2895. const FunctionDecl *B) {
  2896. assert(A->getNumParams() == B->getNumParams());
  2897. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2898. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2899. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2900. if (AttrA == AttrB)
  2901. return true;
  2902. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  2903. AttrA->isDynamic() == AttrB->isDynamic();
  2904. };
  2905. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2906. }
  2907. /// If necessary, adjust the semantic declaration context for a qualified
  2908. /// declaration to name the correct inline namespace within the qualifier.
  2909. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2910. DeclaratorDecl *OldD) {
  2911. // The only case where we need to update the DeclContext is when
  2912. // redeclaration lookup for a qualified name finds a declaration
  2913. // in an inline namespace within the context named by the qualifier:
  2914. //
  2915. // inline namespace N { int f(); }
  2916. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2917. //
  2918. // For unqualified declarations, the semantic context *can* change
  2919. // along the redeclaration chain (for local extern declarations,
  2920. // extern "C" declarations, and friend declarations in particular).
  2921. if (!NewD->getQualifier())
  2922. return;
  2923. // NewD is probably already in the right context.
  2924. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2925. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2926. if (NamedDC->Equals(SemaDC))
  2927. return;
  2928. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2929. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2930. "unexpected context for redeclaration");
  2931. auto *LexDC = NewD->getLexicalDeclContext();
  2932. auto FixSemaDC = [=](NamedDecl *D) {
  2933. if (!D)
  2934. return;
  2935. D->setDeclContext(SemaDC);
  2936. D->setLexicalDeclContext(LexDC);
  2937. };
  2938. FixSemaDC(NewD);
  2939. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2940. FixSemaDC(FD->getDescribedFunctionTemplate());
  2941. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2942. FixSemaDC(VD->getDescribedVarTemplate());
  2943. }
  2944. /// MergeFunctionDecl - We just parsed a function 'New' from
  2945. /// declarator D which has the same name and scope as a previous
  2946. /// declaration 'Old'. Figure out how to resolve this situation,
  2947. /// merging decls or emitting diagnostics as appropriate.
  2948. ///
  2949. /// In C++, New and Old must be declarations that are not
  2950. /// overloaded. Use IsOverload to determine whether New and Old are
  2951. /// overloaded, and to select the Old declaration that New should be
  2952. /// merged with.
  2953. ///
  2954. /// Returns true if there was an error, false otherwise.
  2955. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2956. Scope *S, bool MergeTypeWithOld) {
  2957. // Verify the old decl was also a function.
  2958. FunctionDecl *Old = OldD->getAsFunction();
  2959. if (!Old) {
  2960. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2961. if (New->getFriendObjectKind()) {
  2962. Diag(New->getLocation(), diag::err_using_decl_friend);
  2963. Diag(Shadow->getTargetDecl()->getLocation(),
  2964. diag::note_using_decl_target);
  2965. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
  2966. << 0;
  2967. return true;
  2968. }
  2969. // Check whether the two declarations might declare the same function or
  2970. // function template.
  2971. if (FunctionTemplateDecl *NewTemplate =
  2972. New->getDescribedFunctionTemplate()) {
  2973. if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
  2974. NewTemplate))
  2975. return true;
  2976. OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
  2977. ->getAsFunction();
  2978. } else {
  2979. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2980. return true;
  2981. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2982. }
  2983. } else {
  2984. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2985. << New->getDeclName();
  2986. notePreviousDefinition(OldD, New->getLocation());
  2987. return true;
  2988. }
  2989. }
  2990. // If the old declaration was found in an inline namespace and the new
  2991. // declaration was qualified, update the DeclContext to match.
  2992. adjustDeclContextForDeclaratorDecl(New, Old);
  2993. // If the old declaration is invalid, just give up here.
  2994. if (Old->isInvalidDecl())
  2995. return true;
  2996. // Disallow redeclaration of some builtins.
  2997. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2998. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2999. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  3000. << Old << Old->getType();
  3001. return true;
  3002. }
  3003. diag::kind PrevDiag;
  3004. SourceLocation OldLocation;
  3005. std::tie(PrevDiag, OldLocation) =
  3006. getNoteDiagForInvalidRedeclaration(Old, New);
  3007. // Don't complain about this if we're in GNU89 mode and the old function
  3008. // is an extern inline function.
  3009. // Don't complain about specializations. They are not supposed to have
  3010. // storage classes.
  3011. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  3012. New->getStorageClass() == SC_Static &&
  3013. Old->hasExternalFormalLinkage() &&
  3014. !New->getTemplateSpecializationInfo() &&
  3015. !canRedefineFunction(Old, getLangOpts())) {
  3016. if (getLangOpts().MicrosoftExt) {
  3017. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  3018. Diag(OldLocation, PrevDiag);
  3019. } else {
  3020. Diag(New->getLocation(), diag::err_static_non_static) << New;
  3021. Diag(OldLocation, PrevDiag);
  3022. return true;
  3023. }
  3024. }
  3025. if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
  3026. if (!Old->hasAttr<InternalLinkageAttr>()) {
  3027. Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
  3028. << ILA;
  3029. Diag(Old->getLocation(), diag::note_previous_declaration);
  3030. New->dropAttr<InternalLinkageAttr>();
  3031. }
  3032. if (auto *EA = New->getAttr<ErrorAttr>()) {
  3033. if (!Old->hasAttr<ErrorAttr>()) {
  3034. Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
  3035. Diag(Old->getLocation(), diag::note_previous_declaration);
  3036. New->dropAttr<ErrorAttr>();
  3037. }
  3038. }
  3039. if (CheckRedeclarationInModule(New, Old))
  3040. return true;
  3041. if (!getLangOpts().CPlusPlus) {
  3042. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  3043. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  3044. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  3045. << New << OldOvl;
  3046. // Try our best to find a decl that actually has the overloadable
  3047. // attribute for the note. In most cases (e.g. programs with only one
  3048. // broken declaration/definition), this won't matter.
  3049. //
  3050. // FIXME: We could do this if we juggled some extra state in
  3051. // OverloadableAttr, rather than just removing it.
  3052. const Decl *DiagOld = Old;
  3053. if (OldOvl) {
  3054. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  3055. const auto *A = D->getAttr<OverloadableAttr>();
  3056. return A && !A->isImplicit();
  3057. });
  3058. // If we've implicitly added *all* of the overloadable attrs to this
  3059. // chain, emitting a "previous redecl" note is pointless.
  3060. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  3061. }
  3062. if (DiagOld)
  3063. Diag(DiagOld->getLocation(),
  3064. diag::note_attribute_overloadable_prev_overload)
  3065. << OldOvl;
  3066. if (OldOvl)
  3067. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  3068. else
  3069. New->dropAttr<OverloadableAttr>();
  3070. }
  3071. }
  3072. // If a function is first declared with a calling convention, but is later
  3073. // declared or defined without one, all following decls assume the calling
  3074. // convention of the first.
  3075. //
  3076. // It's OK if a function is first declared without a calling convention,
  3077. // but is later declared or defined with the default calling convention.
  3078. //
  3079. // To test if either decl has an explicit calling convention, we look for
  3080. // AttributedType sugar nodes on the type as written. If they are missing or
  3081. // were canonicalized away, we assume the calling convention was implicit.
  3082. //
  3083. // Note also that we DO NOT return at this point, because we still have
  3084. // other tests to run.
  3085. QualType OldQType = Context.getCanonicalType(Old->getType());
  3086. QualType NewQType = Context.getCanonicalType(New->getType());
  3087. const FunctionType *OldType = cast<FunctionType>(OldQType);
  3088. const FunctionType *NewType = cast<FunctionType>(NewQType);
  3089. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  3090. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  3091. bool RequiresAdjustment = false;
  3092. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  3093. FunctionDecl *First = Old->getFirstDecl();
  3094. const FunctionType *FT =
  3095. First->getType().getCanonicalType()->castAs<FunctionType>();
  3096. FunctionType::ExtInfo FI = FT->getExtInfo();
  3097. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  3098. if (!NewCCExplicit) {
  3099. // Inherit the CC from the previous declaration if it was specified
  3100. // there but not here.
  3101. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  3102. RequiresAdjustment = true;
  3103. } else if (Old->getBuiltinID()) {
  3104. // Builtin attribute isn't propagated to the new one yet at this point,
  3105. // so we check if the old one is a builtin.
  3106. // Calling Conventions on a Builtin aren't really useful and setting a
  3107. // default calling convention and cdecl'ing some builtin redeclarations is
  3108. // common, so warn and ignore the calling convention on the redeclaration.
  3109. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  3110. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  3111. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  3112. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  3113. RequiresAdjustment = true;
  3114. } else {
  3115. // Calling conventions aren't compatible, so complain.
  3116. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  3117. Diag(New->getLocation(), diag::err_cconv_change)
  3118. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  3119. << !FirstCCExplicit
  3120. << (!FirstCCExplicit ? "" :
  3121. FunctionType::getNameForCallConv(FI.getCC()));
  3122. // Put the note on the first decl, since it is the one that matters.
  3123. Diag(First->getLocation(), diag::note_previous_declaration);
  3124. return true;
  3125. }
  3126. }
  3127. // FIXME: diagnose the other way around?
  3128. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  3129. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  3130. RequiresAdjustment = true;
  3131. }
  3132. // Merge regparm attribute.
  3133. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  3134. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  3135. if (NewTypeInfo.getHasRegParm()) {
  3136. Diag(New->getLocation(), diag::err_regparm_mismatch)
  3137. << NewType->getRegParmType()
  3138. << OldType->getRegParmType();
  3139. Diag(OldLocation, diag::note_previous_declaration);
  3140. return true;
  3141. }
  3142. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  3143. RequiresAdjustment = true;
  3144. }
  3145. // Merge ns_returns_retained attribute.
  3146. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  3147. if (NewTypeInfo.getProducesResult()) {
  3148. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  3149. << "'ns_returns_retained'";
  3150. Diag(OldLocation, diag::note_previous_declaration);
  3151. return true;
  3152. }
  3153. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  3154. RequiresAdjustment = true;
  3155. }
  3156. if (OldTypeInfo.getNoCallerSavedRegs() !=
  3157. NewTypeInfo.getNoCallerSavedRegs()) {
  3158. if (NewTypeInfo.getNoCallerSavedRegs()) {
  3159. AnyX86NoCallerSavedRegistersAttr *Attr =
  3160. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  3161. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  3162. Diag(OldLocation, diag::note_previous_declaration);
  3163. return true;
  3164. }
  3165. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  3166. RequiresAdjustment = true;
  3167. }
  3168. if (RequiresAdjustment) {
  3169. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  3170. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  3171. New->setType(QualType(AdjustedType, 0));
  3172. NewQType = Context.getCanonicalType(New->getType());
  3173. }
  3174. // If this redeclaration makes the function inline, we may need to add it to
  3175. // UndefinedButUsed.
  3176. if (!Old->isInlined() && New->isInlined() &&
  3177. !New->hasAttr<GNUInlineAttr>() &&
  3178. !getLangOpts().GNUInline &&
  3179. Old->isUsed(false) &&
  3180. !Old->isDefined() && !New->isThisDeclarationADefinition())
  3181. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3182. SourceLocation()));
  3183. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  3184. // about it.
  3185. if (New->hasAttr<GNUInlineAttr>() &&
  3186. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  3187. UndefinedButUsed.erase(Old->getCanonicalDecl());
  3188. }
  3189. // If pass_object_size params don't match up perfectly, this isn't a valid
  3190. // redeclaration.
  3191. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  3192. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  3193. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  3194. << New->getDeclName();
  3195. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3196. return true;
  3197. }
  3198. if (getLangOpts().CPlusPlus) {
  3199. // C++1z [over.load]p2
  3200. // Certain function declarations cannot be overloaded:
  3201. // -- Function declarations that differ only in the return type,
  3202. // the exception specification, or both cannot be overloaded.
  3203. // Check the exception specifications match. This may recompute the type of
  3204. // both Old and New if it resolved exception specifications, so grab the
  3205. // types again after this. Because this updates the type, we do this before
  3206. // any of the other checks below, which may update the "de facto" NewQType
  3207. // but do not necessarily update the type of New.
  3208. if (CheckEquivalentExceptionSpec(Old, New))
  3209. return true;
  3210. OldQType = Context.getCanonicalType(Old->getType());
  3211. NewQType = Context.getCanonicalType(New->getType());
  3212. // Go back to the type source info to compare the declared return types,
  3213. // per C++1y [dcl.type.auto]p13:
  3214. // Redeclarations or specializations of a function or function template
  3215. // with a declared return type that uses a placeholder type shall also
  3216. // use that placeholder, not a deduced type.
  3217. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  3218. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3219. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3220. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3221. OldDeclaredReturnType)) {
  3222. QualType ResQT;
  3223. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3224. OldDeclaredReturnType->isObjCObjectPointerType())
  3225. // FIXME: This does the wrong thing for a deduced return type.
  3226. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3227. if (ResQT.isNull()) {
  3228. if (New->isCXXClassMember() && New->isOutOfLine())
  3229. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3230. << New << New->getReturnTypeSourceRange();
  3231. else
  3232. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3233. << New->getReturnTypeSourceRange();
  3234. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3235. << Old->getReturnTypeSourceRange();
  3236. return true;
  3237. }
  3238. else
  3239. NewQType = ResQT;
  3240. }
  3241. QualType OldReturnType = OldType->getReturnType();
  3242. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3243. if (OldReturnType != NewReturnType) {
  3244. // If this function has a deduced return type and has already been
  3245. // defined, copy the deduced value from the old declaration.
  3246. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3247. if (OldAT && OldAT->isDeduced()) {
  3248. QualType DT = OldAT->getDeducedType();
  3249. if (DT.isNull()) {
  3250. New->setType(SubstAutoTypeDependent(New->getType()));
  3251. NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
  3252. } else {
  3253. New->setType(SubstAutoType(New->getType(), DT));
  3254. NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
  3255. }
  3256. }
  3257. }
  3258. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3259. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3260. if (OldMethod && NewMethod) {
  3261. // Preserve triviality.
  3262. NewMethod->setTrivial(OldMethod->isTrivial());
  3263. // MSVC allows explicit template specialization at class scope:
  3264. // 2 CXXMethodDecls referring to the same function will be injected.
  3265. // We don't want a redeclaration error.
  3266. bool IsClassScopeExplicitSpecialization =
  3267. OldMethod->isFunctionTemplateSpecialization() &&
  3268. NewMethod->isFunctionTemplateSpecialization();
  3269. bool isFriend = NewMethod->getFriendObjectKind();
  3270. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3271. !IsClassScopeExplicitSpecialization) {
  3272. // -- Member function declarations with the same name and the
  3273. // same parameter types cannot be overloaded if any of them
  3274. // is a static member function declaration.
  3275. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3276. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3277. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3278. return true;
  3279. }
  3280. // C++ [class.mem]p1:
  3281. // [...] A member shall not be declared twice in the
  3282. // member-specification, except that a nested class or member
  3283. // class template can be declared and then later defined.
  3284. if (!inTemplateInstantiation()) {
  3285. unsigned NewDiag;
  3286. if (isa<CXXConstructorDecl>(OldMethod))
  3287. NewDiag = diag::err_constructor_redeclared;
  3288. else if (isa<CXXDestructorDecl>(NewMethod))
  3289. NewDiag = diag::err_destructor_redeclared;
  3290. else if (isa<CXXConversionDecl>(NewMethod))
  3291. NewDiag = diag::err_conv_function_redeclared;
  3292. else
  3293. NewDiag = diag::err_member_redeclared;
  3294. Diag(New->getLocation(), NewDiag);
  3295. } else {
  3296. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3297. << New << New->getType();
  3298. }
  3299. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3300. return true;
  3301. // Complain if this is an explicit declaration of a special
  3302. // member that was initially declared implicitly.
  3303. //
  3304. // As an exception, it's okay to befriend such methods in order
  3305. // to permit the implicit constructor/destructor/operator calls.
  3306. } else if (OldMethod->isImplicit()) {
  3307. if (isFriend) {
  3308. NewMethod->setImplicit();
  3309. } else {
  3310. Diag(NewMethod->getLocation(),
  3311. diag::err_definition_of_implicitly_declared_member)
  3312. << New << getSpecialMember(OldMethod);
  3313. return true;
  3314. }
  3315. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3316. Diag(NewMethod->getLocation(),
  3317. diag::err_definition_of_explicitly_defaulted_member)
  3318. << getSpecialMember(OldMethod);
  3319. return true;
  3320. }
  3321. }
  3322. // C++11 [dcl.attr.noreturn]p1:
  3323. // The first declaration of a function shall specify the noreturn
  3324. // attribute if any declaration of that function specifies the noreturn
  3325. // attribute.
  3326. if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
  3327. if (!Old->hasAttr<CXX11NoReturnAttr>()) {
  3328. Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
  3329. << NRA;
  3330. Diag(Old->getLocation(), diag::note_previous_declaration);
  3331. }
  3332. // C++11 [dcl.attr.depend]p2:
  3333. // The first declaration of a function shall specify the
  3334. // carries_dependency attribute for its declarator-id if any declaration
  3335. // of the function specifies the carries_dependency attribute.
  3336. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3337. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3338. Diag(CDA->getLocation(),
  3339. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3340. Diag(Old->getFirstDecl()->getLocation(),
  3341. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3342. }
  3343. // (C++98 8.3.5p3):
  3344. // All declarations for a function shall agree exactly in both the
  3345. // return type and the parameter-type-list.
  3346. // We also want to respect all the extended bits except noreturn.
  3347. // noreturn should now match unless the old type info didn't have it.
  3348. QualType OldQTypeForComparison = OldQType;
  3349. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3350. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3351. const FunctionType *OldTypeForComparison
  3352. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3353. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3354. assert(OldQTypeForComparison.isCanonical());
  3355. }
  3356. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3357. // As a special case, retain the language linkage from previous
  3358. // declarations of a friend function as an extension.
  3359. //
  3360. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3361. // and is useful because there's otherwise no way to specify language
  3362. // linkage within class scope.
  3363. //
  3364. // Check cautiously as the friend object kind isn't yet complete.
  3365. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3366. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3367. Diag(OldLocation, PrevDiag);
  3368. } else {
  3369. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3370. Diag(OldLocation, PrevDiag);
  3371. return true;
  3372. }
  3373. }
  3374. // If the function types are compatible, merge the declarations. Ignore the
  3375. // exception specifier because it was already checked above in
  3376. // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
  3377. // about incompatible types under -fms-compatibility.
  3378. if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
  3379. NewQType))
  3380. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3381. // If the types are imprecise (due to dependent constructs in friends or
  3382. // local extern declarations), it's OK if they differ. We'll check again
  3383. // during instantiation.
  3384. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3385. return false;
  3386. // Fall through for conflicting redeclarations and redefinitions.
  3387. }
  3388. // C: Function types need to be compatible, not identical. This handles
  3389. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3390. if (!getLangOpts().CPlusPlus &&
  3391. Context.typesAreCompatible(OldQType, NewQType)) {
  3392. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3393. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3394. const FunctionProtoType *OldProto = nullptr;
  3395. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3396. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3397. // The old declaration provided a function prototype, but the
  3398. // new declaration does not. Merge in the prototype.
  3399. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3400. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3401. NewQType =
  3402. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3403. OldProto->getExtProtoInfo());
  3404. New->setType(NewQType);
  3405. New->setHasInheritedPrototype();
  3406. // Synthesize parameters with the same types.
  3407. SmallVector<ParmVarDecl*, 16> Params;
  3408. for (const auto &ParamType : OldProto->param_types()) {
  3409. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3410. SourceLocation(), nullptr,
  3411. ParamType, /*TInfo=*/nullptr,
  3412. SC_None, nullptr);
  3413. Param->setScopeInfo(0, Params.size());
  3414. Param->setImplicit();
  3415. Params.push_back(Param);
  3416. }
  3417. New->setParams(Params);
  3418. }
  3419. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3420. }
  3421. // Check if the function types are compatible when pointer size address
  3422. // spaces are ignored.
  3423. if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
  3424. return false;
  3425. // GNU C permits a K&R definition to follow a prototype declaration
  3426. // if the declared types of the parameters in the K&R definition
  3427. // match the types in the prototype declaration, even when the
  3428. // promoted types of the parameters from the K&R definition differ
  3429. // from the types in the prototype. GCC then keeps the types from
  3430. // the prototype.
  3431. //
  3432. // If a variadic prototype is followed by a non-variadic K&R definition,
  3433. // the K&R definition becomes variadic. This is sort of an edge case, but
  3434. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3435. // C99 6.9.1p8.
  3436. if (!getLangOpts().CPlusPlus &&
  3437. Old->hasPrototype() && !New->hasPrototype() &&
  3438. New->getType()->getAs<FunctionProtoType>() &&
  3439. Old->getNumParams() == New->getNumParams()) {
  3440. SmallVector<QualType, 16> ArgTypes;
  3441. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3442. const FunctionProtoType *OldProto
  3443. = Old->getType()->getAs<FunctionProtoType>();
  3444. const FunctionProtoType *NewProto
  3445. = New->getType()->getAs<FunctionProtoType>();
  3446. // Determine whether this is the GNU C extension.
  3447. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3448. NewProto->getReturnType());
  3449. bool LooseCompatible = !MergedReturn.isNull();
  3450. for (unsigned Idx = 0, End = Old->getNumParams();
  3451. LooseCompatible && Idx != End; ++Idx) {
  3452. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3453. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3454. if (Context.typesAreCompatible(OldParm->getType(),
  3455. NewProto->getParamType(Idx))) {
  3456. ArgTypes.push_back(NewParm->getType());
  3457. } else if (Context.typesAreCompatible(OldParm->getType(),
  3458. NewParm->getType(),
  3459. /*CompareUnqualified=*/true)) {
  3460. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3461. NewProto->getParamType(Idx) };
  3462. Warnings.push_back(Warn);
  3463. ArgTypes.push_back(NewParm->getType());
  3464. } else
  3465. LooseCompatible = false;
  3466. }
  3467. if (LooseCompatible) {
  3468. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3469. Diag(Warnings[Warn].NewParm->getLocation(),
  3470. diag::ext_param_promoted_not_compatible_with_prototype)
  3471. << Warnings[Warn].PromotedType
  3472. << Warnings[Warn].OldParm->getType();
  3473. if (Warnings[Warn].OldParm->getLocation().isValid())
  3474. Diag(Warnings[Warn].OldParm->getLocation(),
  3475. diag::note_previous_declaration);
  3476. }
  3477. if (MergeTypeWithOld)
  3478. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3479. OldProto->getExtProtoInfo()));
  3480. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3481. }
  3482. // Fall through to diagnose conflicting types.
  3483. }
  3484. // A function that has already been declared has been redeclared or
  3485. // defined with a different type; show an appropriate diagnostic.
  3486. // If the previous declaration was an implicitly-generated builtin
  3487. // declaration, then at the very least we should use a specialized note.
  3488. unsigned BuiltinID;
  3489. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3490. // If it's actually a library-defined builtin function like 'malloc'
  3491. // or 'printf', just warn about the incompatible redeclaration.
  3492. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3493. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3494. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3495. << Old << Old->getType();
  3496. return false;
  3497. }
  3498. PrevDiag = diag::note_previous_builtin_declaration;
  3499. }
  3500. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3501. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3502. return true;
  3503. }
  3504. /// Completes the merge of two function declarations that are
  3505. /// known to be compatible.
  3506. ///
  3507. /// This routine handles the merging of attributes and other
  3508. /// properties of function declarations from the old declaration to
  3509. /// the new declaration, once we know that New is in fact a
  3510. /// redeclaration of Old.
  3511. ///
  3512. /// \returns false
  3513. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3514. Scope *S, bool MergeTypeWithOld) {
  3515. // Merge the attributes
  3516. mergeDeclAttributes(New, Old);
  3517. // Merge "pure" flag.
  3518. if (Old->isPure())
  3519. New->setPure();
  3520. // Merge "used" flag.
  3521. if (Old->getMostRecentDecl()->isUsed(false))
  3522. New->setIsUsed();
  3523. // Merge attributes from the parameters. These can mismatch with K&R
  3524. // declarations.
  3525. if (New->getNumParams() == Old->getNumParams())
  3526. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3527. ParmVarDecl *NewParam = New->getParamDecl(i);
  3528. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3529. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3530. mergeParamDeclTypes(NewParam, OldParam, *this);
  3531. }
  3532. if (getLangOpts().CPlusPlus)
  3533. return MergeCXXFunctionDecl(New, Old, S);
  3534. // Merge the function types so the we get the composite types for the return
  3535. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3536. // was visible.
  3537. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3538. if (!Merged.isNull() && MergeTypeWithOld)
  3539. New->setType(Merged);
  3540. return false;
  3541. }
  3542. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3543. ObjCMethodDecl *oldMethod) {
  3544. // Merge the attributes, including deprecated/unavailable
  3545. AvailabilityMergeKind MergeKind =
  3546. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3547. ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
  3548. : AMK_ProtocolImplementation)
  3549. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3550. : AMK_Override;
  3551. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3552. // Merge attributes from the parameters.
  3553. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3554. oe = oldMethod->param_end();
  3555. for (ObjCMethodDecl::param_iterator
  3556. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3557. ni != ne && oi != oe; ++ni, ++oi)
  3558. mergeParamDeclAttributes(*ni, *oi, *this);
  3559. CheckObjCMethodOverride(newMethod, oldMethod);
  3560. }
  3561. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3562. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3563. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3564. ? diag::err_redefinition_different_type
  3565. : diag::err_redeclaration_different_type)
  3566. << New->getDeclName() << New->getType() << Old->getType();
  3567. diag::kind PrevDiag;
  3568. SourceLocation OldLocation;
  3569. std::tie(PrevDiag, OldLocation)
  3570. = getNoteDiagForInvalidRedeclaration(Old, New);
  3571. S.Diag(OldLocation, PrevDiag);
  3572. New->setInvalidDecl();
  3573. }
  3574. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3575. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3576. /// emitting diagnostics as appropriate.
  3577. ///
  3578. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3579. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3580. /// is attached.
  3581. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3582. bool MergeTypeWithOld) {
  3583. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3584. return;
  3585. QualType MergedT;
  3586. if (getLangOpts().CPlusPlus) {
  3587. if (New->getType()->isUndeducedType()) {
  3588. // We don't know what the new type is until the initializer is attached.
  3589. return;
  3590. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3591. // These could still be something that needs exception specs checked.
  3592. return MergeVarDeclExceptionSpecs(New, Old);
  3593. }
  3594. // C++ [basic.link]p10:
  3595. // [...] the types specified by all declarations referring to a given
  3596. // object or function shall be identical, except that declarations for an
  3597. // array object can specify array types that differ by the presence or
  3598. // absence of a major array bound (8.3.4).
  3599. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3600. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3601. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3602. // We are merging a variable declaration New into Old. If it has an array
  3603. // bound, and that bound differs from Old's bound, we should diagnose the
  3604. // mismatch.
  3605. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3606. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3607. PrevVD = PrevVD->getPreviousDecl()) {
  3608. QualType PrevVDTy = PrevVD->getType();
  3609. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3610. continue;
  3611. if (!Context.hasSameType(New->getType(), PrevVDTy))
  3612. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3613. }
  3614. }
  3615. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3616. if (Context.hasSameType(OldArray->getElementType(),
  3617. NewArray->getElementType()))
  3618. MergedT = New->getType();
  3619. }
  3620. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3621. // has no array bound, it should not inherit one from Old, if Old is not
  3622. // visible.
  3623. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3624. if (Context.hasSameType(OldArray->getElementType(),
  3625. NewArray->getElementType()))
  3626. MergedT = Old->getType();
  3627. }
  3628. }
  3629. else if (New->getType()->isObjCObjectPointerType() &&
  3630. Old->getType()->isObjCObjectPointerType()) {
  3631. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3632. Old->getType());
  3633. }
  3634. } else {
  3635. // C 6.2.7p2:
  3636. // All declarations that refer to the same object or function shall have
  3637. // compatible type.
  3638. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3639. }
  3640. if (MergedT.isNull()) {
  3641. // It's OK if we couldn't merge types if either type is dependent, for a
  3642. // block-scope variable. In other cases (static data members of class
  3643. // templates, variable templates, ...), we require the types to be
  3644. // equivalent.
  3645. // FIXME: The C++ standard doesn't say anything about this.
  3646. if ((New->getType()->isDependentType() ||
  3647. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3648. // If the old type was dependent, we can't merge with it, so the new type
  3649. // becomes dependent for now. We'll reproduce the original type when we
  3650. // instantiate the TypeSourceInfo for the variable.
  3651. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3652. New->setType(Context.DependentTy);
  3653. return;
  3654. }
  3655. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3656. }
  3657. // Don't actually update the type on the new declaration if the old
  3658. // declaration was an extern declaration in a different scope.
  3659. if (MergeTypeWithOld)
  3660. New->setType(MergedT);
  3661. }
  3662. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3663. LookupResult &Previous) {
  3664. // C11 6.2.7p4:
  3665. // For an identifier with internal or external linkage declared
  3666. // in a scope in which a prior declaration of that identifier is
  3667. // visible, if the prior declaration specifies internal or
  3668. // external linkage, the type of the identifier at the later
  3669. // declaration becomes the composite type.
  3670. //
  3671. // If the variable isn't visible, we do not merge with its type.
  3672. if (Previous.isShadowed())
  3673. return false;
  3674. if (S.getLangOpts().CPlusPlus) {
  3675. // C++11 [dcl.array]p3:
  3676. // If there is a preceding declaration of the entity in the same
  3677. // scope in which the bound was specified, an omitted array bound
  3678. // is taken to be the same as in that earlier declaration.
  3679. return NewVD->isPreviousDeclInSameBlockScope() ||
  3680. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3681. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3682. } else {
  3683. // If the old declaration was function-local, don't merge with its
  3684. // type unless we're in the same function.
  3685. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3686. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3687. }
  3688. }
  3689. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3690. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3691. /// situation, merging decls or emitting diagnostics as appropriate.
  3692. ///
  3693. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3694. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3695. /// definitions here, since the initializer hasn't been attached.
  3696. ///
  3697. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3698. // If the new decl is already invalid, don't do any other checking.
  3699. if (New->isInvalidDecl())
  3700. return;
  3701. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3702. return;
  3703. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3704. // Verify the old decl was also a variable or variable template.
  3705. VarDecl *Old = nullptr;
  3706. VarTemplateDecl *OldTemplate = nullptr;
  3707. if (Previous.isSingleResult()) {
  3708. if (NewTemplate) {
  3709. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3710. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3711. if (auto *Shadow =
  3712. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3713. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3714. return New->setInvalidDecl();
  3715. } else {
  3716. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3717. if (auto *Shadow =
  3718. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3719. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3720. return New->setInvalidDecl();
  3721. }
  3722. }
  3723. if (!Old) {
  3724. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3725. << New->getDeclName();
  3726. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3727. New->getLocation());
  3728. return New->setInvalidDecl();
  3729. }
  3730. // If the old declaration was found in an inline namespace and the new
  3731. // declaration was qualified, update the DeclContext to match.
  3732. adjustDeclContextForDeclaratorDecl(New, Old);
  3733. // Ensure the template parameters are compatible.
  3734. if (NewTemplate &&
  3735. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3736. OldTemplate->getTemplateParameters(),
  3737. /*Complain=*/true, TPL_TemplateMatch))
  3738. return New->setInvalidDecl();
  3739. // C++ [class.mem]p1:
  3740. // A member shall not be declared twice in the member-specification [...]
  3741. //
  3742. // Here, we need only consider static data members.
  3743. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3744. Diag(New->getLocation(), diag::err_duplicate_member)
  3745. << New->getIdentifier();
  3746. Diag(Old->getLocation(), diag::note_previous_declaration);
  3747. New->setInvalidDecl();
  3748. }
  3749. mergeDeclAttributes(New, Old);
  3750. // Warn if an already-declared variable is made a weak_import in a subsequent
  3751. // declaration
  3752. if (New->hasAttr<WeakImportAttr>() &&
  3753. Old->getStorageClass() == SC_None &&
  3754. !Old->hasAttr<WeakImportAttr>()) {
  3755. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3756. Diag(Old->getLocation(), diag::note_previous_declaration);
  3757. // Remove weak_import attribute on new declaration.
  3758. New->dropAttr<WeakImportAttr>();
  3759. }
  3760. if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
  3761. if (!Old->hasAttr<InternalLinkageAttr>()) {
  3762. Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
  3763. << ILA;
  3764. Diag(Old->getLocation(), diag::note_previous_declaration);
  3765. New->dropAttr<InternalLinkageAttr>();
  3766. }
  3767. // Merge the types.
  3768. VarDecl *MostRecent = Old->getMostRecentDecl();
  3769. if (MostRecent != Old) {
  3770. MergeVarDeclTypes(New, MostRecent,
  3771. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3772. if (New->isInvalidDecl())
  3773. return;
  3774. }
  3775. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3776. if (New->isInvalidDecl())
  3777. return;
  3778. diag::kind PrevDiag;
  3779. SourceLocation OldLocation;
  3780. std::tie(PrevDiag, OldLocation) =
  3781. getNoteDiagForInvalidRedeclaration(Old, New);
  3782. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3783. if (New->getStorageClass() == SC_Static &&
  3784. !New->isStaticDataMember() &&
  3785. Old->hasExternalFormalLinkage()) {
  3786. if (getLangOpts().MicrosoftExt) {
  3787. Diag(New->getLocation(), diag::ext_static_non_static)
  3788. << New->getDeclName();
  3789. Diag(OldLocation, PrevDiag);
  3790. } else {
  3791. Diag(New->getLocation(), diag::err_static_non_static)
  3792. << New->getDeclName();
  3793. Diag(OldLocation, PrevDiag);
  3794. return New->setInvalidDecl();
  3795. }
  3796. }
  3797. // C99 6.2.2p4:
  3798. // For an identifier declared with the storage-class specifier
  3799. // extern in a scope in which a prior declaration of that
  3800. // identifier is visible,23) if the prior declaration specifies
  3801. // internal or external linkage, the linkage of the identifier at
  3802. // the later declaration is the same as the linkage specified at
  3803. // the prior declaration. If no prior declaration is visible, or
  3804. // if the prior declaration specifies no linkage, then the
  3805. // identifier has external linkage.
  3806. if (New->hasExternalStorage() && Old->hasLinkage())
  3807. /* Okay */;
  3808. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3809. !New->isStaticDataMember() &&
  3810. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3811. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3812. Diag(OldLocation, PrevDiag);
  3813. return New->setInvalidDecl();
  3814. }
  3815. // Check if extern is followed by non-extern and vice-versa.
  3816. if (New->hasExternalStorage() &&
  3817. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3818. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3819. Diag(OldLocation, PrevDiag);
  3820. return New->setInvalidDecl();
  3821. }
  3822. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3823. !New->hasExternalStorage()) {
  3824. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3825. Diag(OldLocation, PrevDiag);
  3826. return New->setInvalidDecl();
  3827. }
  3828. if (CheckRedeclarationInModule(New, Old))
  3829. return;
  3830. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3831. // FIXME: The test for external storage here seems wrong? We still
  3832. // need to check for mismatches.
  3833. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3834. // Don't complain about out-of-line definitions of static members.
  3835. !(Old->getLexicalDeclContext()->isRecord() &&
  3836. !New->getLexicalDeclContext()->isRecord())) {
  3837. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3838. Diag(OldLocation, PrevDiag);
  3839. return New->setInvalidDecl();
  3840. }
  3841. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3842. if (VarDecl *Def = Old->getDefinition()) {
  3843. // C++1z [dcl.fcn.spec]p4:
  3844. // If the definition of a variable appears in a translation unit before
  3845. // its first declaration as inline, the program is ill-formed.
  3846. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3847. Diag(Def->getLocation(), diag::note_previous_definition);
  3848. }
  3849. }
  3850. // If this redeclaration makes the variable inline, we may need to add it to
  3851. // UndefinedButUsed.
  3852. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3853. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3854. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3855. SourceLocation()));
  3856. if (New->getTLSKind() != Old->getTLSKind()) {
  3857. if (!Old->getTLSKind()) {
  3858. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3859. Diag(OldLocation, PrevDiag);
  3860. } else if (!New->getTLSKind()) {
  3861. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3862. Diag(OldLocation, PrevDiag);
  3863. } else {
  3864. // Do not allow redeclaration to change the variable between requiring
  3865. // static and dynamic initialization.
  3866. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3867. // declaration to determine the kind. Do we need to be compatible here?
  3868. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3869. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3870. Diag(OldLocation, PrevDiag);
  3871. }
  3872. }
  3873. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3874. if (getLangOpts().CPlusPlus &&
  3875. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3876. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3877. Old->getCanonicalDecl()->isConstexpr()) {
  3878. // This definition won't be a definition any more once it's been merged.
  3879. Diag(New->getLocation(),
  3880. diag::warn_deprecated_redundant_constexpr_static_def);
  3881. } else if (VarDecl *Def = Old->getDefinition()) {
  3882. if (checkVarDeclRedefinition(Def, New))
  3883. return;
  3884. }
  3885. }
  3886. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3887. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3888. Diag(OldLocation, PrevDiag);
  3889. New->setInvalidDecl();
  3890. return;
  3891. }
  3892. // Merge "used" flag.
  3893. if (Old->getMostRecentDecl()->isUsed(false))
  3894. New->setIsUsed();
  3895. // Keep a chain of previous declarations.
  3896. New->setPreviousDecl(Old);
  3897. if (NewTemplate)
  3898. NewTemplate->setPreviousDecl(OldTemplate);
  3899. // Inherit access appropriately.
  3900. New->setAccess(Old->getAccess());
  3901. if (NewTemplate)
  3902. NewTemplate->setAccess(New->getAccess());
  3903. if (Old->isInline())
  3904. New->setImplicitlyInline();
  3905. }
  3906. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3907. SourceManager &SrcMgr = getSourceManager();
  3908. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3909. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3910. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3911. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3912. auto &HSI = PP.getHeaderSearchInfo();
  3913. StringRef HdrFilename =
  3914. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3915. auto noteFromModuleOrInclude = [&](Module *Mod,
  3916. SourceLocation IncLoc) -> bool {
  3917. // Redefinition errors with modules are common with non modular mapped
  3918. // headers, example: a non-modular header H in module A that also gets
  3919. // included directly in a TU. Pointing twice to the same header/definition
  3920. // is confusing, try to get better diagnostics when modules is on.
  3921. if (IncLoc.isValid()) {
  3922. if (Mod) {
  3923. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3924. << HdrFilename.str() << Mod->getFullModuleName();
  3925. if (!Mod->DefinitionLoc.isInvalid())
  3926. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3927. << Mod->getFullModuleName();
  3928. } else {
  3929. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3930. << HdrFilename.str();
  3931. }
  3932. return true;
  3933. }
  3934. return false;
  3935. };
  3936. // Is it the same file and same offset? Provide more information on why
  3937. // this leads to a redefinition error.
  3938. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3939. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3940. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3941. bool EmittedDiag =
  3942. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3943. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3944. // If the header has no guards, emit a note suggesting one.
  3945. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3946. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3947. if (EmittedDiag)
  3948. return;
  3949. }
  3950. // Redefinition coming from different files or couldn't do better above.
  3951. if (Old->getLocation().isValid())
  3952. Diag(Old->getLocation(), diag::note_previous_definition);
  3953. }
  3954. /// We've just determined that \p Old and \p New both appear to be definitions
  3955. /// of the same variable. Either diagnose or fix the problem.
  3956. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3957. if (!hasVisibleDefinition(Old) &&
  3958. (New->getFormalLinkage() == InternalLinkage ||
  3959. New->isInline() ||
  3960. New->getDescribedVarTemplate() ||
  3961. New->getNumTemplateParameterLists() ||
  3962. New->getDeclContext()->isDependentContext())) {
  3963. // The previous definition is hidden, and multiple definitions are
  3964. // permitted (in separate TUs). Demote this to a declaration.
  3965. New->demoteThisDefinitionToDeclaration();
  3966. // Make the canonical definition visible.
  3967. if (auto *OldTD = Old->getDescribedVarTemplate())
  3968. makeMergedDefinitionVisible(OldTD);
  3969. makeMergedDefinitionVisible(Old);
  3970. return false;
  3971. } else {
  3972. Diag(New->getLocation(), diag::err_redefinition) << New;
  3973. notePreviousDefinition(Old, New->getLocation());
  3974. New->setInvalidDecl();
  3975. return true;
  3976. }
  3977. }
  3978. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3979. /// no declarator (e.g. "struct foo;") is parsed.
  3980. Decl *
  3981. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3982. RecordDecl *&AnonRecord) {
  3983. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3984. AnonRecord);
  3985. }
  3986. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3987. // disambiguate entities defined in different scopes.
  3988. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3989. // compatibility.
  3990. // We will pick our mangling number depending on which version of MSVC is being
  3991. // targeted.
  3992. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3993. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3994. ? S->getMSCurManglingNumber()
  3995. : S->getMSLastManglingNumber();
  3996. }
  3997. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3998. if (!Context.getLangOpts().CPlusPlus)
  3999. return;
  4000. if (isa<CXXRecordDecl>(Tag->getParent())) {
  4001. // If this tag is the direct child of a class, number it if
  4002. // it is anonymous.
  4003. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  4004. return;
  4005. MangleNumberingContext &MCtx =
  4006. Context.getManglingNumberContext(Tag->getParent());
  4007. Context.setManglingNumber(
  4008. Tag, MCtx.getManglingNumber(
  4009. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  4010. return;
  4011. }
  4012. // If this tag isn't a direct child of a class, number it if it is local.
  4013. MangleNumberingContext *MCtx;
  4014. Decl *ManglingContextDecl;
  4015. std::tie(MCtx, ManglingContextDecl) =
  4016. getCurrentMangleNumberContext(Tag->getDeclContext());
  4017. if (MCtx) {
  4018. Context.setManglingNumber(
  4019. Tag, MCtx->getManglingNumber(
  4020. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  4021. }
  4022. }
  4023. namespace {
  4024. struct NonCLikeKind {
  4025. enum {
  4026. None,
  4027. BaseClass,
  4028. DefaultMemberInit,
  4029. Lambda,
  4030. Friend,
  4031. OtherMember,
  4032. Invalid,
  4033. } Kind = None;
  4034. SourceRange Range;
  4035. explicit operator bool() { return Kind != None; }
  4036. };
  4037. }
  4038. /// Determine whether a class is C-like, according to the rules of C++
  4039. /// [dcl.typedef] for anonymous classes with typedef names for linkage.
  4040. static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
  4041. if (RD->isInvalidDecl())
  4042. return {NonCLikeKind::Invalid, {}};
  4043. // C++ [dcl.typedef]p9: [P1766R1]
  4044. // An unnamed class with a typedef name for linkage purposes shall not
  4045. //
  4046. // -- have any base classes
  4047. if (RD->getNumBases())
  4048. return {NonCLikeKind::BaseClass,
  4049. SourceRange(RD->bases_begin()->getBeginLoc(),
  4050. RD->bases_end()[-1].getEndLoc())};
  4051. bool Invalid = false;
  4052. for (Decl *D : RD->decls()) {
  4053. // Don't complain about things we already diagnosed.
  4054. if (D->isInvalidDecl()) {
  4055. Invalid = true;
  4056. continue;
  4057. }
  4058. // -- have any [...] default member initializers
  4059. if (auto *FD = dyn_cast<FieldDecl>(D)) {
  4060. if (FD->hasInClassInitializer()) {
  4061. auto *Init = FD->getInClassInitializer();
  4062. return {NonCLikeKind::DefaultMemberInit,
  4063. Init ? Init->getSourceRange() : D->getSourceRange()};
  4064. }
  4065. continue;
  4066. }
  4067. // FIXME: We don't allow friend declarations. This violates the wording of
  4068. // P1766, but not the intent.
  4069. if (isa<FriendDecl>(D))
  4070. return {NonCLikeKind::Friend, D->getSourceRange()};
  4071. // -- declare any members other than non-static data members, member
  4072. // enumerations, or member classes,
  4073. if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
  4074. isa<EnumDecl>(D))
  4075. continue;
  4076. auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
  4077. if (!MemberRD) {
  4078. if (D->isImplicit())
  4079. continue;
  4080. return {NonCLikeKind::OtherMember, D->getSourceRange()};
  4081. }
  4082. // -- contain a lambda-expression,
  4083. if (MemberRD->isLambda())
  4084. return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
  4085. // and all member classes shall also satisfy these requirements
  4086. // (recursively).
  4087. if (MemberRD->isThisDeclarationADefinition()) {
  4088. if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
  4089. return Kind;
  4090. }
  4091. }
  4092. return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
  4093. }
  4094. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  4095. TypedefNameDecl *NewTD) {
  4096. if (TagFromDeclSpec->isInvalidDecl())
  4097. return;
  4098. // Do nothing if the tag already has a name for linkage purposes.
  4099. if (TagFromDeclSpec->hasNameForLinkage())
  4100. return;
  4101. // A well-formed anonymous tag must always be a TUK_Definition.
  4102. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  4103. // The type must match the tag exactly; no qualifiers allowed.
  4104. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  4105. Context.getTagDeclType(TagFromDeclSpec))) {
  4106. if (getLangOpts().CPlusPlus)
  4107. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  4108. return;
  4109. }
  4110. // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
  4111. // An unnamed class with a typedef name for linkage purposes shall [be
  4112. // C-like].
  4113. //
  4114. // FIXME: Also diagnose if we've already computed the linkage. That ideally
  4115. // shouldn't happen, but there are constructs that the language rule doesn't
  4116. // disallow for which we can't reasonably avoid computing linkage early.
  4117. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
  4118. NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
  4119. : NonCLikeKind();
  4120. bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
  4121. if (NonCLike || ChangesLinkage) {
  4122. if (NonCLike.Kind == NonCLikeKind::Invalid)
  4123. return;
  4124. unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
  4125. if (ChangesLinkage) {
  4126. // If the linkage changes, we can't accept this as an extension.
  4127. if (NonCLike.Kind == NonCLikeKind::None)
  4128. DiagID = diag::err_typedef_changes_linkage;
  4129. else
  4130. DiagID = diag::err_non_c_like_anon_struct_in_typedef;
  4131. }
  4132. SourceLocation FixitLoc =
  4133. getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
  4134. llvm::SmallString<40> TextToInsert;
  4135. TextToInsert += ' ';
  4136. TextToInsert += NewTD->getIdentifier()->getName();
  4137. Diag(FixitLoc, DiagID)
  4138. << isa<TypeAliasDecl>(NewTD)
  4139. << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
  4140. if (NonCLike.Kind != NonCLikeKind::None) {
  4141. Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
  4142. << NonCLike.Kind - 1 << NonCLike.Range;
  4143. }
  4144. Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
  4145. << NewTD << isa<TypeAliasDecl>(NewTD);
  4146. if (ChangesLinkage)
  4147. return;
  4148. }
  4149. // Otherwise, set this as the anon-decl typedef for the tag.
  4150. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  4151. }
  4152. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  4153. switch (T) {
  4154. case DeclSpec::TST_class:
  4155. return 0;
  4156. case DeclSpec::TST_struct:
  4157. return 1;
  4158. case DeclSpec::TST_interface:
  4159. return 2;
  4160. case DeclSpec::TST_union:
  4161. return 3;
  4162. case DeclSpec::TST_enum:
  4163. return 4;
  4164. default:
  4165. llvm_unreachable("unexpected type specifier");
  4166. }
  4167. }
  4168. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  4169. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  4170. /// parameters to cope with template friend declarations.
  4171. Decl *
  4172. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  4173. MultiTemplateParamsArg TemplateParams,
  4174. bool IsExplicitInstantiation,
  4175. RecordDecl *&AnonRecord) {
  4176. Decl *TagD = nullptr;
  4177. TagDecl *Tag = nullptr;
  4178. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  4179. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  4180. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  4181. DS.getTypeSpecType() == DeclSpec::TST_union ||
  4182. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  4183. TagD = DS.getRepAsDecl();
  4184. if (!TagD) // We probably had an error
  4185. return nullptr;
  4186. // Note that the above type specs guarantee that the
  4187. // type rep is a Decl, whereas in many of the others
  4188. // it's a Type.
  4189. if (isa<TagDecl>(TagD))
  4190. Tag = cast<TagDecl>(TagD);
  4191. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  4192. Tag = CTD->getTemplatedDecl();
  4193. }
  4194. if (Tag) {
  4195. handleTagNumbering(Tag, S);
  4196. Tag->setFreeStanding();
  4197. if (Tag->isInvalidDecl())
  4198. return Tag;
  4199. }
  4200. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  4201. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  4202. // or incomplete types shall not be restrict-qualified."
  4203. if (TypeQuals & DeclSpec::TQ_restrict)
  4204. Diag(DS.getRestrictSpecLoc(),
  4205. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  4206. << DS.getSourceRange();
  4207. }
  4208. if (DS.isInlineSpecified())
  4209. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  4210. << getLangOpts().CPlusPlus17;
  4211. if (DS.hasConstexprSpecifier()) {
  4212. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  4213. // and definitions of functions and variables.
  4214. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  4215. // the declaration of a function or function template
  4216. if (Tag)
  4217. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  4218. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  4219. << static_cast<int>(DS.getConstexprSpecifier());
  4220. else
  4221. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  4222. << static_cast<int>(DS.getConstexprSpecifier());
  4223. // Don't emit warnings after this error.
  4224. return TagD;
  4225. }
  4226. DiagnoseFunctionSpecifiers(DS);
  4227. if (DS.isFriendSpecified()) {
  4228. // If we're dealing with a decl but not a TagDecl, assume that
  4229. // whatever routines created it handled the friendship aspect.
  4230. if (TagD && !Tag)
  4231. return nullptr;
  4232. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  4233. }
  4234. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  4235. bool IsExplicitSpecialization =
  4236. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  4237. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  4238. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  4239. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  4240. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  4241. // nested-name-specifier unless it is an explicit instantiation
  4242. // or an explicit specialization.
  4243. //
  4244. // FIXME: We allow class template partial specializations here too, per the
  4245. // obvious intent of DR1819.
  4246. //
  4247. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  4248. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  4249. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  4250. return nullptr;
  4251. }
  4252. // Track whether this decl-specifier declares anything.
  4253. bool DeclaresAnything = true;
  4254. // Handle anonymous struct definitions.
  4255. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  4256. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  4257. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  4258. if (getLangOpts().CPlusPlus ||
  4259. Record->getDeclContext()->isRecord()) {
  4260. // If CurContext is a DeclContext that can contain statements,
  4261. // RecursiveASTVisitor won't visit the decls that
  4262. // BuildAnonymousStructOrUnion() will put into CurContext.
  4263. // Also store them here so that they can be part of the
  4264. // DeclStmt that gets created in this case.
  4265. // FIXME: Also return the IndirectFieldDecls created by
  4266. // BuildAnonymousStructOr union, for the same reason?
  4267. if (CurContext->isFunctionOrMethod())
  4268. AnonRecord = Record;
  4269. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  4270. Context.getPrintingPolicy());
  4271. }
  4272. DeclaresAnything = false;
  4273. }
  4274. }
  4275. // C11 6.7.2.1p2:
  4276. // A struct-declaration that does not declare an anonymous structure or
  4277. // anonymous union shall contain a struct-declarator-list.
  4278. //
  4279. // This rule also existed in C89 and C99; the grammar for struct-declaration
  4280. // did not permit a struct-declaration without a struct-declarator-list.
  4281. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  4282. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  4283. // Check for Microsoft C extension: anonymous struct/union member.
  4284. // Handle 2 kinds of anonymous struct/union:
  4285. // struct STRUCT;
  4286. // union UNION;
  4287. // and
  4288. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  4289. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  4290. if ((Tag && Tag->getDeclName()) ||
  4291. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  4292. RecordDecl *Record = nullptr;
  4293. if (Tag)
  4294. Record = dyn_cast<RecordDecl>(Tag);
  4295. else if (const RecordType *RT =
  4296. DS.getRepAsType().get()->getAsStructureType())
  4297. Record = RT->getDecl();
  4298. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  4299. Record = UT->getDecl();
  4300. if (Record && getLangOpts().MicrosoftExt) {
  4301. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  4302. << Record->isUnion() << DS.getSourceRange();
  4303. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  4304. }
  4305. DeclaresAnything = false;
  4306. }
  4307. }
  4308. // Skip all the checks below if we have a type error.
  4309. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  4310. (TagD && TagD->isInvalidDecl()))
  4311. return TagD;
  4312. if (getLangOpts().CPlusPlus &&
  4313. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  4314. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4315. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4316. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4317. DeclaresAnything = false;
  4318. if (!DS.isMissingDeclaratorOk()) {
  4319. // Customize diagnostic for a typedef missing a name.
  4320. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4321. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4322. << DS.getSourceRange();
  4323. else
  4324. DeclaresAnything = false;
  4325. }
  4326. if (DS.isModulePrivateSpecified() &&
  4327. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4328. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4329. << Tag->getTagKind()
  4330. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4331. ActOnDocumentableDecl(TagD);
  4332. // C 6.7/2:
  4333. // A declaration [...] shall declare at least a declarator [...], a tag,
  4334. // or the members of an enumeration.
  4335. // C++ [dcl.dcl]p3:
  4336. // [If there are no declarators], and except for the declaration of an
  4337. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4338. // names into the program, or shall redeclare a name introduced by a
  4339. // previous declaration.
  4340. if (!DeclaresAnything) {
  4341. // In C, we allow this as a (popular) extension / bug. Don't bother
  4342. // producing further diagnostics for redundant qualifiers after this.
  4343. Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
  4344. ? diag::err_no_declarators
  4345. : diag::ext_no_declarators)
  4346. << DS.getSourceRange();
  4347. return TagD;
  4348. }
  4349. // C++ [dcl.stc]p1:
  4350. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4351. // init-declarator-list of the declaration shall not be empty.
  4352. // C++ [dcl.fct.spec]p1:
  4353. // If a cv-qualifier appears in a decl-specifier-seq, the
  4354. // init-declarator-list of the declaration shall not be empty.
  4355. //
  4356. // Spurious qualifiers here appear to be valid in C.
  4357. unsigned DiagID = diag::warn_standalone_specifier;
  4358. if (getLangOpts().CPlusPlus)
  4359. DiagID = diag::ext_standalone_specifier;
  4360. // Note that a linkage-specification sets a storage class, but
  4361. // 'extern "C" struct foo;' is actually valid and not theoretically
  4362. // useless.
  4363. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4364. if (SCS == DeclSpec::SCS_mutable)
  4365. // Since mutable is not a viable storage class specifier in C, there is
  4366. // no reason to treat it as an extension. Instead, diagnose as an error.
  4367. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4368. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4369. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4370. << DeclSpec::getSpecifierName(SCS);
  4371. }
  4372. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4373. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4374. << DeclSpec::getSpecifierName(TSCS);
  4375. if (DS.getTypeQualifiers()) {
  4376. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4377. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4378. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4379. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4380. // Restrict is covered above.
  4381. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4382. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4383. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4384. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4385. }
  4386. // Warn about ignored type attributes, for example:
  4387. // __attribute__((aligned)) struct A;
  4388. // Attributes should be placed after tag to apply to type declaration.
  4389. if (!DS.getAttributes().empty()) {
  4390. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4391. if (TypeSpecType == DeclSpec::TST_class ||
  4392. TypeSpecType == DeclSpec::TST_struct ||
  4393. TypeSpecType == DeclSpec::TST_interface ||
  4394. TypeSpecType == DeclSpec::TST_union ||
  4395. TypeSpecType == DeclSpec::TST_enum) {
  4396. for (const ParsedAttr &AL : DS.getAttributes())
  4397. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4398. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4399. }
  4400. }
  4401. return TagD;
  4402. }
  4403. /// We are trying to inject an anonymous member into the given scope;
  4404. /// check if there's an existing declaration that can't be overloaded.
  4405. ///
  4406. /// \return true if this is a forbidden redeclaration
  4407. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4408. Scope *S,
  4409. DeclContext *Owner,
  4410. DeclarationName Name,
  4411. SourceLocation NameLoc,
  4412. bool IsUnion) {
  4413. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4414. Sema::ForVisibleRedeclaration);
  4415. if (!SemaRef.LookupName(R, S)) return false;
  4416. // Pick a representative declaration.
  4417. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4418. assert(PrevDecl && "Expected a non-null Decl");
  4419. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4420. return false;
  4421. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4422. << IsUnion << Name;
  4423. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4424. return true;
  4425. }
  4426. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4427. /// anonymous struct or union AnonRecord into the owning context Owner
  4428. /// and scope S. This routine will be invoked just after we realize
  4429. /// that an unnamed union or struct is actually an anonymous union or
  4430. /// struct, e.g.,
  4431. ///
  4432. /// @code
  4433. /// union {
  4434. /// int i;
  4435. /// float f;
  4436. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4437. /// // f into the surrounding scope.x
  4438. /// @endcode
  4439. ///
  4440. /// This routine is recursive, injecting the names of nested anonymous
  4441. /// structs/unions into the owning context and scope as well.
  4442. static bool
  4443. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4444. RecordDecl *AnonRecord, AccessSpecifier AS,
  4445. SmallVectorImpl<NamedDecl *> &Chaining) {
  4446. bool Invalid = false;
  4447. // Look every FieldDecl and IndirectFieldDecl with a name.
  4448. for (auto *D : AnonRecord->decls()) {
  4449. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4450. cast<NamedDecl>(D)->getDeclName()) {
  4451. ValueDecl *VD = cast<ValueDecl>(D);
  4452. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4453. VD->getLocation(),
  4454. AnonRecord->isUnion())) {
  4455. // C++ [class.union]p2:
  4456. // The names of the members of an anonymous union shall be
  4457. // distinct from the names of any other entity in the
  4458. // scope in which the anonymous union is declared.
  4459. Invalid = true;
  4460. } else {
  4461. // C++ [class.union]p2:
  4462. // For the purpose of name lookup, after the anonymous union
  4463. // definition, the members of the anonymous union are
  4464. // considered to have been defined in the scope in which the
  4465. // anonymous union is declared.
  4466. unsigned OldChainingSize = Chaining.size();
  4467. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4468. Chaining.append(IF->chain_begin(), IF->chain_end());
  4469. else
  4470. Chaining.push_back(VD);
  4471. assert(Chaining.size() >= 2);
  4472. NamedDecl **NamedChain =
  4473. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4474. for (unsigned i = 0; i < Chaining.size(); i++)
  4475. NamedChain[i] = Chaining[i];
  4476. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4477. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4478. VD->getType(), {NamedChain, Chaining.size()});
  4479. for (const auto *Attr : VD->attrs())
  4480. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4481. IndirectField->setAccess(AS);
  4482. IndirectField->setImplicit();
  4483. SemaRef.PushOnScopeChains(IndirectField, S);
  4484. // That includes picking up the appropriate access specifier.
  4485. if (AS != AS_none) IndirectField->setAccess(AS);
  4486. Chaining.resize(OldChainingSize);
  4487. }
  4488. }
  4489. }
  4490. return Invalid;
  4491. }
  4492. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4493. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4494. /// illegal input values are mapped to SC_None.
  4495. static StorageClass
  4496. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4497. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4498. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4499. "Parser allowed 'typedef' as storage class VarDecl.");
  4500. switch (StorageClassSpec) {
  4501. case DeclSpec::SCS_unspecified: return SC_None;
  4502. case DeclSpec::SCS_extern:
  4503. if (DS.isExternInLinkageSpec())
  4504. return SC_None;
  4505. return SC_Extern;
  4506. case DeclSpec::SCS_static: return SC_Static;
  4507. case DeclSpec::SCS_auto: return SC_Auto;
  4508. case DeclSpec::SCS_register: return SC_Register;
  4509. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4510. // Illegal SCSs map to None: error reporting is up to the caller.
  4511. case DeclSpec::SCS_mutable: // Fall through.
  4512. case DeclSpec::SCS_typedef: return SC_None;
  4513. }
  4514. llvm_unreachable("unknown storage class specifier");
  4515. }
  4516. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4517. assert(Record->hasInClassInitializer());
  4518. for (const auto *I : Record->decls()) {
  4519. const auto *FD = dyn_cast<FieldDecl>(I);
  4520. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4521. FD = IFD->getAnonField();
  4522. if (FD && FD->hasInClassInitializer())
  4523. return FD->getLocation();
  4524. }
  4525. llvm_unreachable("couldn't find in-class initializer");
  4526. }
  4527. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4528. SourceLocation DefaultInitLoc) {
  4529. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4530. return;
  4531. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4532. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4533. }
  4534. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4535. CXXRecordDecl *AnonUnion) {
  4536. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4537. return;
  4538. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4539. }
  4540. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4541. /// anonymous structure or union. Anonymous unions are a C++ feature
  4542. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4543. /// are a C11 feature and GNU C++ extension.
  4544. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4545. AccessSpecifier AS,
  4546. RecordDecl *Record,
  4547. const PrintingPolicy &Policy) {
  4548. DeclContext *Owner = Record->getDeclContext();
  4549. // Diagnose whether this anonymous struct/union is an extension.
  4550. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4551. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4552. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4553. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4554. else if (!Record->isUnion() && !getLangOpts().C11)
  4555. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4556. // C and C++ require different kinds of checks for anonymous
  4557. // structs/unions.
  4558. bool Invalid = false;
  4559. if (getLangOpts().CPlusPlus) {
  4560. const char *PrevSpec = nullptr;
  4561. if (Record->isUnion()) {
  4562. // C++ [class.union]p6:
  4563. // C++17 [class.union.anon]p2:
  4564. // Anonymous unions declared in a named namespace or in the
  4565. // global namespace shall be declared static.
  4566. unsigned DiagID;
  4567. DeclContext *OwnerScope = Owner->getRedeclContext();
  4568. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4569. (OwnerScope->isTranslationUnit() ||
  4570. (OwnerScope->isNamespace() &&
  4571. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4572. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4573. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4574. // Recover by adding 'static'.
  4575. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4576. PrevSpec, DiagID, Policy);
  4577. }
  4578. // C++ [class.union]p6:
  4579. // A storage class is not allowed in a declaration of an
  4580. // anonymous union in a class scope.
  4581. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4582. isa<RecordDecl>(Owner)) {
  4583. Diag(DS.getStorageClassSpecLoc(),
  4584. diag::err_anonymous_union_with_storage_spec)
  4585. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4586. // Recover by removing the storage specifier.
  4587. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4588. SourceLocation(),
  4589. PrevSpec, DiagID, Context.getPrintingPolicy());
  4590. }
  4591. }
  4592. // Ignore const/volatile/restrict qualifiers.
  4593. if (DS.getTypeQualifiers()) {
  4594. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4595. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4596. << Record->isUnion() << "const"
  4597. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4598. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4599. Diag(DS.getVolatileSpecLoc(),
  4600. diag::ext_anonymous_struct_union_qualified)
  4601. << Record->isUnion() << "volatile"
  4602. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4603. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4604. Diag(DS.getRestrictSpecLoc(),
  4605. diag::ext_anonymous_struct_union_qualified)
  4606. << Record->isUnion() << "restrict"
  4607. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4608. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4609. Diag(DS.getAtomicSpecLoc(),
  4610. diag::ext_anonymous_struct_union_qualified)
  4611. << Record->isUnion() << "_Atomic"
  4612. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4613. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4614. Diag(DS.getUnalignedSpecLoc(),
  4615. diag::ext_anonymous_struct_union_qualified)
  4616. << Record->isUnion() << "__unaligned"
  4617. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4618. DS.ClearTypeQualifiers();
  4619. }
  4620. // C++ [class.union]p2:
  4621. // The member-specification of an anonymous union shall only
  4622. // define non-static data members. [Note: nested types and
  4623. // functions cannot be declared within an anonymous union. ]
  4624. for (auto *Mem : Record->decls()) {
  4625. // Ignore invalid declarations; we already diagnosed them.
  4626. if (Mem->isInvalidDecl())
  4627. continue;
  4628. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4629. // C++ [class.union]p3:
  4630. // An anonymous union shall not have private or protected
  4631. // members (clause 11).
  4632. assert(FD->getAccess() != AS_none);
  4633. if (FD->getAccess() != AS_public) {
  4634. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4635. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4636. Invalid = true;
  4637. }
  4638. // C++ [class.union]p1
  4639. // An object of a class with a non-trivial constructor, a non-trivial
  4640. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4641. // assignment operator cannot be a member of a union, nor can an
  4642. // array of such objects.
  4643. if (CheckNontrivialField(FD))
  4644. Invalid = true;
  4645. } else if (Mem->isImplicit()) {
  4646. // Any implicit members are fine.
  4647. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4648. // This is a type that showed up in an
  4649. // elaborated-type-specifier inside the anonymous struct or
  4650. // union, but which actually declares a type outside of the
  4651. // anonymous struct or union. It's okay.
  4652. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4653. if (!MemRecord->isAnonymousStructOrUnion() &&
  4654. MemRecord->getDeclName()) {
  4655. // Visual C++ allows type definition in anonymous struct or union.
  4656. if (getLangOpts().MicrosoftExt)
  4657. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4658. << Record->isUnion();
  4659. else {
  4660. // This is a nested type declaration.
  4661. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4662. << Record->isUnion();
  4663. Invalid = true;
  4664. }
  4665. } else {
  4666. // This is an anonymous type definition within another anonymous type.
  4667. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4668. // not part of standard C++.
  4669. Diag(MemRecord->getLocation(),
  4670. diag::ext_anonymous_record_with_anonymous_type)
  4671. << Record->isUnion();
  4672. }
  4673. } else if (isa<AccessSpecDecl>(Mem)) {
  4674. // Any access specifier is fine.
  4675. } else if (isa<StaticAssertDecl>(Mem)) {
  4676. // In C++1z, static_assert declarations are also fine.
  4677. } else {
  4678. // We have something that isn't a non-static data
  4679. // member. Complain about it.
  4680. unsigned DK = diag::err_anonymous_record_bad_member;
  4681. if (isa<TypeDecl>(Mem))
  4682. DK = diag::err_anonymous_record_with_type;
  4683. else if (isa<FunctionDecl>(Mem))
  4684. DK = diag::err_anonymous_record_with_function;
  4685. else if (isa<VarDecl>(Mem))
  4686. DK = diag::err_anonymous_record_with_static;
  4687. // Visual C++ allows type definition in anonymous struct or union.
  4688. if (getLangOpts().MicrosoftExt &&
  4689. DK == diag::err_anonymous_record_with_type)
  4690. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4691. << Record->isUnion();
  4692. else {
  4693. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4694. Invalid = true;
  4695. }
  4696. }
  4697. }
  4698. // C++11 [class.union]p8 (DR1460):
  4699. // At most one variant member of a union may have a
  4700. // brace-or-equal-initializer.
  4701. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4702. Owner->isRecord())
  4703. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4704. cast<CXXRecordDecl>(Record));
  4705. }
  4706. if (!Record->isUnion() && !Owner->isRecord()) {
  4707. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4708. << getLangOpts().CPlusPlus;
  4709. Invalid = true;
  4710. }
  4711. // C++ [dcl.dcl]p3:
  4712. // [If there are no declarators], and except for the declaration of an
  4713. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4714. // names into the program
  4715. // C++ [class.mem]p2:
  4716. // each such member-declaration shall either declare at least one member
  4717. // name of the class or declare at least one unnamed bit-field
  4718. //
  4719. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  4720. if (getLangOpts().CPlusPlus && Record->field_empty())
  4721. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  4722. // Mock up a declarator.
  4723. Declarator Dc(DS, DeclaratorContext::Member);
  4724. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4725. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4726. // Create a declaration for this anonymous struct/union.
  4727. NamedDecl *Anon = nullptr;
  4728. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4729. Anon = FieldDecl::Create(
  4730. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4731. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4732. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4733. /*InitStyle=*/ICIS_NoInit);
  4734. Anon->setAccess(AS);
  4735. ProcessDeclAttributes(S, Anon, Dc);
  4736. if (getLangOpts().CPlusPlus)
  4737. FieldCollector->Add(cast<FieldDecl>(Anon));
  4738. } else {
  4739. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4740. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4741. if (SCSpec == DeclSpec::SCS_mutable) {
  4742. // mutable can only appear on non-static class members, so it's always
  4743. // an error here
  4744. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4745. Invalid = true;
  4746. SC = SC_None;
  4747. }
  4748. assert(DS.getAttributes().empty() && "No attribute expected");
  4749. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4750. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4751. Context.getTypeDeclType(Record), TInfo, SC);
  4752. // Default-initialize the implicit variable. This initialization will be
  4753. // trivial in almost all cases, except if a union member has an in-class
  4754. // initializer:
  4755. // union { int n = 0; };
  4756. ActOnUninitializedDecl(Anon);
  4757. }
  4758. Anon->setImplicit();
  4759. // Mark this as an anonymous struct/union type.
  4760. Record->setAnonymousStructOrUnion(true);
  4761. // Add the anonymous struct/union object to the current
  4762. // context. We'll be referencing this object when we refer to one of
  4763. // its members.
  4764. Owner->addDecl(Anon);
  4765. // Inject the members of the anonymous struct/union into the owning
  4766. // context and into the identifier resolver chain for name lookup
  4767. // purposes.
  4768. SmallVector<NamedDecl*, 2> Chain;
  4769. Chain.push_back(Anon);
  4770. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4771. Invalid = true;
  4772. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4773. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4774. MangleNumberingContext *MCtx;
  4775. Decl *ManglingContextDecl;
  4776. std::tie(MCtx, ManglingContextDecl) =
  4777. getCurrentMangleNumberContext(NewVD->getDeclContext());
  4778. if (MCtx) {
  4779. Context.setManglingNumber(
  4780. NewVD, MCtx->getManglingNumber(
  4781. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4782. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4783. }
  4784. }
  4785. }
  4786. if (Invalid)
  4787. Anon->setInvalidDecl();
  4788. return Anon;
  4789. }
  4790. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4791. /// Microsoft C anonymous structure.
  4792. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4793. /// Example:
  4794. ///
  4795. /// struct A { int a; };
  4796. /// struct B { struct A; int b; };
  4797. ///
  4798. /// void foo() {
  4799. /// B var;
  4800. /// var.a = 3;
  4801. /// }
  4802. ///
  4803. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4804. RecordDecl *Record) {
  4805. assert(Record && "expected a record!");
  4806. // Mock up a declarator.
  4807. Declarator Dc(DS, DeclaratorContext::TypeName);
  4808. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4809. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4810. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4811. QualType RecTy = Context.getTypeDeclType(Record);
  4812. // Create a declaration for this anonymous struct.
  4813. NamedDecl *Anon =
  4814. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4815. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4816. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4817. /*InitStyle=*/ICIS_NoInit);
  4818. Anon->setImplicit();
  4819. // Add the anonymous struct object to the current context.
  4820. CurContext->addDecl(Anon);
  4821. // Inject the members of the anonymous struct into the current
  4822. // context and into the identifier resolver chain for name lookup
  4823. // purposes.
  4824. SmallVector<NamedDecl*, 2> Chain;
  4825. Chain.push_back(Anon);
  4826. RecordDecl *RecordDef = Record->getDefinition();
  4827. if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
  4828. diag::err_field_incomplete_or_sizeless) ||
  4829. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4830. AS_none, Chain)) {
  4831. Anon->setInvalidDecl();
  4832. ParentDecl->setInvalidDecl();
  4833. }
  4834. return Anon;
  4835. }
  4836. /// GetNameForDeclarator - Determine the full declaration name for the
  4837. /// given Declarator.
  4838. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4839. return GetNameFromUnqualifiedId(D.getName());
  4840. }
  4841. /// Retrieves the declaration name from a parsed unqualified-id.
  4842. DeclarationNameInfo
  4843. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4844. DeclarationNameInfo NameInfo;
  4845. NameInfo.setLoc(Name.StartLocation);
  4846. switch (Name.getKind()) {
  4847. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4848. case UnqualifiedIdKind::IK_Identifier:
  4849. NameInfo.setName(Name.Identifier);
  4850. return NameInfo;
  4851. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4852. // C++ [temp.deduct.guide]p3:
  4853. // The simple-template-id shall name a class template specialization.
  4854. // The template-name shall be the same identifier as the template-name
  4855. // of the simple-template-id.
  4856. // These together intend to imply that the template-name shall name a
  4857. // class template.
  4858. // FIXME: template<typename T> struct X {};
  4859. // template<typename T> using Y = X<T>;
  4860. // Y(int) -> Y<int>;
  4861. // satisfies these rules but does not name a class template.
  4862. TemplateName TN = Name.TemplateName.get().get();
  4863. auto *Template = TN.getAsTemplateDecl();
  4864. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4865. Diag(Name.StartLocation,
  4866. diag::err_deduction_guide_name_not_class_template)
  4867. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4868. if (Template)
  4869. Diag(Template->getLocation(), diag::note_template_decl_here);
  4870. return DeclarationNameInfo();
  4871. }
  4872. NameInfo.setName(
  4873. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4874. return NameInfo;
  4875. }
  4876. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4877. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4878. Name.OperatorFunctionId.Operator));
  4879. NameInfo.setCXXOperatorNameRange(SourceRange(
  4880. Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
  4881. return NameInfo;
  4882. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4883. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4884. Name.Identifier));
  4885. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4886. return NameInfo;
  4887. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4888. TypeSourceInfo *TInfo;
  4889. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4890. if (Ty.isNull())
  4891. return DeclarationNameInfo();
  4892. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4893. Context.getCanonicalType(Ty)));
  4894. NameInfo.setNamedTypeInfo(TInfo);
  4895. return NameInfo;
  4896. }
  4897. case UnqualifiedIdKind::IK_ConstructorName: {
  4898. TypeSourceInfo *TInfo;
  4899. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4900. if (Ty.isNull())
  4901. return DeclarationNameInfo();
  4902. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4903. Context.getCanonicalType(Ty)));
  4904. NameInfo.setNamedTypeInfo(TInfo);
  4905. return NameInfo;
  4906. }
  4907. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4908. // In well-formed code, we can only have a constructor
  4909. // template-id that refers to the current context, so go there
  4910. // to find the actual type being constructed.
  4911. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4912. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4913. return DeclarationNameInfo();
  4914. // Determine the type of the class being constructed.
  4915. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4916. // FIXME: Check two things: that the template-id names the same type as
  4917. // CurClassType, and that the template-id does not occur when the name
  4918. // was qualified.
  4919. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4920. Context.getCanonicalType(CurClassType)));
  4921. // FIXME: should we retrieve TypeSourceInfo?
  4922. NameInfo.setNamedTypeInfo(nullptr);
  4923. return NameInfo;
  4924. }
  4925. case UnqualifiedIdKind::IK_DestructorName: {
  4926. TypeSourceInfo *TInfo;
  4927. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4928. if (Ty.isNull())
  4929. return DeclarationNameInfo();
  4930. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4931. Context.getCanonicalType(Ty)));
  4932. NameInfo.setNamedTypeInfo(TInfo);
  4933. return NameInfo;
  4934. }
  4935. case UnqualifiedIdKind::IK_TemplateId: {
  4936. TemplateName TName = Name.TemplateId->Template.get();
  4937. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4938. return Context.getNameForTemplate(TName, TNameLoc);
  4939. }
  4940. } // switch (Name.getKind())
  4941. llvm_unreachable("Unknown name kind");
  4942. }
  4943. static QualType getCoreType(QualType Ty) {
  4944. do {
  4945. if (Ty->isPointerType() || Ty->isReferenceType())
  4946. Ty = Ty->getPointeeType();
  4947. else if (Ty->isArrayType())
  4948. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4949. else
  4950. return Ty.withoutLocalFastQualifiers();
  4951. } while (true);
  4952. }
  4953. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4954. /// and Definition have "nearly" matching parameters. This heuristic is
  4955. /// used to improve diagnostics in the case where an out-of-line function
  4956. /// definition doesn't match any declaration within the class or namespace.
  4957. /// Also sets Params to the list of indices to the parameters that differ
  4958. /// between the declaration and the definition. If hasSimilarParameters
  4959. /// returns true and Params is empty, then all of the parameters match.
  4960. static bool hasSimilarParameters(ASTContext &Context,
  4961. FunctionDecl *Declaration,
  4962. FunctionDecl *Definition,
  4963. SmallVectorImpl<unsigned> &Params) {
  4964. Params.clear();
  4965. if (Declaration->param_size() != Definition->param_size())
  4966. return false;
  4967. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4968. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4969. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4970. // The parameter types are identical
  4971. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4972. continue;
  4973. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4974. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4975. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4976. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4977. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4978. (DeclTyName && DeclTyName == DefTyName))
  4979. Params.push_back(Idx);
  4980. else // The two parameters aren't even close
  4981. return false;
  4982. }
  4983. return true;
  4984. }
  4985. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4986. /// declarator needs to be rebuilt in the current instantiation.
  4987. /// Any bits of declarator which appear before the name are valid for
  4988. /// consideration here. That's specifically the type in the decl spec
  4989. /// and the base type in any member-pointer chunks.
  4990. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4991. DeclarationName Name) {
  4992. // The types we specifically need to rebuild are:
  4993. // - typenames, typeofs, and decltypes
  4994. // - types which will become injected class names
  4995. // Of course, we also need to rebuild any type referencing such a
  4996. // type. It's safest to just say "dependent", but we call out a
  4997. // few cases here.
  4998. DeclSpec &DS = D.getMutableDeclSpec();
  4999. switch (DS.getTypeSpecType()) {
  5000. case DeclSpec::TST_typename:
  5001. case DeclSpec::TST_typeofType:
  5002. case DeclSpec::TST_underlyingType:
  5003. case DeclSpec::TST_atomic: {
  5004. // Grab the type from the parser.
  5005. TypeSourceInfo *TSI = nullptr;
  5006. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  5007. if (T.isNull() || !T->isInstantiationDependentType()) break;
  5008. // Make sure there's a type source info. This isn't really much
  5009. // of a waste; most dependent types should have type source info
  5010. // attached already.
  5011. if (!TSI)
  5012. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  5013. // Rebuild the type in the current instantiation.
  5014. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  5015. if (!TSI) return true;
  5016. // Store the new type back in the decl spec.
  5017. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  5018. DS.UpdateTypeRep(LocType);
  5019. break;
  5020. }
  5021. case DeclSpec::TST_decltype:
  5022. case DeclSpec::TST_typeofExpr: {
  5023. Expr *E = DS.getRepAsExpr();
  5024. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  5025. if (Result.isInvalid()) return true;
  5026. DS.UpdateExprRep(Result.get());
  5027. break;
  5028. }
  5029. default:
  5030. // Nothing to do for these decl specs.
  5031. break;
  5032. }
  5033. // It doesn't matter what order we do this in.
  5034. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  5035. DeclaratorChunk &Chunk = D.getTypeObject(I);
  5036. // The only type information in the declarator which can come
  5037. // before the declaration name is the base type of a member
  5038. // pointer.
  5039. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  5040. continue;
  5041. // Rebuild the scope specifier in-place.
  5042. CXXScopeSpec &SS = Chunk.Mem.Scope();
  5043. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  5044. return true;
  5045. }
  5046. return false;
  5047. }
  5048. /// Returns true if the declaration is declared in a system header or from a
  5049. /// system macro.
  5050. static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
  5051. return SM.isInSystemHeader(D->getLocation()) ||
  5052. SM.isInSystemMacro(D->getLocation());
  5053. }
  5054. void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
  5055. // Avoid warning twice on the same identifier, and don't warn on redeclaration
  5056. // of system decl.
  5057. if (D->getPreviousDecl() || D->isImplicit())
  5058. return;
  5059. ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
  5060. if (Status != ReservedIdentifierStatus::NotReserved &&
  5061. !isFromSystemHeader(Context.getSourceManager(), D)) {
  5062. Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
  5063. << D << static_cast<int>(Status);
  5064. }
  5065. }
  5066. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  5067. D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
  5068. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  5069. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  5070. Dcl && Dcl->getDeclContext()->isFileContext())
  5071. Dcl->setTopLevelDeclInObjCContainer();
  5072. return Dcl;
  5073. }
  5074. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  5075. /// If T is the name of a class, then each of the following shall have a
  5076. /// name different from T:
  5077. /// - every static data member of class T;
  5078. /// - every member function of class T
  5079. /// - every member of class T that is itself a type;
  5080. /// \returns true if the declaration name violates these rules.
  5081. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  5082. DeclarationNameInfo NameInfo) {
  5083. DeclarationName Name = NameInfo.getName();
  5084. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  5085. while (Record && Record->isAnonymousStructOrUnion())
  5086. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  5087. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  5088. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  5089. return true;
  5090. }
  5091. return false;
  5092. }
  5093. /// Diagnose a declaration whose declarator-id has the given
  5094. /// nested-name-specifier.
  5095. ///
  5096. /// \param SS The nested-name-specifier of the declarator-id.
  5097. ///
  5098. /// \param DC The declaration context to which the nested-name-specifier
  5099. /// resolves.
  5100. ///
  5101. /// \param Name The name of the entity being declared.
  5102. ///
  5103. /// \param Loc The location of the name of the entity being declared.
  5104. ///
  5105. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  5106. /// we're declaring an explicit / partial specialization / instantiation.
  5107. ///
  5108. /// \returns true if we cannot safely recover from this error, false otherwise.
  5109. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  5110. DeclarationName Name,
  5111. SourceLocation Loc, bool IsTemplateId) {
  5112. DeclContext *Cur = CurContext;
  5113. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  5114. Cur = Cur->getParent();
  5115. // If the user provided a superfluous scope specifier that refers back to the
  5116. // class in which the entity is already declared, diagnose and ignore it.
  5117. //
  5118. // class X {
  5119. // void X::f();
  5120. // };
  5121. //
  5122. // Note, it was once ill-formed to give redundant qualification in all
  5123. // contexts, but that rule was removed by DR482.
  5124. if (Cur->Equals(DC)) {
  5125. if (Cur->isRecord()) {
  5126. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  5127. : diag::err_member_extra_qualification)
  5128. << Name << FixItHint::CreateRemoval(SS.getRange());
  5129. SS.clear();
  5130. } else {
  5131. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  5132. }
  5133. return false;
  5134. }
  5135. // Check whether the qualifying scope encloses the scope of the original
  5136. // declaration. For a template-id, we perform the checks in
  5137. // CheckTemplateSpecializationScope.
  5138. if (!Cur->Encloses(DC) && !IsTemplateId) {
  5139. if (Cur->isRecord())
  5140. Diag(Loc, diag::err_member_qualification)
  5141. << Name << SS.getRange();
  5142. else if (isa<TranslationUnitDecl>(DC))
  5143. Diag(Loc, diag::err_invalid_declarator_global_scope)
  5144. << Name << SS.getRange();
  5145. else if (isa<FunctionDecl>(Cur))
  5146. Diag(Loc, diag::err_invalid_declarator_in_function)
  5147. << Name << SS.getRange();
  5148. else if (isa<BlockDecl>(Cur))
  5149. Diag(Loc, diag::err_invalid_declarator_in_block)
  5150. << Name << SS.getRange();
  5151. else if (isa<ExportDecl>(Cur)) {
  5152. if (!isa<NamespaceDecl>(DC))
  5153. Diag(Loc, diag::err_export_non_namespace_scope_name)
  5154. << Name << SS.getRange();
  5155. else
  5156. // The cases that DC is not NamespaceDecl should be handled in
  5157. // CheckRedeclarationExported.
  5158. return false;
  5159. } else
  5160. Diag(Loc, diag::err_invalid_declarator_scope)
  5161. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  5162. return true;
  5163. }
  5164. if (Cur->isRecord()) {
  5165. // Cannot qualify members within a class.
  5166. Diag(Loc, diag::err_member_qualification)
  5167. << Name << SS.getRange();
  5168. SS.clear();
  5169. // C++ constructors and destructors with incorrect scopes can break
  5170. // our AST invariants by having the wrong underlying types. If
  5171. // that's the case, then drop this declaration entirely.
  5172. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  5173. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  5174. !Context.hasSameType(Name.getCXXNameType(),
  5175. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  5176. return true;
  5177. return false;
  5178. }
  5179. // C++11 [dcl.meaning]p1:
  5180. // [...] "The nested-name-specifier of the qualified declarator-id shall
  5181. // not begin with a decltype-specifer"
  5182. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  5183. while (SpecLoc.getPrefix())
  5184. SpecLoc = SpecLoc.getPrefix();
  5185. if (isa_and_nonnull<DecltypeType>(
  5186. SpecLoc.getNestedNameSpecifier()->getAsType()))
  5187. Diag(Loc, diag::err_decltype_in_declarator)
  5188. << SpecLoc.getTypeLoc().getSourceRange();
  5189. return false;
  5190. }
  5191. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  5192. MultiTemplateParamsArg TemplateParamLists) {
  5193. // TODO: consider using NameInfo for diagnostic.
  5194. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  5195. DeclarationName Name = NameInfo.getName();
  5196. // All of these full declarators require an identifier. If it doesn't have
  5197. // one, the ParsedFreeStandingDeclSpec action should be used.
  5198. if (D.isDecompositionDeclarator()) {
  5199. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  5200. } else if (!Name) {
  5201. if (!D.isInvalidType()) // Reject this if we think it is valid.
  5202. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  5203. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  5204. return nullptr;
  5205. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  5206. return nullptr;
  5207. // The scope passed in may not be a decl scope. Zip up the scope tree until
  5208. // we find one that is.
  5209. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  5210. (S->getFlags() & Scope::TemplateParamScope) != 0)
  5211. S = S->getParent();
  5212. DeclContext *DC = CurContext;
  5213. if (D.getCXXScopeSpec().isInvalid())
  5214. D.setInvalidType();
  5215. else if (D.getCXXScopeSpec().isSet()) {
  5216. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  5217. UPPC_DeclarationQualifier))
  5218. return nullptr;
  5219. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  5220. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  5221. if (!DC || isa<EnumDecl>(DC)) {
  5222. // If we could not compute the declaration context, it's because the
  5223. // declaration context is dependent but does not refer to a class,
  5224. // class template, or class template partial specialization. Complain
  5225. // and return early, to avoid the coming semantic disaster.
  5226. Diag(D.getIdentifierLoc(),
  5227. diag::err_template_qualified_declarator_no_match)
  5228. << D.getCXXScopeSpec().getScopeRep()
  5229. << D.getCXXScopeSpec().getRange();
  5230. return nullptr;
  5231. }
  5232. bool IsDependentContext = DC->isDependentContext();
  5233. if (!IsDependentContext &&
  5234. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  5235. return nullptr;
  5236. // If a class is incomplete, do not parse entities inside it.
  5237. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  5238. Diag(D.getIdentifierLoc(),
  5239. diag::err_member_def_undefined_record)
  5240. << Name << DC << D.getCXXScopeSpec().getRange();
  5241. return nullptr;
  5242. }
  5243. if (!D.getDeclSpec().isFriendSpecified()) {
  5244. if (diagnoseQualifiedDeclaration(
  5245. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  5246. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  5247. if (DC->isRecord())
  5248. return nullptr;
  5249. D.setInvalidType();
  5250. }
  5251. }
  5252. // Check whether we need to rebuild the type of the given
  5253. // declaration in the current instantiation.
  5254. if (EnteringContext && IsDependentContext &&
  5255. TemplateParamLists.size() != 0) {
  5256. ContextRAII SavedContext(*this, DC);
  5257. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  5258. D.setInvalidType();
  5259. }
  5260. }
  5261. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5262. QualType R = TInfo->getType();
  5263. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  5264. UPPC_DeclarationType))
  5265. D.setInvalidType();
  5266. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  5267. forRedeclarationInCurContext());
  5268. // See if this is a redefinition of a variable in the same scope.
  5269. if (!D.getCXXScopeSpec().isSet()) {
  5270. bool IsLinkageLookup = false;
  5271. bool CreateBuiltins = false;
  5272. // If the declaration we're planning to build will be a function
  5273. // or object with linkage, then look for another declaration with
  5274. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  5275. //
  5276. // If the declaration we're planning to build will be declared with
  5277. // external linkage in the translation unit, create any builtin with
  5278. // the same name.
  5279. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  5280. /* Do nothing*/;
  5281. else if (CurContext->isFunctionOrMethod() &&
  5282. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  5283. R->isFunctionType())) {
  5284. IsLinkageLookup = true;
  5285. CreateBuiltins =
  5286. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  5287. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  5288. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  5289. CreateBuiltins = true;
  5290. if (IsLinkageLookup) {
  5291. Previous.clear(LookupRedeclarationWithLinkage);
  5292. Previous.setRedeclarationKind(ForExternalRedeclaration);
  5293. }
  5294. LookupName(Previous, S, CreateBuiltins);
  5295. } else { // Something like "int foo::x;"
  5296. LookupQualifiedName(Previous, DC);
  5297. // C++ [dcl.meaning]p1:
  5298. // When the declarator-id is qualified, the declaration shall refer to a
  5299. // previously declared member of the class or namespace to which the
  5300. // qualifier refers (or, in the case of a namespace, of an element of the
  5301. // inline namespace set of that namespace (7.3.1)) or to a specialization
  5302. // thereof; [...]
  5303. //
  5304. // Note that we already checked the context above, and that we do not have
  5305. // enough information to make sure that Previous contains the declaration
  5306. // we want to match. For example, given:
  5307. //
  5308. // class X {
  5309. // void f();
  5310. // void f(float);
  5311. // };
  5312. //
  5313. // void X::f(int) { } // ill-formed
  5314. //
  5315. // In this case, Previous will point to the overload set
  5316. // containing the two f's declared in X, but neither of them
  5317. // matches.
  5318. // C++ [dcl.meaning]p1:
  5319. // [...] the member shall not merely have been introduced by a
  5320. // using-declaration in the scope of the class or namespace nominated by
  5321. // the nested-name-specifier of the declarator-id.
  5322. RemoveUsingDecls(Previous);
  5323. }
  5324. if (Previous.isSingleResult() &&
  5325. Previous.getFoundDecl()->isTemplateParameter()) {
  5326. // Maybe we will complain about the shadowed template parameter.
  5327. if (!D.isInvalidType())
  5328. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  5329. Previous.getFoundDecl());
  5330. // Just pretend that we didn't see the previous declaration.
  5331. Previous.clear();
  5332. }
  5333. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  5334. // Forget that the previous declaration is the injected-class-name.
  5335. Previous.clear();
  5336. // In C++, the previous declaration we find might be a tag type
  5337. // (class or enum). In this case, the new declaration will hide the
  5338. // tag type. Note that this applies to functions, function templates, and
  5339. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  5340. if (Previous.isSingleTagDecl() &&
  5341. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  5342. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  5343. Previous.clear();
  5344. // Check that there are no default arguments other than in the parameters
  5345. // of a function declaration (C++ only).
  5346. if (getLangOpts().CPlusPlus)
  5347. CheckExtraCXXDefaultArguments(D);
  5348. NamedDecl *New;
  5349. bool AddToScope = true;
  5350. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5351. if (TemplateParamLists.size()) {
  5352. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5353. return nullptr;
  5354. }
  5355. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5356. } else if (R->isFunctionType()) {
  5357. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5358. TemplateParamLists,
  5359. AddToScope);
  5360. } else {
  5361. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5362. AddToScope);
  5363. }
  5364. if (!New)
  5365. return nullptr;
  5366. // If this has an identifier and is not a function template specialization,
  5367. // add it to the scope stack.
  5368. if (New->getDeclName() && AddToScope)
  5369. PushOnScopeChains(New, S);
  5370. if (isInOpenMPDeclareTargetContext())
  5371. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5372. return New;
  5373. }
  5374. /// Helper method to turn variable array types into constant array
  5375. /// types in certain situations which would otherwise be errors (for
  5376. /// GCC compatibility).
  5377. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5378. ASTContext &Context,
  5379. bool &SizeIsNegative,
  5380. llvm::APSInt &Oversized) {
  5381. // This method tries to turn a variable array into a constant
  5382. // array even when the size isn't an ICE. This is necessary
  5383. // for compatibility with code that depends on gcc's buggy
  5384. // constant expression folding, like struct {char x[(int)(char*)2];}
  5385. SizeIsNegative = false;
  5386. Oversized = 0;
  5387. if (T->isDependentType())
  5388. return QualType();
  5389. QualifierCollector Qs;
  5390. const Type *Ty = Qs.strip(T);
  5391. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5392. QualType Pointee = PTy->getPointeeType();
  5393. QualType FixedType =
  5394. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5395. Oversized);
  5396. if (FixedType.isNull()) return FixedType;
  5397. FixedType = Context.getPointerType(FixedType);
  5398. return Qs.apply(Context, FixedType);
  5399. }
  5400. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5401. QualType Inner = PTy->getInnerType();
  5402. QualType FixedType =
  5403. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5404. Oversized);
  5405. if (FixedType.isNull()) return FixedType;
  5406. FixedType = Context.getParenType(FixedType);
  5407. return Qs.apply(Context, FixedType);
  5408. }
  5409. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5410. if (!VLATy)
  5411. return QualType();
  5412. QualType ElemTy = VLATy->getElementType();
  5413. if (ElemTy->isVariablyModifiedType()) {
  5414. ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
  5415. SizeIsNegative, Oversized);
  5416. if (ElemTy.isNull())
  5417. return QualType();
  5418. }
  5419. Expr::EvalResult Result;
  5420. if (!VLATy->getSizeExpr() ||
  5421. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5422. return QualType();
  5423. llvm::APSInt Res = Result.Val.getInt();
  5424. // Check whether the array size is negative.
  5425. if (Res.isSigned() && Res.isNegative()) {
  5426. SizeIsNegative = true;
  5427. return QualType();
  5428. }
  5429. // Check whether the array is too large to be addressed.
  5430. unsigned ActiveSizeBits =
  5431. (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
  5432. !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
  5433. ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
  5434. : Res.getActiveBits();
  5435. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5436. Oversized = Res;
  5437. return QualType();
  5438. }
  5439. QualType FoldedArrayType = Context.getConstantArrayType(
  5440. ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
  5441. return Qs.apply(Context, FoldedArrayType);
  5442. }
  5443. static void
  5444. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5445. SrcTL = SrcTL.getUnqualifiedLoc();
  5446. DstTL = DstTL.getUnqualifiedLoc();
  5447. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5448. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5449. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5450. DstPTL.getPointeeLoc());
  5451. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5452. return;
  5453. }
  5454. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5455. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5456. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5457. DstPTL.getInnerLoc());
  5458. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5459. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5460. return;
  5461. }
  5462. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5463. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5464. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5465. TypeLoc DstElemTL = DstATL.getElementLoc();
  5466. if (VariableArrayTypeLoc SrcElemATL =
  5467. SrcElemTL.getAs<VariableArrayTypeLoc>()) {
  5468. ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
  5469. FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
  5470. } else {
  5471. DstElemTL.initializeFullCopy(SrcElemTL);
  5472. }
  5473. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5474. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5475. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5476. }
  5477. /// Helper method to turn variable array types into constant array
  5478. /// types in certain situations which would otherwise be errors (for
  5479. /// GCC compatibility).
  5480. static TypeSourceInfo*
  5481. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5482. ASTContext &Context,
  5483. bool &SizeIsNegative,
  5484. llvm::APSInt &Oversized) {
  5485. QualType FixedTy
  5486. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5487. SizeIsNegative, Oversized);
  5488. if (FixedTy.isNull())
  5489. return nullptr;
  5490. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5491. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5492. FixedTInfo->getTypeLoc());
  5493. return FixedTInfo;
  5494. }
  5495. /// Attempt to fold a variable-sized type to a constant-sized type, returning
  5496. /// true if we were successful.
  5497. bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
  5498. QualType &T, SourceLocation Loc,
  5499. unsigned FailedFoldDiagID) {
  5500. bool SizeIsNegative;
  5501. llvm::APSInt Oversized;
  5502. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  5503. TInfo, Context, SizeIsNegative, Oversized);
  5504. if (FixedTInfo) {
  5505. Diag(Loc, diag::ext_vla_folded_to_constant);
  5506. TInfo = FixedTInfo;
  5507. T = FixedTInfo->getType();
  5508. return true;
  5509. }
  5510. if (SizeIsNegative)
  5511. Diag(Loc, diag::err_typecheck_negative_array_size);
  5512. else if (Oversized.getBoolValue())
  5513. Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
  5514. else if (FailedFoldDiagID)
  5515. Diag(Loc, FailedFoldDiagID);
  5516. return false;
  5517. }
  5518. /// Register the given locally-scoped extern "C" declaration so
  5519. /// that it can be found later for redeclarations. We include any extern "C"
  5520. /// declaration that is not visible in the translation unit here, not just
  5521. /// function-scope declarations.
  5522. void
  5523. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5524. if (!getLangOpts().CPlusPlus &&
  5525. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5526. // Don't need to track declarations in the TU in C.
  5527. return;
  5528. // Note that we have a locally-scoped external with this name.
  5529. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5530. }
  5531. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5532. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5533. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5534. return Result.empty() ? nullptr : *Result.begin();
  5535. }
  5536. /// Diagnose function specifiers on a declaration of an identifier that
  5537. /// does not identify a function.
  5538. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5539. // FIXME: We should probably indicate the identifier in question to avoid
  5540. // confusion for constructs like "virtual int a(), b;"
  5541. if (DS.isVirtualSpecified())
  5542. Diag(DS.getVirtualSpecLoc(),
  5543. diag::err_virtual_non_function);
  5544. if (DS.hasExplicitSpecifier())
  5545. Diag(DS.getExplicitSpecLoc(),
  5546. diag::err_explicit_non_function);
  5547. if (DS.isNoreturnSpecified())
  5548. Diag(DS.getNoreturnSpecLoc(),
  5549. diag::err_noreturn_non_function);
  5550. }
  5551. NamedDecl*
  5552. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5553. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5554. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5555. if (D.getCXXScopeSpec().isSet()) {
  5556. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5557. << D.getCXXScopeSpec().getRange();
  5558. D.setInvalidType();
  5559. // Pretend we didn't see the scope specifier.
  5560. DC = CurContext;
  5561. Previous.clear();
  5562. }
  5563. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5564. if (D.getDeclSpec().isInlineSpecified())
  5565. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5566. << getLangOpts().CPlusPlus17;
  5567. if (D.getDeclSpec().hasConstexprSpecifier())
  5568. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5569. << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  5570. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5571. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5572. Diag(D.getName().StartLocation,
  5573. diag::err_deduction_guide_invalid_specifier)
  5574. << "typedef";
  5575. else
  5576. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5577. << D.getName().getSourceRange();
  5578. return nullptr;
  5579. }
  5580. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5581. if (!NewTD) return nullptr;
  5582. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5583. ProcessDeclAttributes(S, NewTD, D);
  5584. CheckTypedefForVariablyModifiedType(S, NewTD);
  5585. bool Redeclaration = D.isRedeclaration();
  5586. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5587. D.setRedeclaration(Redeclaration);
  5588. return ND;
  5589. }
  5590. void
  5591. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5592. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5593. // then it shall have block scope.
  5594. // Note that variably modified types must be fixed before merging the decl so
  5595. // that redeclarations will match.
  5596. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5597. QualType T = TInfo->getType();
  5598. if (T->isVariablyModifiedType()) {
  5599. setFunctionHasBranchProtectedScope();
  5600. if (S->getFnParent() == nullptr) {
  5601. bool SizeIsNegative;
  5602. llvm::APSInt Oversized;
  5603. TypeSourceInfo *FixedTInfo =
  5604. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5605. SizeIsNegative,
  5606. Oversized);
  5607. if (FixedTInfo) {
  5608. Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
  5609. NewTD->setTypeSourceInfo(FixedTInfo);
  5610. } else {
  5611. if (SizeIsNegative)
  5612. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5613. else if (T->isVariableArrayType())
  5614. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5615. else if (Oversized.getBoolValue())
  5616. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5617. << toString(Oversized, 10);
  5618. else
  5619. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5620. NewTD->setInvalidDecl();
  5621. }
  5622. }
  5623. }
  5624. }
  5625. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5626. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5627. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5628. NamedDecl*
  5629. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5630. LookupResult &Previous, bool &Redeclaration) {
  5631. // Find the shadowed declaration before filtering for scope.
  5632. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5633. // Merge the decl with the existing one if appropriate. If the decl is
  5634. // in an outer scope, it isn't the same thing.
  5635. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5636. /*AllowInlineNamespace*/false);
  5637. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5638. if (!Previous.empty()) {
  5639. Redeclaration = true;
  5640. MergeTypedefNameDecl(S, NewTD, Previous);
  5641. } else {
  5642. inferGslPointerAttribute(NewTD);
  5643. }
  5644. if (ShadowedDecl && !Redeclaration)
  5645. CheckShadow(NewTD, ShadowedDecl, Previous);
  5646. // If this is the C FILE type, notify the AST context.
  5647. if (IdentifierInfo *II = NewTD->getIdentifier())
  5648. if (!NewTD->isInvalidDecl() &&
  5649. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5650. if (II->isStr("FILE"))
  5651. Context.setFILEDecl(NewTD);
  5652. else if (II->isStr("jmp_buf"))
  5653. Context.setjmp_bufDecl(NewTD);
  5654. else if (II->isStr("sigjmp_buf"))
  5655. Context.setsigjmp_bufDecl(NewTD);
  5656. else if (II->isStr("ucontext_t"))
  5657. Context.setucontext_tDecl(NewTD);
  5658. }
  5659. return NewTD;
  5660. }
  5661. /// Determines whether the given declaration is an out-of-scope
  5662. /// previous declaration.
  5663. ///
  5664. /// This routine should be invoked when name lookup has found a
  5665. /// previous declaration (PrevDecl) that is not in the scope where a
  5666. /// new declaration by the same name is being introduced. If the new
  5667. /// declaration occurs in a local scope, previous declarations with
  5668. /// linkage may still be considered previous declarations (C99
  5669. /// 6.2.2p4-5, C++ [basic.link]p6).
  5670. ///
  5671. /// \param PrevDecl the previous declaration found by name
  5672. /// lookup
  5673. ///
  5674. /// \param DC the context in which the new declaration is being
  5675. /// declared.
  5676. ///
  5677. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5678. /// for a new delcaration with the same name.
  5679. static bool
  5680. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5681. ASTContext &Context) {
  5682. if (!PrevDecl)
  5683. return false;
  5684. if (!PrevDecl->hasLinkage())
  5685. return false;
  5686. if (Context.getLangOpts().CPlusPlus) {
  5687. // C++ [basic.link]p6:
  5688. // If there is a visible declaration of an entity with linkage
  5689. // having the same name and type, ignoring entities declared
  5690. // outside the innermost enclosing namespace scope, the block
  5691. // scope declaration declares that same entity and receives the
  5692. // linkage of the previous declaration.
  5693. DeclContext *OuterContext = DC->getRedeclContext();
  5694. if (!OuterContext->isFunctionOrMethod())
  5695. // This rule only applies to block-scope declarations.
  5696. return false;
  5697. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5698. if (PrevOuterContext->isRecord())
  5699. // We found a member function: ignore it.
  5700. return false;
  5701. // Find the innermost enclosing namespace for the new and
  5702. // previous declarations.
  5703. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5704. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5705. // The previous declaration is in a different namespace, so it
  5706. // isn't the same function.
  5707. if (!OuterContext->Equals(PrevOuterContext))
  5708. return false;
  5709. }
  5710. return true;
  5711. }
  5712. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5713. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5714. if (!SS.isSet()) return;
  5715. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5716. }
  5717. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5718. QualType type = decl->getType();
  5719. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5720. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5721. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5722. unsigned kind = -1U;
  5723. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5724. if (var->hasAttr<BlocksAttr>())
  5725. kind = 0; // __block
  5726. else if (!var->hasLocalStorage())
  5727. kind = 1; // global
  5728. } else if (isa<ObjCIvarDecl>(decl)) {
  5729. kind = 3; // ivar
  5730. } else if (isa<FieldDecl>(decl)) {
  5731. kind = 2; // field
  5732. }
  5733. if (kind != -1U) {
  5734. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5735. << kind;
  5736. }
  5737. } else if (lifetime == Qualifiers::OCL_None) {
  5738. // Try to infer lifetime.
  5739. if (!type->isObjCLifetimeType())
  5740. return false;
  5741. lifetime = type->getObjCARCImplicitLifetime();
  5742. type = Context.getLifetimeQualifiedType(type, lifetime);
  5743. decl->setType(type);
  5744. }
  5745. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5746. // Thread-local variables cannot have lifetime.
  5747. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5748. var->getTLSKind()) {
  5749. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5750. << var->getType();
  5751. return true;
  5752. }
  5753. }
  5754. return false;
  5755. }
  5756. void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
  5757. if (Decl->getType().hasAddressSpace())
  5758. return;
  5759. if (Decl->getType()->isDependentType())
  5760. return;
  5761. if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
  5762. QualType Type = Var->getType();
  5763. if (Type->isSamplerT() || Type->isVoidType())
  5764. return;
  5765. LangAS ImplAS = LangAS::opencl_private;
  5766. // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
  5767. // __opencl_c_program_scope_global_variables feature, the address space
  5768. // for a variable at program scope or a static or extern variable inside
  5769. // a function are inferred to be __global.
  5770. if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
  5771. Var->hasGlobalStorage())
  5772. ImplAS = LangAS::opencl_global;
  5773. // If the original type from a decayed type is an array type and that array
  5774. // type has no address space yet, deduce it now.
  5775. if (auto DT = dyn_cast<DecayedType>(Type)) {
  5776. auto OrigTy = DT->getOriginalType();
  5777. if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
  5778. // Add the address space to the original array type and then propagate
  5779. // that to the element type through `getAsArrayType`.
  5780. OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
  5781. OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
  5782. // Re-generate the decayed type.
  5783. Type = Context.getDecayedType(OrigTy);
  5784. }
  5785. }
  5786. Type = Context.getAddrSpaceQualType(Type, ImplAS);
  5787. // Apply any qualifiers (including address space) from the array type to
  5788. // the element type. This implements C99 6.7.3p8: "If the specification of
  5789. // an array type includes any type qualifiers, the element type is so
  5790. // qualified, not the array type."
  5791. if (Type->isArrayType())
  5792. Type = QualType(Context.getAsArrayType(Type), 0);
  5793. Decl->setType(Type);
  5794. }
  5795. }
  5796. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5797. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5798. // the wrong linkage.
  5799. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5800. // 'weak' only applies to declarations with external linkage.
  5801. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5802. if (!ND.isExternallyVisible()) {
  5803. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5804. ND.dropAttr<WeakAttr>();
  5805. }
  5806. }
  5807. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5808. if (ND.isExternallyVisible()) {
  5809. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5810. ND.dropAttr<WeakRefAttr>();
  5811. ND.dropAttr<AliasAttr>();
  5812. }
  5813. }
  5814. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5815. if (VD->hasInit()) {
  5816. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5817. assert(VD->isThisDeclarationADefinition() &&
  5818. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5819. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5820. VD->dropAttr<AliasAttr>();
  5821. }
  5822. }
  5823. }
  5824. // 'selectany' only applies to externally visible variable declarations.
  5825. // It does not apply to functions.
  5826. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5827. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5828. S.Diag(Attr->getLocation(),
  5829. diag::err_attribute_selectany_non_extern_data);
  5830. ND.dropAttr<SelectAnyAttr>();
  5831. }
  5832. }
  5833. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5834. auto *VD = dyn_cast<VarDecl>(&ND);
  5835. bool IsAnonymousNS = false;
  5836. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5837. if (VD) {
  5838. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  5839. while (NS && !IsAnonymousNS) {
  5840. IsAnonymousNS = NS->isAnonymousNamespace();
  5841. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  5842. }
  5843. }
  5844. // dll attributes require external linkage. Static locals may have external
  5845. // linkage but still cannot be explicitly imported or exported.
  5846. // In Microsoft mode, a variable defined in anonymous namespace must have
  5847. // external linkage in order to be exported.
  5848. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  5849. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  5850. (!AnonNSInMicrosoftMode &&
  5851. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  5852. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5853. << &ND << Attr;
  5854. ND.setInvalidDecl();
  5855. }
  5856. }
  5857. // Check the attributes on the function type, if any.
  5858. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5859. // Don't declare this variable in the second operand of the for-statement;
  5860. // GCC miscompiles that by ending its lifetime before evaluating the
  5861. // third operand. See gcc.gnu.org/PR86769.
  5862. AttributedTypeLoc ATL;
  5863. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5864. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5865. TL = ATL.getModifiedLoc()) {
  5866. // The [[lifetimebound]] attribute can be applied to the implicit object
  5867. // parameter of a non-static member function (other than a ctor or dtor)
  5868. // by applying it to the function type.
  5869. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5870. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5871. if (!MD || MD->isStatic()) {
  5872. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5873. << !MD << A->getRange();
  5874. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5875. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5876. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5877. }
  5878. }
  5879. }
  5880. }
  5881. }
  5882. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5883. NamedDecl *NewDecl,
  5884. bool IsSpecialization,
  5885. bool IsDefinition) {
  5886. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5887. return;
  5888. bool IsTemplate = false;
  5889. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5890. OldDecl = OldTD->getTemplatedDecl();
  5891. IsTemplate = true;
  5892. if (!IsSpecialization)
  5893. IsDefinition = false;
  5894. }
  5895. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5896. NewDecl = NewTD->getTemplatedDecl();
  5897. IsTemplate = true;
  5898. }
  5899. if (!OldDecl || !NewDecl)
  5900. return;
  5901. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5902. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5903. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5904. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5905. // dllimport and dllexport are inheritable attributes so we have to exclude
  5906. // inherited attribute instances.
  5907. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5908. (NewExportAttr && !NewExportAttr->isInherited());
  5909. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5910. // the only exception being explicit specializations.
  5911. // Implicitly generated declarations are also excluded for now because there
  5912. // is no other way to switch these to use dllimport or dllexport.
  5913. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5914. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5915. // Allow with a warning for free functions and global variables.
  5916. bool JustWarn = false;
  5917. if (!OldDecl->isCXXClassMember()) {
  5918. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5919. if (VD && !VD->getDescribedVarTemplate())
  5920. JustWarn = true;
  5921. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5922. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5923. JustWarn = true;
  5924. }
  5925. // We cannot change a declaration that's been used because IR has already
  5926. // been emitted. Dllimported functions will still work though (modulo
  5927. // address equality) as they can use the thunk.
  5928. if (OldDecl->isUsed())
  5929. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5930. JustWarn = false;
  5931. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5932. : diag::err_attribute_dll_redeclaration;
  5933. S.Diag(NewDecl->getLocation(), DiagID)
  5934. << NewDecl
  5935. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5936. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5937. if (!JustWarn) {
  5938. NewDecl->setInvalidDecl();
  5939. return;
  5940. }
  5941. }
  5942. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5943. // exceptions being inline function definitions (except for function
  5944. // templates), local extern declarations, qualified friend declarations or
  5945. // special MSVC extension: in the last case, the declaration is treated as if
  5946. // it were marked dllexport.
  5947. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5948. bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
  5949. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5950. // Ignore static data because out-of-line definitions are diagnosed
  5951. // separately.
  5952. IsStaticDataMember = VD->isStaticDataMember();
  5953. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5954. VarDecl::DeclarationOnly;
  5955. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5956. IsInline = FD->isInlined();
  5957. IsQualifiedFriend = FD->getQualifier() &&
  5958. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5959. }
  5960. if (OldImportAttr && !HasNewAttr &&
  5961. (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
  5962. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5963. if (IsMicrosoftABI && IsDefinition) {
  5964. S.Diag(NewDecl->getLocation(),
  5965. diag::warn_redeclaration_without_import_attribute)
  5966. << NewDecl;
  5967. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5968. NewDecl->dropAttr<DLLImportAttr>();
  5969. NewDecl->addAttr(
  5970. DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
  5971. } else {
  5972. S.Diag(NewDecl->getLocation(),
  5973. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5974. << NewDecl << OldImportAttr;
  5975. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5976. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5977. OldDecl->dropAttr<DLLImportAttr>();
  5978. NewDecl->dropAttr<DLLImportAttr>();
  5979. }
  5980. } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
  5981. // In MinGW, seeing a function declared inline drops the dllimport
  5982. // attribute.
  5983. OldDecl->dropAttr<DLLImportAttr>();
  5984. NewDecl->dropAttr<DLLImportAttr>();
  5985. S.Diag(NewDecl->getLocation(),
  5986. diag::warn_dllimport_dropped_from_inline_function)
  5987. << NewDecl << OldImportAttr;
  5988. }
  5989. // A specialization of a class template member function is processed here
  5990. // since it's a redeclaration. If the parent class is dllexport, the
  5991. // specialization inherits that attribute. This doesn't happen automatically
  5992. // since the parent class isn't instantiated until later.
  5993. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5994. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5995. !NewImportAttr && !NewExportAttr) {
  5996. if (const DLLExportAttr *ParentExportAttr =
  5997. MD->getParent()->getAttr<DLLExportAttr>()) {
  5998. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5999. NewAttr->setInherited(true);
  6000. NewDecl->addAttr(NewAttr);
  6001. }
  6002. }
  6003. }
  6004. }
  6005. /// Given that we are within the definition of the given function,
  6006. /// will that definition behave like C99's 'inline', where the
  6007. /// definition is discarded except for optimization purposes?
  6008. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  6009. // Try to avoid calling GetGVALinkageForFunction.
  6010. // All cases of this require the 'inline' keyword.
  6011. if (!FD->isInlined()) return false;
  6012. // This is only possible in C++ with the gnu_inline attribute.
  6013. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  6014. return false;
  6015. // Okay, go ahead and call the relatively-more-expensive function.
  6016. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  6017. }
  6018. /// Determine whether a variable is extern "C" prior to attaching
  6019. /// an initializer. We can't just call isExternC() here, because that
  6020. /// will also compute and cache whether the declaration is externally
  6021. /// visible, which might change when we attach the initializer.
  6022. ///
  6023. /// This can only be used if the declaration is known to not be a
  6024. /// redeclaration of an internal linkage declaration.
  6025. ///
  6026. /// For instance:
  6027. ///
  6028. /// auto x = []{};
  6029. ///
  6030. /// Attaching the initializer here makes this declaration not externally
  6031. /// visible, because its type has internal linkage.
  6032. ///
  6033. /// FIXME: This is a hack.
  6034. template<typename T>
  6035. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  6036. if (S.getLangOpts().CPlusPlus) {
  6037. // In C++, the overloadable attribute negates the effects of extern "C".
  6038. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  6039. return false;
  6040. // So do CUDA's host/device attributes.
  6041. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  6042. D->template hasAttr<CUDAHostAttr>()))
  6043. return false;
  6044. }
  6045. return D->isExternC();
  6046. }
  6047. static bool shouldConsiderLinkage(const VarDecl *VD) {
  6048. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  6049. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  6050. isa<OMPDeclareMapperDecl>(DC))
  6051. return VD->hasExternalStorage();
  6052. if (DC->isFileContext())
  6053. return true;
  6054. if (DC->isRecord())
  6055. return false;
  6056. if (isa<RequiresExprBodyDecl>(DC))
  6057. return false;
  6058. llvm_unreachable("Unexpected context");
  6059. }
  6060. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  6061. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  6062. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  6063. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  6064. return true;
  6065. if (DC->isRecord())
  6066. return false;
  6067. llvm_unreachable("Unexpected context");
  6068. }
  6069. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  6070. ParsedAttr::Kind Kind) {
  6071. // Check decl attributes on the DeclSpec.
  6072. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  6073. return true;
  6074. // Walk the declarator structure, checking decl attributes that were in a type
  6075. // position to the decl itself.
  6076. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  6077. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  6078. return true;
  6079. }
  6080. // Finally, check attributes on the decl itself.
  6081. return PD.getAttributes().hasAttribute(Kind);
  6082. }
  6083. /// Adjust the \c DeclContext for a function or variable that might be a
  6084. /// function-local external declaration.
  6085. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  6086. if (!DC->isFunctionOrMethod())
  6087. return false;
  6088. // If this is a local extern function or variable declared within a function
  6089. // template, don't add it into the enclosing namespace scope until it is
  6090. // instantiated; it might have a dependent type right now.
  6091. if (DC->isDependentContext())
  6092. return true;
  6093. // C++11 [basic.link]p7:
  6094. // When a block scope declaration of an entity with linkage is not found to
  6095. // refer to some other declaration, then that entity is a member of the
  6096. // innermost enclosing namespace.
  6097. //
  6098. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  6099. // semantically-enclosing namespace, not a lexically-enclosing one.
  6100. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  6101. DC = DC->getParent();
  6102. return true;
  6103. }
  6104. /// Returns true if given declaration has external C language linkage.
  6105. static bool isDeclExternC(const Decl *D) {
  6106. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  6107. return FD->isExternC();
  6108. if (const auto *VD = dyn_cast<VarDecl>(D))
  6109. return VD->isExternC();
  6110. llvm_unreachable("Unknown type of decl!");
  6111. }
  6112. /// Returns true if there hasn't been any invalid type diagnosed.
  6113. static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
  6114. DeclContext *DC = NewVD->getDeclContext();
  6115. QualType R = NewVD->getType();
  6116. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  6117. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  6118. // argument.
  6119. if (R->isImageType() || R->isPipeType()) {
  6120. Se.Diag(NewVD->getLocation(),
  6121. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  6122. << R;
  6123. NewVD->setInvalidDecl();
  6124. return false;
  6125. }
  6126. // OpenCL v1.2 s6.9.r:
  6127. // The event type cannot be used to declare a program scope variable.
  6128. // OpenCL v2.0 s6.9.q:
  6129. // The clk_event_t and reserve_id_t types cannot be declared in program
  6130. // scope.
  6131. if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
  6132. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  6133. Se.Diag(NewVD->getLocation(),
  6134. diag::err_invalid_type_for_program_scope_var)
  6135. << R;
  6136. NewVD->setInvalidDecl();
  6137. return false;
  6138. }
  6139. }
  6140. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  6141. if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
  6142. Se.getLangOpts())) {
  6143. QualType NR = R.getCanonicalType();
  6144. while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
  6145. NR->isReferenceType()) {
  6146. if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
  6147. NR->isFunctionReferenceType()) {
  6148. Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
  6149. << NR->isReferenceType();
  6150. NewVD->setInvalidDecl();
  6151. return false;
  6152. }
  6153. NR = NR->getPointeeType();
  6154. }
  6155. }
  6156. if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
  6157. Se.getLangOpts())) {
  6158. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  6159. // half array type (unless the cl_khr_fp16 extension is enabled).
  6160. if (Se.Context.getBaseElementType(R)->isHalfType()) {
  6161. Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
  6162. NewVD->setInvalidDecl();
  6163. return false;
  6164. }
  6165. }
  6166. // OpenCL v1.2 s6.9.r:
  6167. // The event type cannot be used with the __local, __constant and __global
  6168. // address space qualifiers.
  6169. if (R->isEventT()) {
  6170. if (R.getAddressSpace() != LangAS::opencl_private) {
  6171. Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
  6172. NewVD->setInvalidDecl();
  6173. return false;
  6174. }
  6175. }
  6176. if (R->isSamplerT()) {
  6177. // OpenCL v1.2 s6.9.b p4:
  6178. // The sampler type cannot be used with the __local and __global address
  6179. // space qualifiers.
  6180. if (R.getAddressSpace() == LangAS::opencl_local ||
  6181. R.getAddressSpace() == LangAS::opencl_global) {
  6182. Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
  6183. NewVD->setInvalidDecl();
  6184. }
  6185. // OpenCL v1.2 s6.12.14.1:
  6186. // A global sampler must be declared with either the constant address
  6187. // space qualifier or with the const qualifier.
  6188. if (DC->isTranslationUnit() &&
  6189. !(R.getAddressSpace() == LangAS::opencl_constant ||
  6190. R.isConstQualified())) {
  6191. Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
  6192. NewVD->setInvalidDecl();
  6193. }
  6194. if (NewVD->isInvalidDecl())
  6195. return false;
  6196. }
  6197. return true;
  6198. }
  6199. template <typename AttrTy>
  6200. static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
  6201. const TypedefNameDecl *TND = TT->getDecl();
  6202. if (const auto *Attribute = TND->getAttr<AttrTy>()) {
  6203. AttrTy *Clone = Attribute->clone(S.Context);
  6204. Clone->setInherited(true);
  6205. D->addAttr(Clone);
  6206. }
  6207. }
  6208. NamedDecl *Sema::ActOnVariableDeclarator(
  6209. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  6210. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  6211. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  6212. QualType R = TInfo->getType();
  6213. DeclarationName Name = GetNameForDeclarator(D).getName();
  6214. IdentifierInfo *II = Name.getAsIdentifierInfo();
  6215. if (D.isDecompositionDeclarator()) {
  6216. // Take the name of the first declarator as our name for diagnostic
  6217. // purposes.
  6218. auto &Decomp = D.getDecompositionDeclarator();
  6219. if (!Decomp.bindings().empty()) {
  6220. II = Decomp.bindings()[0].Name;
  6221. Name = II;
  6222. }
  6223. } else if (!II) {
  6224. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  6225. return nullptr;
  6226. }
  6227. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  6228. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  6229. // dllimport globals without explicit storage class are treated as extern. We
  6230. // have to change the storage class this early to get the right DeclContext.
  6231. if (SC == SC_None && !DC->isRecord() &&
  6232. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  6233. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  6234. SC = SC_Extern;
  6235. DeclContext *OriginalDC = DC;
  6236. bool IsLocalExternDecl = SC == SC_Extern &&
  6237. adjustContextForLocalExternDecl(DC);
  6238. if (SCSpec == DeclSpec::SCS_mutable) {
  6239. // mutable can only appear on non-static class members, so it's always
  6240. // an error here
  6241. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  6242. D.setInvalidType();
  6243. SC = SC_None;
  6244. }
  6245. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  6246. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  6247. D.getDeclSpec().getStorageClassSpecLoc())) {
  6248. // In C++11, the 'register' storage class specifier is deprecated.
  6249. // Suppress the warning in system macros, it's used in macros in some
  6250. // popular C system headers, such as in glibc's htonl() macro.
  6251. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6252. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  6253. : diag::warn_deprecated_register)
  6254. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6255. }
  6256. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  6257. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  6258. // C99 6.9p2: The storage-class specifiers auto and register shall not
  6259. // appear in the declaration specifiers in an external declaration.
  6260. // Global Register+Asm is a GNU extension we support.
  6261. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  6262. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  6263. D.setInvalidType();
  6264. }
  6265. }
  6266. // If this variable has a VLA type and an initializer, try to
  6267. // fold to a constant-sized type. This is otherwise invalid.
  6268. if (D.hasInitializer() && R->isVariableArrayType())
  6269. tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
  6270. /*DiagID=*/0);
  6271. bool IsMemberSpecialization = false;
  6272. bool IsVariableTemplateSpecialization = false;
  6273. bool IsPartialSpecialization = false;
  6274. bool IsVariableTemplate = false;
  6275. VarDecl *NewVD = nullptr;
  6276. VarTemplateDecl *NewTemplate = nullptr;
  6277. TemplateParameterList *TemplateParams = nullptr;
  6278. if (!getLangOpts().CPlusPlus) {
  6279. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  6280. II, R, TInfo, SC);
  6281. if (R->getContainedDeducedType())
  6282. ParsingInitForAutoVars.insert(NewVD);
  6283. if (D.isInvalidType())
  6284. NewVD->setInvalidDecl();
  6285. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  6286. NewVD->hasLocalStorage())
  6287. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  6288. NTCUC_AutoVar, NTCUK_Destruct);
  6289. } else {
  6290. bool Invalid = false;
  6291. if (DC->isRecord() && !CurContext->isRecord()) {
  6292. // This is an out-of-line definition of a static data member.
  6293. switch (SC) {
  6294. case SC_None:
  6295. break;
  6296. case SC_Static:
  6297. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6298. diag::err_static_out_of_line)
  6299. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6300. break;
  6301. case SC_Auto:
  6302. case SC_Register:
  6303. case SC_Extern:
  6304. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  6305. // to names of variables declared in a block or to function parameters.
  6306. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  6307. // of class members
  6308. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6309. diag::err_storage_class_for_static_member)
  6310. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6311. break;
  6312. case SC_PrivateExtern:
  6313. llvm_unreachable("C storage class in c++!");
  6314. }
  6315. }
  6316. if (SC == SC_Static && CurContext->isRecord()) {
  6317. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  6318. // Walk up the enclosing DeclContexts to check for any that are
  6319. // incompatible with static data members.
  6320. const DeclContext *FunctionOrMethod = nullptr;
  6321. const CXXRecordDecl *AnonStruct = nullptr;
  6322. for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
  6323. if (Ctxt->isFunctionOrMethod()) {
  6324. FunctionOrMethod = Ctxt;
  6325. break;
  6326. }
  6327. const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
  6328. if (ParentDecl && !ParentDecl->getDeclName()) {
  6329. AnonStruct = ParentDecl;
  6330. break;
  6331. }
  6332. }
  6333. if (FunctionOrMethod) {
  6334. // C++ [class.static.data]p5: A local class shall not have static data
  6335. // members.
  6336. Diag(D.getIdentifierLoc(),
  6337. diag::err_static_data_member_not_allowed_in_local_class)
  6338. << Name << RD->getDeclName() << RD->getTagKind();
  6339. } else if (AnonStruct) {
  6340. // C++ [class.static.data]p4: Unnamed classes and classes contained
  6341. // directly or indirectly within unnamed classes shall not contain
  6342. // static data members.
  6343. Diag(D.getIdentifierLoc(),
  6344. diag::err_static_data_member_not_allowed_in_anon_struct)
  6345. << Name << AnonStruct->getTagKind();
  6346. Invalid = true;
  6347. } else if (RD->isUnion()) {
  6348. // C++98 [class.union]p1: If a union contains a static data member,
  6349. // the program is ill-formed. C++11 drops this restriction.
  6350. Diag(D.getIdentifierLoc(),
  6351. getLangOpts().CPlusPlus11
  6352. ? diag::warn_cxx98_compat_static_data_member_in_union
  6353. : diag::ext_static_data_member_in_union) << Name;
  6354. }
  6355. }
  6356. }
  6357. // Match up the template parameter lists with the scope specifier, then
  6358. // determine whether we have a template or a template specialization.
  6359. bool InvalidScope = false;
  6360. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  6361. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  6362. D.getCXXScopeSpec(),
  6363. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  6364. ? D.getName().TemplateId
  6365. : nullptr,
  6366. TemplateParamLists,
  6367. /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
  6368. Invalid |= InvalidScope;
  6369. if (TemplateParams) {
  6370. if (!TemplateParams->size() &&
  6371. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  6372. // There is an extraneous 'template<>' for this variable. Complain
  6373. // about it, but allow the declaration of the variable.
  6374. Diag(TemplateParams->getTemplateLoc(),
  6375. diag::err_template_variable_noparams)
  6376. << II
  6377. << SourceRange(TemplateParams->getTemplateLoc(),
  6378. TemplateParams->getRAngleLoc());
  6379. TemplateParams = nullptr;
  6380. } else {
  6381. // Check that we can declare a template here.
  6382. if (CheckTemplateDeclScope(S, TemplateParams))
  6383. return nullptr;
  6384. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  6385. // This is an explicit specialization or a partial specialization.
  6386. IsVariableTemplateSpecialization = true;
  6387. IsPartialSpecialization = TemplateParams->size() > 0;
  6388. } else { // if (TemplateParams->size() > 0)
  6389. // This is a template declaration.
  6390. IsVariableTemplate = true;
  6391. // Only C++1y supports variable templates (N3651).
  6392. Diag(D.getIdentifierLoc(),
  6393. getLangOpts().CPlusPlus14
  6394. ? diag::warn_cxx11_compat_variable_template
  6395. : diag::ext_variable_template);
  6396. }
  6397. }
  6398. } else {
  6399. // Check that we can declare a member specialization here.
  6400. if (!TemplateParamLists.empty() && IsMemberSpecialization &&
  6401. CheckTemplateDeclScope(S, TemplateParamLists.back()))
  6402. return nullptr;
  6403. assert((Invalid ||
  6404. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  6405. "should have a 'template<>' for this decl");
  6406. }
  6407. if (IsVariableTemplateSpecialization) {
  6408. SourceLocation TemplateKWLoc =
  6409. TemplateParamLists.size() > 0
  6410. ? TemplateParamLists[0]->getTemplateLoc()
  6411. : SourceLocation();
  6412. DeclResult Res = ActOnVarTemplateSpecialization(
  6413. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  6414. IsPartialSpecialization);
  6415. if (Res.isInvalid())
  6416. return nullptr;
  6417. NewVD = cast<VarDecl>(Res.get());
  6418. AddToScope = false;
  6419. } else if (D.isDecompositionDeclarator()) {
  6420. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  6421. D.getIdentifierLoc(), R, TInfo, SC,
  6422. Bindings);
  6423. } else
  6424. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  6425. D.getIdentifierLoc(), II, R, TInfo, SC);
  6426. // If this is supposed to be a variable template, create it as such.
  6427. if (IsVariableTemplate) {
  6428. NewTemplate =
  6429. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  6430. TemplateParams, NewVD);
  6431. NewVD->setDescribedVarTemplate(NewTemplate);
  6432. }
  6433. // If this decl has an auto type in need of deduction, make a note of the
  6434. // Decl so we can diagnose uses of it in its own initializer.
  6435. if (R->getContainedDeducedType())
  6436. ParsingInitForAutoVars.insert(NewVD);
  6437. if (D.isInvalidType() || Invalid) {
  6438. NewVD->setInvalidDecl();
  6439. if (NewTemplate)
  6440. NewTemplate->setInvalidDecl();
  6441. }
  6442. SetNestedNameSpecifier(*this, NewVD, D);
  6443. // If we have any template parameter lists that don't directly belong to
  6444. // the variable (matching the scope specifier), store them.
  6445. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  6446. if (TemplateParamLists.size() > VDTemplateParamLists)
  6447. NewVD->setTemplateParameterListsInfo(
  6448. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  6449. }
  6450. if (D.getDeclSpec().isInlineSpecified()) {
  6451. if (!getLangOpts().CPlusPlus) {
  6452. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  6453. << 0;
  6454. } else if (CurContext->isFunctionOrMethod()) {
  6455. // 'inline' is not allowed on block scope variable declaration.
  6456. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6457. diag::err_inline_declaration_block_scope) << Name
  6458. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6459. } else {
  6460. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6461. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  6462. : diag::ext_inline_variable);
  6463. NewVD->setInlineSpecified();
  6464. }
  6465. }
  6466. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6467. // lexical context will be different from the semantic context.
  6468. NewVD->setLexicalDeclContext(CurContext);
  6469. if (NewTemplate)
  6470. NewTemplate->setLexicalDeclContext(CurContext);
  6471. if (IsLocalExternDecl) {
  6472. if (D.isDecompositionDeclarator())
  6473. for (auto *B : Bindings)
  6474. B->setLocalExternDecl();
  6475. else
  6476. NewVD->setLocalExternDecl();
  6477. }
  6478. bool EmitTLSUnsupportedError = false;
  6479. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6480. // C++11 [dcl.stc]p4:
  6481. // When thread_local is applied to a variable of block scope the
  6482. // storage-class-specifier static is implied if it does not appear
  6483. // explicitly.
  6484. // Core issue: 'static' is not implied if the variable is declared
  6485. // 'extern'.
  6486. if (NewVD->hasLocalStorage() &&
  6487. (SCSpec != DeclSpec::SCS_unspecified ||
  6488. TSCS != DeclSpec::TSCS_thread_local ||
  6489. !DC->isFunctionOrMethod()))
  6490. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6491. diag::err_thread_non_global)
  6492. << DeclSpec::getSpecifierName(TSCS);
  6493. else if (!Context.getTargetInfo().isTLSSupported()) {
  6494. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
  6495. getLangOpts().SYCLIsDevice) {
  6496. // Postpone error emission until we've collected attributes required to
  6497. // figure out whether it's a host or device variable and whether the
  6498. // error should be ignored.
  6499. EmitTLSUnsupportedError = true;
  6500. // We still need to mark the variable as TLS so it shows up in AST with
  6501. // proper storage class for other tools to use even if we're not going
  6502. // to emit any code for it.
  6503. NewVD->setTSCSpec(TSCS);
  6504. } else
  6505. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6506. diag::err_thread_unsupported);
  6507. } else
  6508. NewVD->setTSCSpec(TSCS);
  6509. }
  6510. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6511. case ConstexprSpecKind::Unspecified:
  6512. break;
  6513. case ConstexprSpecKind::Consteval:
  6514. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6515. diag::err_constexpr_wrong_decl_kind)
  6516. << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  6517. LLVM_FALLTHROUGH;
  6518. case ConstexprSpecKind::Constexpr:
  6519. NewVD->setConstexpr(true);
  6520. // C++1z [dcl.spec.constexpr]p1:
  6521. // A static data member declared with the constexpr specifier is
  6522. // implicitly an inline variable.
  6523. if (NewVD->isStaticDataMember() &&
  6524. (getLangOpts().CPlusPlus17 ||
  6525. Context.getTargetInfo().getCXXABI().isMicrosoft()))
  6526. NewVD->setImplicitlyInline();
  6527. break;
  6528. case ConstexprSpecKind::Constinit:
  6529. if (!NewVD->hasGlobalStorage())
  6530. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6531. diag::err_constinit_local_variable);
  6532. else
  6533. NewVD->addAttr(ConstInitAttr::Create(
  6534. Context, D.getDeclSpec().getConstexprSpecLoc(),
  6535. AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
  6536. break;
  6537. }
  6538. // C99 6.7.4p3
  6539. // An inline definition of a function with external linkage shall
  6540. // not contain a definition of a modifiable object with static or
  6541. // thread storage duration...
  6542. // We only apply this when the function is required to be defined
  6543. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6544. // that a local variable with thread storage duration still has to
  6545. // be marked 'static'. Also note that it's possible to get these
  6546. // semantics in C++ using __attribute__((gnu_inline)).
  6547. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6548. !NewVD->getType().isConstQualified()) {
  6549. FunctionDecl *CurFD = getCurFunctionDecl();
  6550. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6551. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6552. diag::warn_static_local_in_extern_inline);
  6553. MaybeSuggestAddingStaticToDecl(CurFD);
  6554. }
  6555. }
  6556. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6557. if (IsVariableTemplateSpecialization)
  6558. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6559. << (IsPartialSpecialization ? 1 : 0)
  6560. << FixItHint::CreateRemoval(
  6561. D.getDeclSpec().getModulePrivateSpecLoc());
  6562. else if (IsMemberSpecialization)
  6563. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6564. << 2
  6565. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6566. else if (NewVD->hasLocalStorage())
  6567. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6568. << 0 << NewVD
  6569. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6570. << FixItHint::CreateRemoval(
  6571. D.getDeclSpec().getModulePrivateSpecLoc());
  6572. else {
  6573. NewVD->setModulePrivate();
  6574. if (NewTemplate)
  6575. NewTemplate->setModulePrivate();
  6576. for (auto *B : Bindings)
  6577. B->setModulePrivate();
  6578. }
  6579. }
  6580. if (getLangOpts().OpenCL) {
  6581. deduceOpenCLAddressSpace(NewVD);
  6582. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  6583. if (TSC != TSCS_unspecified) {
  6584. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6585. diag::err_opencl_unknown_type_specifier)
  6586. << getLangOpts().getOpenCLVersionString()
  6587. << DeclSpec::getSpecifierName(TSC) << 1;
  6588. NewVD->setInvalidDecl();
  6589. }
  6590. }
  6591. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6592. ProcessDeclAttributes(S, NewVD, D);
  6593. // FIXME: This is probably the wrong location to be doing this and we should
  6594. // probably be doing this for more attributes (especially for function
  6595. // pointer attributes such as format, warn_unused_result, etc.). Ideally
  6596. // the code to copy attributes would be generated by TableGen.
  6597. if (R->isFunctionPointerType())
  6598. if (const auto *TT = R->getAs<TypedefType>())
  6599. copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
  6600. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
  6601. getLangOpts().SYCLIsDevice) {
  6602. if (EmitTLSUnsupportedError &&
  6603. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6604. (getLangOpts().OpenMPIsDevice &&
  6605. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6606. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6607. diag::err_thread_unsupported);
  6608. if (EmitTLSUnsupportedError &&
  6609. (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
  6610. targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
  6611. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6612. // storage [duration]."
  6613. if (SC == SC_None && S->getFnParent() != nullptr &&
  6614. (NewVD->hasAttr<CUDASharedAttr>() ||
  6615. NewVD->hasAttr<CUDAConstantAttr>())) {
  6616. NewVD->setStorageClass(SC_Static);
  6617. }
  6618. }
  6619. // Ensure that dllimport globals without explicit storage class are treated as
  6620. // extern. The storage class is set above using parsed attributes. Now we can
  6621. // check the VarDecl itself.
  6622. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6623. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6624. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6625. // In auto-retain/release, infer strong retension for variables of
  6626. // retainable type.
  6627. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6628. NewVD->setInvalidDecl();
  6629. // Handle GNU asm-label extension (encoded as an attribute).
  6630. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6631. // The parser guarantees this is a string.
  6632. StringLiteral *SE = cast<StringLiteral>(E);
  6633. StringRef Label = SE->getString();
  6634. if (S->getFnParent() != nullptr) {
  6635. switch (SC) {
  6636. case SC_None:
  6637. case SC_Auto:
  6638. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  6639. break;
  6640. case SC_Register:
  6641. // Local Named register
  6642. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  6643. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  6644. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6645. break;
  6646. case SC_Static:
  6647. case SC_Extern:
  6648. case SC_PrivateExtern:
  6649. break;
  6650. }
  6651. } else if (SC == SC_Register) {
  6652. // Global Named register
  6653. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  6654. const auto &TI = Context.getTargetInfo();
  6655. bool HasSizeMismatch;
  6656. if (!TI.isValidGCCRegisterName(Label))
  6657. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  6658. else if (!TI.validateGlobalRegisterVariable(Label,
  6659. Context.getTypeSize(R),
  6660. HasSizeMismatch))
  6661. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  6662. else if (HasSizeMismatch)
  6663. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  6664. }
  6665. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  6666. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  6667. NewVD->setInvalidDecl(true);
  6668. }
  6669. }
  6670. NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
  6671. /*IsLiteralLabel=*/true,
  6672. SE->getStrTokenLoc(0)));
  6673. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6674. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6675. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6676. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6677. if (isDeclExternC(NewVD)) {
  6678. NewVD->addAttr(I->second);
  6679. ExtnameUndeclaredIdentifiers.erase(I);
  6680. } else
  6681. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6682. << /*Variable*/1 << NewVD;
  6683. }
  6684. }
  6685. // Find the shadowed declaration before filtering for scope.
  6686. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6687. ? getShadowedDeclaration(NewVD, Previous)
  6688. : nullptr;
  6689. // Don't consider existing declarations that are in a different
  6690. // scope and are out-of-semantic-context declarations (if the new
  6691. // declaration has linkage).
  6692. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6693. D.getCXXScopeSpec().isNotEmpty() ||
  6694. IsMemberSpecialization ||
  6695. IsVariableTemplateSpecialization);
  6696. // Check whether the previous declaration is in the same block scope. This
  6697. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6698. if (getLangOpts().CPlusPlus &&
  6699. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6700. NewVD->setPreviousDeclInSameBlockScope(
  6701. Previous.isSingleResult() && !Previous.isShadowed() &&
  6702. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6703. if (!getLangOpts().CPlusPlus) {
  6704. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6705. } else {
  6706. // If this is an explicit specialization of a static data member, check it.
  6707. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6708. CheckMemberSpecialization(NewVD, Previous))
  6709. NewVD->setInvalidDecl();
  6710. // Merge the decl with the existing one if appropriate.
  6711. if (!Previous.empty()) {
  6712. if (Previous.isSingleResult() &&
  6713. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6714. D.getCXXScopeSpec().isSet()) {
  6715. // The user tried to define a non-static data member
  6716. // out-of-line (C++ [dcl.meaning]p1).
  6717. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6718. << D.getCXXScopeSpec().getRange();
  6719. Previous.clear();
  6720. NewVD->setInvalidDecl();
  6721. }
  6722. } else if (D.getCXXScopeSpec().isSet()) {
  6723. // No previous declaration in the qualifying scope.
  6724. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6725. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6726. << D.getCXXScopeSpec().getRange();
  6727. NewVD->setInvalidDecl();
  6728. }
  6729. if (!IsVariableTemplateSpecialization)
  6730. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6731. if (NewTemplate) {
  6732. VarTemplateDecl *PrevVarTemplate =
  6733. NewVD->getPreviousDecl()
  6734. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6735. : nullptr;
  6736. // Check the template parameter list of this declaration, possibly
  6737. // merging in the template parameter list from the previous variable
  6738. // template declaration.
  6739. if (CheckTemplateParameterList(
  6740. TemplateParams,
  6741. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6742. : nullptr,
  6743. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6744. DC->isDependentContext())
  6745. ? TPC_ClassTemplateMember
  6746. : TPC_VarTemplate))
  6747. NewVD->setInvalidDecl();
  6748. // If we are providing an explicit specialization of a static variable
  6749. // template, make a note of that.
  6750. if (PrevVarTemplate &&
  6751. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6752. PrevVarTemplate->setMemberSpecialization();
  6753. }
  6754. }
  6755. // Diagnose shadowed variables iff this isn't a redeclaration.
  6756. if (ShadowedDecl && !D.isRedeclaration())
  6757. CheckShadow(NewVD, ShadowedDecl, Previous);
  6758. ProcessPragmaWeak(S, NewVD);
  6759. // If this is the first declaration of an extern C variable, update
  6760. // the map of such variables.
  6761. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6762. isIncompleteDeclExternC(*this, NewVD))
  6763. RegisterLocallyScopedExternCDecl(NewVD, S);
  6764. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6765. MangleNumberingContext *MCtx;
  6766. Decl *ManglingContextDecl;
  6767. std::tie(MCtx, ManglingContextDecl) =
  6768. getCurrentMangleNumberContext(NewVD->getDeclContext());
  6769. if (MCtx) {
  6770. Context.setManglingNumber(
  6771. NewVD, MCtx->getManglingNumber(
  6772. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6773. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6774. }
  6775. }
  6776. // Special handling of variable named 'main'.
  6777. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6778. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6779. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6780. // C++ [basic.start.main]p3
  6781. // A program that declares a variable main at global scope is ill-formed.
  6782. if (getLangOpts().CPlusPlus)
  6783. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6784. // In C, and external-linkage variable named main results in undefined
  6785. // behavior.
  6786. else if (NewVD->hasExternalFormalLinkage())
  6787. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6788. }
  6789. if (D.isRedeclaration() && !Previous.empty()) {
  6790. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6791. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6792. D.isFunctionDefinition());
  6793. }
  6794. if (NewTemplate) {
  6795. if (NewVD->isInvalidDecl())
  6796. NewTemplate->setInvalidDecl();
  6797. ActOnDocumentableDecl(NewTemplate);
  6798. return NewTemplate;
  6799. }
  6800. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6801. CompleteMemberSpecialization(NewVD, Previous);
  6802. return NewVD;
  6803. }
  6804. /// Enum describing the %select options in diag::warn_decl_shadow.
  6805. enum ShadowedDeclKind {
  6806. SDK_Local,
  6807. SDK_Global,
  6808. SDK_StaticMember,
  6809. SDK_Field,
  6810. SDK_Typedef,
  6811. SDK_Using,
  6812. SDK_StructuredBinding
  6813. };
  6814. /// Determine what kind of declaration we're shadowing.
  6815. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6816. const DeclContext *OldDC) {
  6817. if (isa<TypeAliasDecl>(ShadowedDecl))
  6818. return SDK_Using;
  6819. else if (isa<TypedefDecl>(ShadowedDecl))
  6820. return SDK_Typedef;
  6821. else if (isa<BindingDecl>(ShadowedDecl))
  6822. return SDK_StructuredBinding;
  6823. else if (isa<RecordDecl>(OldDC))
  6824. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6825. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6826. }
  6827. /// Return the location of the capture if the given lambda captures the given
  6828. /// variable \p VD, or an invalid source location otherwise.
  6829. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6830. const VarDecl *VD) {
  6831. for (const Capture &Capture : LSI->Captures) {
  6832. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6833. return Capture.getLocation();
  6834. }
  6835. return SourceLocation();
  6836. }
  6837. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6838. const LookupResult &R) {
  6839. // Only diagnose if we're shadowing an unambiguous field or variable.
  6840. if (R.getResultKind() != LookupResult::Found)
  6841. return false;
  6842. // Return false if warning is ignored.
  6843. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6844. }
  6845. /// Return the declaration shadowed by the given variable \p D, or null
  6846. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6847. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6848. const LookupResult &R) {
  6849. if (!shouldWarnIfShadowedDecl(Diags, R))
  6850. return nullptr;
  6851. // Don't diagnose declarations at file scope.
  6852. if (D->hasGlobalStorage())
  6853. return nullptr;
  6854. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6855. return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
  6856. : nullptr;
  6857. }
  6858. /// Return the declaration shadowed by the given typedef \p D, or null
  6859. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6860. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6861. const LookupResult &R) {
  6862. // Don't warn if typedef declaration is part of a class
  6863. if (D->getDeclContext()->isRecord())
  6864. return nullptr;
  6865. if (!shouldWarnIfShadowedDecl(Diags, R))
  6866. return nullptr;
  6867. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6868. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6869. }
  6870. /// Return the declaration shadowed by the given variable \p D, or null
  6871. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6872. NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
  6873. const LookupResult &R) {
  6874. if (!shouldWarnIfShadowedDecl(Diags, R))
  6875. return nullptr;
  6876. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6877. return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
  6878. : nullptr;
  6879. }
  6880. /// Diagnose variable or built-in function shadowing. Implements
  6881. /// -Wshadow.
  6882. ///
  6883. /// This method is called whenever a VarDecl is added to a "useful"
  6884. /// scope.
  6885. ///
  6886. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6887. /// \param R the lookup of the name
  6888. ///
  6889. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6890. const LookupResult &R) {
  6891. DeclContext *NewDC = D->getDeclContext();
  6892. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6893. // Fields are not shadowed by variables in C++ static methods.
  6894. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6895. if (MD->isStatic())
  6896. return;
  6897. // Fields shadowed by constructor parameters are a special case. Usually
  6898. // the constructor initializes the field with the parameter.
  6899. if (isa<CXXConstructorDecl>(NewDC))
  6900. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6901. // Remember that this was shadowed so we can either warn about its
  6902. // modification or its existence depending on warning settings.
  6903. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6904. return;
  6905. }
  6906. }
  6907. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6908. if (shadowedVar->isExternC()) {
  6909. // For shadowing external vars, make sure that we point to the global
  6910. // declaration, not a locally scoped extern declaration.
  6911. for (auto I : shadowedVar->redecls())
  6912. if (I->isFileVarDecl()) {
  6913. ShadowedDecl = I;
  6914. break;
  6915. }
  6916. }
  6917. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6918. unsigned WarningDiag = diag::warn_decl_shadow;
  6919. SourceLocation CaptureLoc;
  6920. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6921. isa<CXXMethodDecl>(NewDC)) {
  6922. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6923. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6924. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6925. // Try to avoid warnings for lambdas with an explicit capture list.
  6926. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6927. // Warn only when the lambda captures the shadowed decl explicitly.
  6928. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6929. if (CaptureLoc.isInvalid())
  6930. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6931. } else {
  6932. // Remember that this was shadowed so we can avoid the warning if the
  6933. // shadowed decl isn't captured and the warning settings allow it.
  6934. cast<LambdaScopeInfo>(getCurFunction())
  6935. ->ShadowingDecls.push_back(
  6936. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6937. return;
  6938. }
  6939. }
  6940. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6941. // A variable can't shadow a local variable in an enclosing scope, if
  6942. // they are separated by a non-capturing declaration context.
  6943. for (DeclContext *ParentDC = NewDC;
  6944. ParentDC && !ParentDC->Equals(OldDC);
  6945. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6946. // Only block literals, captured statements, and lambda expressions
  6947. // can capture; other scopes don't.
  6948. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6949. !isLambdaCallOperator(ParentDC)) {
  6950. return;
  6951. }
  6952. }
  6953. }
  6954. }
  6955. }
  6956. // Only warn about certain kinds of shadowing for class members.
  6957. if (NewDC && NewDC->isRecord()) {
  6958. // In particular, don't warn about shadowing non-class members.
  6959. if (!OldDC->isRecord())
  6960. return;
  6961. // TODO: should we warn about static data members shadowing
  6962. // static data members from base classes?
  6963. // TODO: don't diagnose for inaccessible shadowed members.
  6964. // This is hard to do perfectly because we might friend the
  6965. // shadowing context, but that's just a false negative.
  6966. }
  6967. DeclarationName Name = R.getLookupName();
  6968. // Emit warning and note.
  6969. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6970. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6971. if (!CaptureLoc.isInvalid())
  6972. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6973. << Name << /*explicitly*/ 1;
  6974. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6975. }
  6976. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6977. /// when these variables are captured by the lambda.
  6978. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6979. for (const auto &Shadow : LSI->ShadowingDecls) {
  6980. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6981. // Try to avoid the warning when the shadowed decl isn't captured.
  6982. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6983. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6984. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6985. ? diag::warn_decl_shadow_uncaptured_local
  6986. : diag::warn_decl_shadow)
  6987. << Shadow.VD->getDeclName()
  6988. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6989. if (!CaptureLoc.isInvalid())
  6990. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6991. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6992. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6993. }
  6994. }
  6995. /// Check -Wshadow without the advantage of a previous lookup.
  6996. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6997. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6998. return;
  6999. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  7000. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  7001. LookupName(R, S);
  7002. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  7003. CheckShadow(D, ShadowedDecl, R);
  7004. }
  7005. /// Check if 'E', which is an expression that is about to be modified, refers
  7006. /// to a constructor parameter that shadows a field.
  7007. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  7008. // Quickly ignore expressions that can't be shadowing ctor parameters.
  7009. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  7010. return;
  7011. E = E->IgnoreParenImpCasts();
  7012. auto *DRE = dyn_cast<DeclRefExpr>(E);
  7013. if (!DRE)
  7014. return;
  7015. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  7016. auto I = ShadowingDecls.find(D);
  7017. if (I == ShadowingDecls.end())
  7018. return;
  7019. const NamedDecl *ShadowedDecl = I->second;
  7020. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  7021. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  7022. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  7023. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  7024. // Avoid issuing multiple warnings about the same decl.
  7025. ShadowingDecls.erase(I);
  7026. }
  7027. /// Check for conflict between this global or extern "C" declaration and
  7028. /// previous global or extern "C" declarations. This is only used in C++.
  7029. template<typename T>
  7030. static bool checkGlobalOrExternCConflict(
  7031. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  7032. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  7033. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  7034. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  7035. // The common case: this global doesn't conflict with any extern "C"
  7036. // declaration.
  7037. return false;
  7038. }
  7039. if (Prev) {
  7040. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  7041. // Both the old and new declarations have C language linkage. This is a
  7042. // redeclaration.
  7043. Previous.clear();
  7044. Previous.addDecl(Prev);
  7045. return true;
  7046. }
  7047. // This is a global, non-extern "C" declaration, and there is a previous
  7048. // non-global extern "C" declaration. Diagnose if this is a variable
  7049. // declaration.
  7050. if (!isa<VarDecl>(ND))
  7051. return false;
  7052. } else {
  7053. // The declaration is extern "C". Check for any declaration in the
  7054. // translation unit which might conflict.
  7055. if (IsGlobal) {
  7056. // We have already performed the lookup into the translation unit.
  7057. IsGlobal = false;
  7058. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7059. I != E; ++I) {
  7060. if (isa<VarDecl>(*I)) {
  7061. Prev = *I;
  7062. break;
  7063. }
  7064. }
  7065. } else {
  7066. DeclContext::lookup_result R =
  7067. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  7068. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  7069. I != E; ++I) {
  7070. if (isa<VarDecl>(*I)) {
  7071. Prev = *I;
  7072. break;
  7073. }
  7074. // FIXME: If we have any other entity with this name in global scope,
  7075. // the declaration is ill-formed, but that is a defect: it breaks the
  7076. // 'stat' hack, for instance. Only variables can have mangled name
  7077. // clashes with extern "C" declarations, so only they deserve a
  7078. // diagnostic.
  7079. }
  7080. }
  7081. if (!Prev)
  7082. return false;
  7083. }
  7084. // Use the first declaration's location to ensure we point at something which
  7085. // is lexically inside an extern "C" linkage-spec.
  7086. assert(Prev && "should have found a previous declaration to diagnose");
  7087. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  7088. Prev = FD->getFirstDecl();
  7089. else
  7090. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  7091. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  7092. << IsGlobal << ND;
  7093. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  7094. << IsGlobal;
  7095. return false;
  7096. }
  7097. /// Apply special rules for handling extern "C" declarations. Returns \c true
  7098. /// if we have found that this is a redeclaration of some prior entity.
  7099. ///
  7100. /// Per C++ [dcl.link]p6:
  7101. /// Two declarations [for a function or variable] with C language linkage
  7102. /// with the same name that appear in different scopes refer to the same
  7103. /// [entity]. An entity with C language linkage shall not be declared with
  7104. /// the same name as an entity in global scope.
  7105. template<typename T>
  7106. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  7107. LookupResult &Previous) {
  7108. if (!S.getLangOpts().CPlusPlus) {
  7109. // In C, when declaring a global variable, look for a corresponding 'extern'
  7110. // variable declared in function scope. We don't need this in C++, because
  7111. // we find local extern decls in the surrounding file-scope DeclContext.
  7112. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7113. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  7114. Previous.clear();
  7115. Previous.addDecl(Prev);
  7116. return true;
  7117. }
  7118. }
  7119. return false;
  7120. }
  7121. // A declaration in the translation unit can conflict with an extern "C"
  7122. // declaration.
  7123. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  7124. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  7125. // An extern "C" declaration can conflict with a declaration in the
  7126. // translation unit or can be a redeclaration of an extern "C" declaration
  7127. // in another scope.
  7128. if (isIncompleteDeclExternC(S,ND))
  7129. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  7130. // Neither global nor extern "C": nothing to do.
  7131. return false;
  7132. }
  7133. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  7134. // If the decl is already known invalid, don't check it.
  7135. if (NewVD->isInvalidDecl())
  7136. return;
  7137. QualType T = NewVD->getType();
  7138. // Defer checking an 'auto' type until its initializer is attached.
  7139. if (T->isUndeducedType())
  7140. return;
  7141. if (NewVD->hasAttrs())
  7142. CheckAlignasUnderalignment(NewVD);
  7143. if (T->isObjCObjectType()) {
  7144. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  7145. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  7146. T = Context.getObjCObjectPointerType(T);
  7147. NewVD->setType(T);
  7148. }
  7149. // Emit an error if an address space was applied to decl with local storage.
  7150. // This includes arrays of objects with address space qualifiers, but not
  7151. // automatic variables that point to other address spaces.
  7152. // ISO/IEC TR 18037 S5.1.2
  7153. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  7154. T.getAddressSpace() != LangAS::Default) {
  7155. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  7156. NewVD->setInvalidDecl();
  7157. return;
  7158. }
  7159. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  7160. // scope.
  7161. if (getLangOpts().OpenCLVersion == 120 &&
  7162. !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
  7163. getLangOpts()) &&
  7164. NewVD->isStaticLocal()) {
  7165. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  7166. NewVD->setInvalidDecl();
  7167. return;
  7168. }
  7169. if (getLangOpts().OpenCL) {
  7170. if (!diagnoseOpenCLTypes(*this, NewVD))
  7171. return;
  7172. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  7173. if (NewVD->hasAttr<BlocksAttr>()) {
  7174. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  7175. return;
  7176. }
  7177. if (T->isBlockPointerType()) {
  7178. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  7179. // can't use 'extern' storage class.
  7180. if (!T.isConstQualified()) {
  7181. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  7182. << 0 /*const*/;
  7183. NewVD->setInvalidDecl();
  7184. return;
  7185. }
  7186. if (NewVD->hasExternalStorage()) {
  7187. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  7188. NewVD->setInvalidDecl();
  7189. return;
  7190. }
  7191. }
  7192. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  7193. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  7194. NewVD->hasExternalStorage()) {
  7195. if (!T->isSamplerT() && !T->isDependentType() &&
  7196. !(T.getAddressSpace() == LangAS::opencl_constant ||
  7197. (T.getAddressSpace() == LangAS::opencl_global &&
  7198. getOpenCLOptions().areProgramScopeVariablesSupported(
  7199. getLangOpts())))) {
  7200. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  7201. if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
  7202. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  7203. << Scope << "global or constant";
  7204. else
  7205. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  7206. << Scope << "constant";
  7207. NewVD->setInvalidDecl();
  7208. return;
  7209. }
  7210. } else {
  7211. if (T.getAddressSpace() == LangAS::opencl_global) {
  7212. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7213. << 1 /*is any function*/ << "global";
  7214. NewVD->setInvalidDecl();
  7215. return;
  7216. }
  7217. if (T.getAddressSpace() == LangAS::opencl_constant ||
  7218. T.getAddressSpace() == LangAS::opencl_local) {
  7219. FunctionDecl *FD = getCurFunctionDecl();
  7220. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  7221. // in functions.
  7222. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  7223. if (T.getAddressSpace() == LangAS::opencl_constant)
  7224. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7225. << 0 /*non-kernel only*/ << "constant";
  7226. else
  7227. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7228. << 0 /*non-kernel only*/ << "local";
  7229. NewVD->setInvalidDecl();
  7230. return;
  7231. }
  7232. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  7233. // in the outermost scope of a kernel function.
  7234. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  7235. if (!getCurScope()->isFunctionScope()) {
  7236. if (T.getAddressSpace() == LangAS::opencl_constant)
  7237. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  7238. << "constant";
  7239. else
  7240. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  7241. << "local";
  7242. NewVD->setInvalidDecl();
  7243. return;
  7244. }
  7245. }
  7246. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  7247. // If we are parsing a template we didn't deduce an addr
  7248. // space yet.
  7249. T.getAddressSpace() != LangAS::Default) {
  7250. // Do not allow other address spaces on automatic variable.
  7251. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  7252. NewVD->setInvalidDecl();
  7253. return;
  7254. }
  7255. }
  7256. }
  7257. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  7258. && !NewVD->hasAttr<BlocksAttr>()) {
  7259. if (getLangOpts().getGC() != LangOptions::NonGC)
  7260. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  7261. else {
  7262. assert(!getLangOpts().ObjCAutoRefCount);
  7263. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  7264. }
  7265. }
  7266. bool isVM = T->isVariablyModifiedType();
  7267. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  7268. NewVD->hasAttr<BlocksAttr>())
  7269. setFunctionHasBranchProtectedScope();
  7270. if ((isVM && NewVD->hasLinkage()) ||
  7271. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  7272. bool SizeIsNegative;
  7273. llvm::APSInt Oversized;
  7274. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  7275. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  7276. QualType FixedT;
  7277. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  7278. FixedT = FixedTInfo->getType();
  7279. else if (FixedTInfo) {
  7280. // Type and type-as-written are canonically different. We need to fix up
  7281. // both types separately.
  7282. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  7283. Oversized);
  7284. }
  7285. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  7286. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  7287. // FIXME: This won't give the correct result for
  7288. // int a[10][n];
  7289. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  7290. if (NewVD->isFileVarDecl())
  7291. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  7292. << SizeRange;
  7293. else if (NewVD->isStaticLocal())
  7294. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  7295. << SizeRange;
  7296. else
  7297. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  7298. << SizeRange;
  7299. NewVD->setInvalidDecl();
  7300. return;
  7301. }
  7302. if (!FixedTInfo) {
  7303. if (NewVD->isFileVarDecl())
  7304. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  7305. else
  7306. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  7307. NewVD->setInvalidDecl();
  7308. return;
  7309. }
  7310. Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
  7311. NewVD->setType(FixedT);
  7312. NewVD->setTypeSourceInfo(FixedTInfo);
  7313. }
  7314. if (T->isVoidType()) {
  7315. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  7316. // of objects and functions.
  7317. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  7318. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  7319. << T;
  7320. NewVD->setInvalidDecl();
  7321. return;
  7322. }
  7323. }
  7324. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  7325. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  7326. NewVD->setInvalidDecl();
  7327. return;
  7328. }
  7329. if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
  7330. Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
  7331. NewVD->setInvalidDecl();
  7332. return;
  7333. }
  7334. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  7335. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  7336. NewVD->setInvalidDecl();
  7337. return;
  7338. }
  7339. if (NewVD->isConstexpr() && !T->isDependentType() &&
  7340. RequireLiteralType(NewVD->getLocation(), T,
  7341. diag::err_constexpr_var_non_literal)) {
  7342. NewVD->setInvalidDecl();
  7343. return;
  7344. }
  7345. // PPC MMA non-pointer types are not allowed as non-local variable types.
  7346. if (Context.getTargetInfo().getTriple().isPPC64() &&
  7347. !NewVD->isLocalVarDecl() &&
  7348. CheckPPCMMAType(T, NewVD->getLocation())) {
  7349. NewVD->setInvalidDecl();
  7350. return;
  7351. }
  7352. }
  7353. /// Perform semantic checking on a newly-created variable
  7354. /// declaration.
  7355. ///
  7356. /// This routine performs all of the type-checking required for a
  7357. /// variable declaration once it has been built. It is used both to
  7358. /// check variables after they have been parsed and their declarators
  7359. /// have been translated into a declaration, and to check variables
  7360. /// that have been instantiated from a template.
  7361. ///
  7362. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  7363. ///
  7364. /// Returns true if the variable declaration is a redeclaration.
  7365. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  7366. CheckVariableDeclarationType(NewVD);
  7367. // If the decl is already known invalid, don't check it.
  7368. if (NewVD->isInvalidDecl())
  7369. return false;
  7370. // If we did not find anything by this name, look for a non-visible
  7371. // extern "C" declaration with the same name.
  7372. if (Previous.empty() &&
  7373. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  7374. Previous.setShadowed();
  7375. if (!Previous.empty()) {
  7376. MergeVarDecl(NewVD, Previous);
  7377. return true;
  7378. }
  7379. return false;
  7380. }
  7381. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  7382. /// and if so, check that it's a valid override and remember it.
  7383. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  7384. llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
  7385. // Look for methods in base classes that this method might override.
  7386. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
  7387. /*DetectVirtual=*/false);
  7388. auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  7389. CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
  7390. DeclarationName Name = MD->getDeclName();
  7391. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7392. // We really want to find the base class destructor here.
  7393. QualType T = Context.getTypeDeclType(BaseRecord);
  7394. CanQualType CT = Context.getCanonicalType(T);
  7395. Name = Context.DeclarationNames.getCXXDestructorName(CT);
  7396. }
  7397. for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
  7398. CXXMethodDecl *BaseMD =
  7399. dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
  7400. if (!BaseMD || !BaseMD->isVirtual() ||
  7401. IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
  7402. /*ConsiderCudaAttrs=*/true,
  7403. // C++2a [class.virtual]p2 does not consider requires
  7404. // clauses when overriding.
  7405. /*ConsiderRequiresClauses=*/false))
  7406. continue;
  7407. if (Overridden.insert(BaseMD).second) {
  7408. MD->addOverriddenMethod(BaseMD);
  7409. CheckOverridingFunctionReturnType(MD, BaseMD);
  7410. CheckOverridingFunctionAttributes(MD, BaseMD);
  7411. CheckOverridingFunctionExceptionSpec(MD, BaseMD);
  7412. CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
  7413. }
  7414. // A method can only override one function from each base class. We
  7415. // don't track indirectly overridden methods from bases of bases.
  7416. return true;
  7417. }
  7418. return false;
  7419. };
  7420. DC->lookupInBases(VisitBase, Paths);
  7421. return !Overridden.empty();
  7422. }
  7423. namespace {
  7424. // Struct for holding all of the extra arguments needed by
  7425. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  7426. struct ActOnFDArgs {
  7427. Scope *S;
  7428. Declarator &D;
  7429. MultiTemplateParamsArg TemplateParamLists;
  7430. bool AddToScope;
  7431. };
  7432. } // end anonymous namespace
  7433. namespace {
  7434. // Callback to only accept typo corrections that have a non-zero edit distance.
  7435. // Also only accept corrections that have the same parent decl.
  7436. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  7437. public:
  7438. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  7439. CXXRecordDecl *Parent)
  7440. : Context(Context), OriginalFD(TypoFD),
  7441. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  7442. bool ValidateCandidate(const TypoCorrection &candidate) override {
  7443. if (candidate.getEditDistance() == 0)
  7444. return false;
  7445. SmallVector<unsigned, 1> MismatchedParams;
  7446. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  7447. CDeclEnd = candidate.end();
  7448. CDecl != CDeclEnd; ++CDecl) {
  7449. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7450. if (FD && !FD->hasBody() &&
  7451. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  7452. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  7453. CXXRecordDecl *Parent = MD->getParent();
  7454. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  7455. return true;
  7456. } else if (!ExpectedParent) {
  7457. return true;
  7458. }
  7459. }
  7460. }
  7461. return false;
  7462. }
  7463. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  7464. return std::make_unique<DifferentNameValidatorCCC>(*this);
  7465. }
  7466. private:
  7467. ASTContext &Context;
  7468. FunctionDecl *OriginalFD;
  7469. CXXRecordDecl *ExpectedParent;
  7470. };
  7471. } // end anonymous namespace
  7472. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7473. TypoCorrectedFunctionDefinitions.insert(F);
  7474. }
  7475. /// Generate diagnostics for an invalid function redeclaration.
  7476. ///
  7477. /// This routine handles generating the diagnostic messages for an invalid
  7478. /// function redeclaration, including finding possible similar declarations
  7479. /// or performing typo correction if there are no previous declarations with
  7480. /// the same name.
  7481. ///
  7482. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7483. /// the new declaration name does not cause new errors.
  7484. static NamedDecl *DiagnoseInvalidRedeclaration(
  7485. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7486. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7487. DeclarationName Name = NewFD->getDeclName();
  7488. DeclContext *NewDC = NewFD->getDeclContext();
  7489. SmallVector<unsigned, 1> MismatchedParams;
  7490. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7491. TypoCorrection Correction;
  7492. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7493. unsigned DiagMsg =
  7494. IsLocalFriend ? diag::err_no_matching_local_friend :
  7495. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7496. diag::err_member_decl_does_not_match;
  7497. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7498. IsLocalFriend ? Sema::LookupLocalFriendName
  7499. : Sema::LookupOrdinaryName,
  7500. Sema::ForVisibleRedeclaration);
  7501. NewFD->setInvalidDecl();
  7502. if (IsLocalFriend)
  7503. SemaRef.LookupName(Prev, S);
  7504. else
  7505. SemaRef.LookupQualifiedName(Prev, NewDC);
  7506. assert(!Prev.isAmbiguous() &&
  7507. "Cannot have an ambiguity in previous-declaration lookup");
  7508. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7509. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7510. MD ? MD->getParent() : nullptr);
  7511. if (!Prev.empty()) {
  7512. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7513. Func != FuncEnd; ++Func) {
  7514. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7515. if (FD &&
  7516. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7517. // Add 1 to the index so that 0 can mean the mismatch didn't
  7518. // involve a parameter
  7519. unsigned ParamNum =
  7520. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7521. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7522. }
  7523. }
  7524. // If the qualified name lookup yielded nothing, try typo correction
  7525. } else if ((Correction = SemaRef.CorrectTypo(
  7526. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7527. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7528. IsLocalFriend ? nullptr : NewDC))) {
  7529. // Set up everything for the call to ActOnFunctionDeclarator
  7530. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7531. ExtraArgs.D.getIdentifierLoc());
  7532. Previous.clear();
  7533. Previous.setLookupName(Correction.getCorrection());
  7534. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7535. CDeclEnd = Correction.end();
  7536. CDecl != CDeclEnd; ++CDecl) {
  7537. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7538. if (FD && !FD->hasBody() &&
  7539. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7540. Previous.addDecl(FD);
  7541. }
  7542. }
  7543. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7544. NamedDecl *Result;
  7545. // Retry building the function declaration with the new previous
  7546. // declarations, and with errors suppressed.
  7547. {
  7548. // Trap errors.
  7549. Sema::SFINAETrap Trap(SemaRef);
  7550. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7551. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7552. // eliminate the need for the parameter pack ExtraArgs.
  7553. Result = SemaRef.ActOnFunctionDeclarator(
  7554. ExtraArgs.S, ExtraArgs.D,
  7555. Correction.getCorrectionDecl()->getDeclContext(),
  7556. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7557. ExtraArgs.AddToScope);
  7558. if (Trap.hasErrorOccurred())
  7559. Result = nullptr;
  7560. }
  7561. if (Result) {
  7562. // Determine which correction we picked.
  7563. Decl *Canonical = Result->getCanonicalDecl();
  7564. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7565. I != E; ++I)
  7566. if ((*I)->getCanonicalDecl() == Canonical)
  7567. Correction.setCorrectionDecl(*I);
  7568. // Let Sema know about the correction.
  7569. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7570. SemaRef.diagnoseTypo(
  7571. Correction,
  7572. SemaRef.PDiag(IsLocalFriend
  7573. ? diag::err_no_matching_local_friend_suggest
  7574. : diag::err_member_decl_does_not_match_suggest)
  7575. << Name << NewDC << IsDefinition);
  7576. return Result;
  7577. }
  7578. // Pretend the typo correction never occurred
  7579. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7580. ExtraArgs.D.getIdentifierLoc());
  7581. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7582. Previous.clear();
  7583. Previous.setLookupName(Name);
  7584. }
  7585. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7586. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7587. bool NewFDisConst = false;
  7588. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7589. NewFDisConst = NewMD->isConst();
  7590. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7591. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7592. NearMatch != NearMatchEnd; ++NearMatch) {
  7593. FunctionDecl *FD = NearMatch->first;
  7594. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7595. bool FDisConst = MD && MD->isConst();
  7596. bool IsMember = MD || !IsLocalFriend;
  7597. // FIXME: These notes are poorly worded for the local friend case.
  7598. if (unsigned Idx = NearMatch->second) {
  7599. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7600. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7601. if (Loc.isInvalid()) Loc = FD->getLocation();
  7602. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7603. : diag::note_local_decl_close_param_match)
  7604. << Idx << FDParam->getType()
  7605. << NewFD->getParamDecl(Idx - 1)->getType();
  7606. } else if (FDisConst != NewFDisConst) {
  7607. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7608. << NewFDisConst << FD->getSourceRange().getEnd()
  7609. << (NewFDisConst
  7610. ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
  7611. .getConstQualifierLoc())
  7612. : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
  7613. .getRParenLoc()
  7614. .getLocWithOffset(1),
  7615. " const"));
  7616. } else
  7617. SemaRef.Diag(FD->getLocation(),
  7618. IsMember ? diag::note_member_def_close_match
  7619. : diag::note_local_decl_close_match);
  7620. }
  7621. return nullptr;
  7622. }
  7623. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  7624. switch (D.getDeclSpec().getStorageClassSpec()) {
  7625. default: llvm_unreachable("Unknown storage class!");
  7626. case DeclSpec::SCS_auto:
  7627. case DeclSpec::SCS_register:
  7628. case DeclSpec::SCS_mutable:
  7629. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7630. diag::err_typecheck_sclass_func);
  7631. D.getMutableDeclSpec().ClearStorageClassSpecs();
  7632. D.setInvalidType();
  7633. break;
  7634. case DeclSpec::SCS_unspecified: break;
  7635. case DeclSpec::SCS_extern:
  7636. if (D.getDeclSpec().isExternInLinkageSpec())
  7637. return SC_None;
  7638. return SC_Extern;
  7639. case DeclSpec::SCS_static: {
  7640. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  7641. // C99 6.7.1p5:
  7642. // The declaration of an identifier for a function that has
  7643. // block scope shall have no explicit storage-class specifier
  7644. // other than extern
  7645. // See also (C++ [dcl.stc]p4).
  7646. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7647. diag::err_static_block_func);
  7648. break;
  7649. } else
  7650. return SC_Static;
  7651. }
  7652. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  7653. }
  7654. // No explicit storage class has already been returned
  7655. return SC_None;
  7656. }
  7657. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  7658. DeclContext *DC, QualType &R,
  7659. TypeSourceInfo *TInfo,
  7660. StorageClass SC,
  7661. bool &IsVirtualOkay) {
  7662. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7663. DeclarationName Name = NameInfo.getName();
  7664. FunctionDecl *NewFD = nullptr;
  7665. bool isInline = D.getDeclSpec().isInlineSpecified();
  7666. if (!SemaRef.getLangOpts().CPlusPlus) {
  7667. // Determine whether the function was written with a
  7668. // prototype. This true when:
  7669. // - there is a prototype in the declarator, or
  7670. // - the type R of the function is some kind of typedef or other non-
  7671. // attributed reference to a type name (which eventually refers to a
  7672. // function type).
  7673. bool HasPrototype =
  7674. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7675. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7676. NewFD = FunctionDecl::Create(
  7677. SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
  7678. SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
  7679. ConstexprSpecKind::Unspecified,
  7680. /*TrailingRequiresClause=*/nullptr);
  7681. if (D.isInvalidType())
  7682. NewFD->setInvalidDecl();
  7683. return NewFD;
  7684. }
  7685. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  7686. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  7687. if (ConstexprKind == ConstexprSpecKind::Constinit) {
  7688. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  7689. diag::err_constexpr_wrong_decl_kind)
  7690. << static_cast<int>(ConstexprKind);
  7691. ConstexprKind = ConstexprSpecKind::Unspecified;
  7692. D.getMutableDeclSpec().ClearConstexprSpec();
  7693. }
  7694. Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
  7695. // Check that the return type is not an abstract class type.
  7696. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7697. // the class has been completely parsed.
  7698. if (!DC->isRecord() &&
  7699. SemaRef.RequireNonAbstractType(
  7700. D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
  7701. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7702. D.setInvalidType();
  7703. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7704. // This is a C++ constructor declaration.
  7705. assert(DC->isRecord() &&
  7706. "Constructors can only be declared in a member context");
  7707. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7708. return CXXConstructorDecl::Create(
  7709. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7710. TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
  7711. isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
  7712. InheritedConstructor(), TrailingRequiresClause);
  7713. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7714. // This is a C++ destructor declaration.
  7715. if (DC->isRecord()) {
  7716. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7717. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7718. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7719. SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
  7720. SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  7721. /*isImplicitlyDeclared=*/false, ConstexprKind,
  7722. TrailingRequiresClause);
  7723. // If the destructor needs an implicit exception specification, set it
  7724. // now. FIXME: It'd be nice to be able to create the right type to start
  7725. // with, but the type needs to reference the destructor declaration.
  7726. if (SemaRef.getLangOpts().CPlusPlus11)
  7727. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7728. IsVirtualOkay = true;
  7729. return NewDD;
  7730. } else {
  7731. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7732. D.setInvalidType();
  7733. // Create a FunctionDecl to satisfy the function definition parsing
  7734. // code path.
  7735. return FunctionDecl::Create(
  7736. SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
  7737. TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  7738. /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
  7739. }
  7740. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7741. if (!DC->isRecord()) {
  7742. SemaRef.Diag(D.getIdentifierLoc(),
  7743. diag::err_conv_function_not_member);
  7744. return nullptr;
  7745. }
  7746. SemaRef.CheckConversionDeclarator(D, R, SC);
  7747. if (D.isInvalidType())
  7748. return nullptr;
  7749. IsVirtualOkay = true;
  7750. return CXXConversionDecl::Create(
  7751. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7752. TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  7753. ExplicitSpecifier, ConstexprKind, SourceLocation(),
  7754. TrailingRequiresClause);
  7755. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7756. if (TrailingRequiresClause)
  7757. SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
  7758. diag::err_trailing_requires_clause_on_deduction_guide)
  7759. << TrailingRequiresClause->getSourceRange();
  7760. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7761. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7762. ExplicitSpecifier, NameInfo, R, TInfo,
  7763. D.getEndLoc());
  7764. } else if (DC->isRecord()) {
  7765. // If the name of the function is the same as the name of the record,
  7766. // then this must be an invalid constructor that has a return type.
  7767. // (The parser checks for a return type and makes the declarator a
  7768. // constructor if it has no return type).
  7769. if (Name.getAsIdentifierInfo() &&
  7770. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7771. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7772. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7773. << SourceRange(D.getIdentifierLoc());
  7774. return nullptr;
  7775. }
  7776. // This is a C++ method declaration.
  7777. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7778. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7779. TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  7780. ConstexprKind, SourceLocation(), TrailingRequiresClause);
  7781. IsVirtualOkay = !Ret->isStatic();
  7782. return Ret;
  7783. } else {
  7784. bool isFriend =
  7785. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7786. if (!isFriend && SemaRef.CurContext->isRecord())
  7787. return nullptr;
  7788. // Determine whether the function was written with a
  7789. // prototype. This true when:
  7790. // - we're in C++ (where every function has a prototype),
  7791. return FunctionDecl::Create(
  7792. SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
  7793. SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  7794. true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
  7795. }
  7796. }
  7797. enum OpenCLParamType {
  7798. ValidKernelParam,
  7799. PtrPtrKernelParam,
  7800. PtrKernelParam,
  7801. InvalidAddrSpacePtrKernelParam,
  7802. InvalidKernelParam,
  7803. RecordKernelParam
  7804. };
  7805. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7806. // Size dependent types are just typedefs to normal integer types
  7807. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7808. // integers other than by their names.
  7809. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7810. // Remove typedefs one by one until we reach a typedef
  7811. // for a size dependent type.
  7812. QualType DesugaredTy = Ty;
  7813. do {
  7814. ArrayRef<StringRef> Names(SizeTypeNames);
  7815. auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
  7816. if (Names.end() != Match)
  7817. return true;
  7818. Ty = DesugaredTy;
  7819. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7820. } while (DesugaredTy != Ty);
  7821. return false;
  7822. }
  7823. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7824. if (PT->isDependentType())
  7825. return InvalidKernelParam;
  7826. if (PT->isPointerType() || PT->isReferenceType()) {
  7827. QualType PointeeType = PT->getPointeeType();
  7828. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7829. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7830. PointeeType.getAddressSpace() == LangAS::Default)
  7831. return InvalidAddrSpacePtrKernelParam;
  7832. if (PointeeType->isPointerType()) {
  7833. // This is a pointer to pointer parameter.
  7834. // Recursively check inner type.
  7835. OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
  7836. if (ParamKind == InvalidAddrSpacePtrKernelParam ||
  7837. ParamKind == InvalidKernelParam)
  7838. return ParamKind;
  7839. return PtrPtrKernelParam;
  7840. }
  7841. // C++ for OpenCL v1.0 s2.4:
  7842. // Moreover the types used in parameters of the kernel functions must be:
  7843. // Standard layout types for pointer parameters. The same applies to
  7844. // reference if an implementation supports them in kernel parameters.
  7845. if (S.getLangOpts().OpenCLCPlusPlus &&
  7846. !S.getOpenCLOptions().isAvailableOption(
  7847. "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
  7848. !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
  7849. !PointeeType->isStandardLayoutType())
  7850. return InvalidKernelParam;
  7851. return PtrKernelParam;
  7852. }
  7853. // OpenCL v1.2 s6.9.k:
  7854. // Arguments to kernel functions in a program cannot be declared with the
  7855. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7856. // uintptr_t or a struct and/or union that contain fields declared to be one
  7857. // of these built-in scalar types.
  7858. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7859. return InvalidKernelParam;
  7860. if (PT->isImageType())
  7861. return PtrKernelParam;
  7862. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7863. return InvalidKernelParam;
  7864. // OpenCL extension spec v1.2 s9.5:
  7865. // This extension adds support for half scalar and vector types as built-in
  7866. // types that can be used for arithmetic operations, conversions etc.
  7867. if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
  7868. PT->isHalfType())
  7869. return InvalidKernelParam;
  7870. // Look into an array argument to check if it has a forbidden type.
  7871. if (PT->isArrayType()) {
  7872. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7873. // Call ourself to check an underlying type of an array. Since the
  7874. // getPointeeOrArrayElementType returns an innermost type which is not an
  7875. // array, this recursive call only happens once.
  7876. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7877. }
  7878. // C++ for OpenCL v1.0 s2.4:
  7879. // Moreover the types used in parameters of the kernel functions must be:
  7880. // Trivial and standard-layout types C++17 [basic.types] (plain old data
  7881. // types) for parameters passed by value;
  7882. if (S.getLangOpts().OpenCLCPlusPlus &&
  7883. !S.getOpenCLOptions().isAvailableOption(
  7884. "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
  7885. !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
  7886. return InvalidKernelParam;
  7887. if (PT->isRecordType())
  7888. return RecordKernelParam;
  7889. return ValidKernelParam;
  7890. }
  7891. static void checkIsValidOpenCLKernelParameter(
  7892. Sema &S,
  7893. Declarator &D,
  7894. ParmVarDecl *Param,
  7895. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7896. QualType PT = Param->getType();
  7897. // Cache the valid types we encounter to avoid rechecking structs that are
  7898. // used again
  7899. if (ValidTypes.count(PT.getTypePtr()))
  7900. return;
  7901. switch (getOpenCLKernelParameterType(S, PT)) {
  7902. case PtrPtrKernelParam:
  7903. // OpenCL v3.0 s6.11.a:
  7904. // A kernel function argument cannot be declared as a pointer to a pointer
  7905. // type. [...] This restriction only applies to OpenCL C 1.2 or below.
  7906. if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
  7907. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7908. D.setInvalidType();
  7909. return;
  7910. }
  7911. ValidTypes.insert(PT.getTypePtr());
  7912. return;
  7913. case InvalidAddrSpacePtrKernelParam:
  7914. // OpenCL v1.0 s6.5:
  7915. // __kernel function arguments declared to be a pointer of a type can point
  7916. // to one of the following address spaces only : __global, __local or
  7917. // __constant.
  7918. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7919. D.setInvalidType();
  7920. return;
  7921. // OpenCL v1.2 s6.9.k:
  7922. // Arguments to kernel functions in a program cannot be declared with the
  7923. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7924. // uintptr_t or a struct and/or union that contain fields declared to be
  7925. // one of these built-in scalar types.
  7926. case InvalidKernelParam:
  7927. // OpenCL v1.2 s6.8 n:
  7928. // A kernel function argument cannot be declared
  7929. // of event_t type.
  7930. // Do not diagnose half type since it is diagnosed as invalid argument
  7931. // type for any function elsewhere.
  7932. if (!PT->isHalfType()) {
  7933. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7934. // Explain what typedefs are involved.
  7935. const TypedefType *Typedef = nullptr;
  7936. while ((Typedef = PT->getAs<TypedefType>())) {
  7937. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7938. // SourceLocation may be invalid for a built-in type.
  7939. if (Loc.isValid())
  7940. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7941. PT = Typedef->desugar();
  7942. }
  7943. }
  7944. D.setInvalidType();
  7945. return;
  7946. case PtrKernelParam:
  7947. case ValidKernelParam:
  7948. ValidTypes.insert(PT.getTypePtr());
  7949. return;
  7950. case RecordKernelParam:
  7951. break;
  7952. }
  7953. // Track nested structs we will inspect
  7954. SmallVector<const Decl *, 4> VisitStack;
  7955. // Track where we are in the nested structs. Items will migrate from
  7956. // VisitStack to HistoryStack as we do the DFS for bad field.
  7957. SmallVector<const FieldDecl *, 4> HistoryStack;
  7958. HistoryStack.push_back(nullptr);
  7959. // At this point we already handled everything except of a RecordType or
  7960. // an ArrayType of a RecordType.
  7961. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7962. const RecordType *RecTy =
  7963. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7964. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7965. VisitStack.push_back(RecTy->getDecl());
  7966. assert(VisitStack.back() && "First decl null?");
  7967. do {
  7968. const Decl *Next = VisitStack.pop_back_val();
  7969. if (!Next) {
  7970. assert(!HistoryStack.empty());
  7971. // Found a marker, we have gone up a level
  7972. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7973. ValidTypes.insert(Hist->getType().getTypePtr());
  7974. continue;
  7975. }
  7976. // Adds everything except the original parameter declaration (which is not a
  7977. // field itself) to the history stack.
  7978. const RecordDecl *RD;
  7979. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7980. HistoryStack.push_back(Field);
  7981. QualType FieldTy = Field->getType();
  7982. // Other field types (known to be valid or invalid) are handled while we
  7983. // walk around RecordDecl::fields().
  7984. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7985. "Unexpected type.");
  7986. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7987. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7988. } else {
  7989. RD = cast<RecordDecl>(Next);
  7990. }
  7991. // Add a null marker so we know when we've gone back up a level
  7992. VisitStack.push_back(nullptr);
  7993. for (const auto *FD : RD->fields()) {
  7994. QualType QT = FD->getType();
  7995. if (ValidTypes.count(QT.getTypePtr()))
  7996. continue;
  7997. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7998. if (ParamType == ValidKernelParam)
  7999. continue;
  8000. if (ParamType == RecordKernelParam) {
  8001. VisitStack.push_back(FD);
  8002. continue;
  8003. }
  8004. // OpenCL v1.2 s6.9.p:
  8005. // Arguments to kernel functions that are declared to be a struct or union
  8006. // do not allow OpenCL objects to be passed as elements of the struct or
  8007. // union.
  8008. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  8009. ParamType == InvalidAddrSpacePtrKernelParam) {
  8010. S.Diag(Param->getLocation(),
  8011. diag::err_record_with_pointers_kernel_param)
  8012. << PT->isUnionType()
  8013. << PT;
  8014. } else {
  8015. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  8016. }
  8017. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  8018. << OrigRecDecl->getDeclName();
  8019. // We have an error, now let's go back up through history and show where
  8020. // the offending field came from
  8021. for (ArrayRef<const FieldDecl *>::const_iterator
  8022. I = HistoryStack.begin() + 1,
  8023. E = HistoryStack.end();
  8024. I != E; ++I) {
  8025. const FieldDecl *OuterField = *I;
  8026. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  8027. << OuterField->getType();
  8028. }
  8029. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  8030. << QT->isPointerType()
  8031. << QT;
  8032. D.setInvalidType();
  8033. return;
  8034. }
  8035. } while (!VisitStack.empty());
  8036. }
  8037. /// Find the DeclContext in which a tag is implicitly declared if we see an
  8038. /// elaborated type specifier in the specified context, and lookup finds
  8039. /// nothing.
  8040. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  8041. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  8042. DC = DC->getParent();
  8043. return DC;
  8044. }
  8045. /// Find the Scope in which a tag is implicitly declared if we see an
  8046. /// elaborated type specifier in the specified context, and lookup finds
  8047. /// nothing.
  8048. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  8049. while (S->isClassScope() ||
  8050. (LangOpts.CPlusPlus &&
  8051. S->isFunctionPrototypeScope()) ||
  8052. ((S->getFlags() & Scope::DeclScope) == 0) ||
  8053. (S->getEntity() && S->getEntity()->isTransparentContext()))
  8054. S = S->getParent();
  8055. return S;
  8056. }
  8057. NamedDecl*
  8058. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  8059. TypeSourceInfo *TInfo, LookupResult &Previous,
  8060. MultiTemplateParamsArg TemplateParamListsRef,
  8061. bool &AddToScope) {
  8062. QualType R = TInfo->getType();
  8063. assert(R->isFunctionType());
  8064. if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
  8065. Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
  8066. SmallVector<TemplateParameterList *, 4> TemplateParamLists;
  8067. for (TemplateParameterList *TPL : TemplateParamListsRef)
  8068. TemplateParamLists.push_back(TPL);
  8069. if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
  8070. if (!TemplateParamLists.empty() &&
  8071. Invented->getDepth() == TemplateParamLists.back()->getDepth())
  8072. TemplateParamLists.back() = Invented;
  8073. else
  8074. TemplateParamLists.push_back(Invented);
  8075. }
  8076. // TODO: consider using NameInfo for diagnostic.
  8077. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  8078. DeclarationName Name = NameInfo.getName();
  8079. StorageClass SC = getFunctionStorageClass(*this, D);
  8080. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  8081. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  8082. diag::err_invalid_thread)
  8083. << DeclSpec::getSpecifierName(TSCS);
  8084. if (D.isFirstDeclarationOfMember())
  8085. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  8086. D.getIdentifierLoc());
  8087. bool isFriend = false;
  8088. FunctionTemplateDecl *FunctionTemplate = nullptr;
  8089. bool isMemberSpecialization = false;
  8090. bool isFunctionTemplateSpecialization = false;
  8091. bool isDependentClassScopeExplicitSpecialization = false;
  8092. bool HasExplicitTemplateArgs = false;
  8093. TemplateArgumentListInfo TemplateArgs;
  8094. bool isVirtualOkay = false;
  8095. DeclContext *OriginalDC = DC;
  8096. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  8097. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  8098. isVirtualOkay);
  8099. if (!NewFD) return nullptr;
  8100. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  8101. NewFD->setTopLevelDeclInObjCContainer();
  8102. // Set the lexical context. If this is a function-scope declaration, or has a
  8103. // C++ scope specifier, or is the object of a friend declaration, the lexical
  8104. // context will be different from the semantic context.
  8105. NewFD->setLexicalDeclContext(CurContext);
  8106. if (IsLocalExternDecl)
  8107. NewFD->setLocalExternDecl();
  8108. if (getLangOpts().CPlusPlus) {
  8109. bool isInline = D.getDeclSpec().isInlineSpecified();
  8110. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  8111. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  8112. isFriend = D.getDeclSpec().isFriendSpecified();
  8113. if (isFriend && !isInline && D.isFunctionDefinition()) {
  8114. // C++ [class.friend]p5
  8115. // A function can be defined in a friend declaration of a
  8116. // class . . . . Such a function is implicitly inline.
  8117. NewFD->setImplicitlyInline();
  8118. }
  8119. // If this is a method defined in an __interface, and is not a constructor
  8120. // or an overloaded operator, then set the pure flag (isVirtual will already
  8121. // return true).
  8122. if (const CXXRecordDecl *Parent =
  8123. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  8124. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  8125. NewFD->setPure(true);
  8126. // C++ [class.union]p2
  8127. // A union can have member functions, but not virtual functions.
  8128. if (isVirtual && Parent->isUnion()) {
  8129. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  8130. NewFD->setInvalidDecl();
  8131. }
  8132. if ((Parent->isClass() || Parent->isStruct()) &&
  8133. Parent->hasAttr<SYCLSpecialClassAttr>() &&
  8134. NewFD->getKind() == Decl::Kind::CXXMethod &&
  8135. NewFD->getName() == "__init" && D.isFunctionDefinition()) {
  8136. if (auto *Def = Parent->getDefinition())
  8137. Def->setInitMethod(true);
  8138. }
  8139. }
  8140. SetNestedNameSpecifier(*this, NewFD, D);
  8141. isMemberSpecialization = false;
  8142. isFunctionTemplateSpecialization = false;
  8143. if (D.isInvalidType())
  8144. NewFD->setInvalidDecl();
  8145. // Match up the template parameter lists with the scope specifier, then
  8146. // determine whether we have a template or a template specialization.
  8147. bool Invalid = false;
  8148. TemplateParameterList *TemplateParams =
  8149. MatchTemplateParametersToScopeSpecifier(
  8150. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  8151. D.getCXXScopeSpec(),
  8152. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  8153. ? D.getName().TemplateId
  8154. : nullptr,
  8155. TemplateParamLists, isFriend, isMemberSpecialization,
  8156. Invalid);
  8157. if (TemplateParams) {
  8158. // Check that we can declare a template here.
  8159. if (CheckTemplateDeclScope(S, TemplateParams))
  8160. NewFD->setInvalidDecl();
  8161. if (TemplateParams->size() > 0) {
  8162. // This is a function template
  8163. // A destructor cannot be a template.
  8164. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  8165. Diag(NewFD->getLocation(), diag::err_destructor_template);
  8166. NewFD->setInvalidDecl();
  8167. }
  8168. // If we're adding a template to a dependent context, we may need to
  8169. // rebuilding some of the types used within the template parameter list,
  8170. // now that we know what the current instantiation is.
  8171. if (DC->isDependentContext()) {
  8172. ContextRAII SavedContext(*this, DC);
  8173. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  8174. Invalid = true;
  8175. }
  8176. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  8177. NewFD->getLocation(),
  8178. Name, TemplateParams,
  8179. NewFD);
  8180. FunctionTemplate->setLexicalDeclContext(CurContext);
  8181. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  8182. // For source fidelity, store the other template param lists.
  8183. if (TemplateParamLists.size() > 1) {
  8184. NewFD->setTemplateParameterListsInfo(Context,
  8185. ArrayRef<TemplateParameterList *>(TemplateParamLists)
  8186. .drop_back(1));
  8187. }
  8188. } else {
  8189. // This is a function template specialization.
  8190. isFunctionTemplateSpecialization = true;
  8191. // For source fidelity, store all the template param lists.
  8192. if (TemplateParamLists.size() > 0)
  8193. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  8194. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  8195. if (isFriend) {
  8196. // We want to remove the "template<>", found here.
  8197. SourceRange RemoveRange = TemplateParams->getSourceRange();
  8198. // If we remove the template<> and the name is not a
  8199. // template-id, we're actually silently creating a problem:
  8200. // the friend declaration will refer to an untemplated decl,
  8201. // and clearly the user wants a template specialization. So
  8202. // we need to insert '<>' after the name.
  8203. SourceLocation InsertLoc;
  8204. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  8205. InsertLoc = D.getName().getSourceRange().getEnd();
  8206. InsertLoc = getLocForEndOfToken(InsertLoc);
  8207. }
  8208. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  8209. << Name << RemoveRange
  8210. << FixItHint::CreateRemoval(RemoveRange)
  8211. << FixItHint::CreateInsertion(InsertLoc, "<>");
  8212. Invalid = true;
  8213. }
  8214. }
  8215. } else {
  8216. // Check that we can declare a template here.
  8217. if (!TemplateParamLists.empty() && isMemberSpecialization &&
  8218. CheckTemplateDeclScope(S, TemplateParamLists.back()))
  8219. NewFD->setInvalidDecl();
  8220. // All template param lists were matched against the scope specifier:
  8221. // this is NOT (an explicit specialization of) a template.
  8222. if (TemplateParamLists.size() > 0)
  8223. // For source fidelity, store all the template param lists.
  8224. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  8225. }
  8226. if (Invalid) {
  8227. NewFD->setInvalidDecl();
  8228. if (FunctionTemplate)
  8229. FunctionTemplate->setInvalidDecl();
  8230. }
  8231. // C++ [dcl.fct.spec]p5:
  8232. // The virtual specifier shall only be used in declarations of
  8233. // nonstatic class member functions that appear within a
  8234. // member-specification of a class declaration; see 10.3.
  8235. //
  8236. if (isVirtual && !NewFD->isInvalidDecl()) {
  8237. if (!isVirtualOkay) {
  8238. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8239. diag::err_virtual_non_function);
  8240. } else if (!CurContext->isRecord()) {
  8241. // 'virtual' was specified outside of the class.
  8242. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8243. diag::err_virtual_out_of_class)
  8244. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  8245. } else if (NewFD->getDescribedFunctionTemplate()) {
  8246. // C++ [temp.mem]p3:
  8247. // A member function template shall not be virtual.
  8248. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8249. diag::err_virtual_member_function_template)
  8250. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  8251. } else {
  8252. // Okay: Add virtual to the method.
  8253. NewFD->setVirtualAsWritten(true);
  8254. }
  8255. if (getLangOpts().CPlusPlus14 &&
  8256. NewFD->getReturnType()->isUndeducedType())
  8257. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  8258. }
  8259. if (getLangOpts().CPlusPlus14 &&
  8260. (NewFD->isDependentContext() ||
  8261. (isFriend && CurContext->isDependentContext())) &&
  8262. NewFD->getReturnType()->isUndeducedType()) {
  8263. // If the function template is referenced directly (for instance, as a
  8264. // member of the current instantiation), pretend it has a dependent type.
  8265. // This is not really justified by the standard, but is the only sane
  8266. // thing to do.
  8267. // FIXME: For a friend function, we have not marked the function as being
  8268. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  8269. const FunctionProtoType *FPT =
  8270. NewFD->getType()->castAs<FunctionProtoType>();
  8271. QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
  8272. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  8273. FPT->getExtProtoInfo()));
  8274. }
  8275. // C++ [dcl.fct.spec]p3:
  8276. // The inline specifier shall not appear on a block scope function
  8277. // declaration.
  8278. if (isInline && !NewFD->isInvalidDecl()) {
  8279. if (CurContext->isFunctionOrMethod()) {
  8280. // 'inline' is not allowed on block scope function declaration.
  8281. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8282. diag::err_inline_declaration_block_scope) << Name
  8283. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  8284. }
  8285. }
  8286. // C++ [dcl.fct.spec]p6:
  8287. // The explicit specifier shall be used only in the declaration of a
  8288. // constructor or conversion function within its class definition;
  8289. // see 12.3.1 and 12.3.2.
  8290. if (hasExplicit && !NewFD->isInvalidDecl() &&
  8291. !isa<CXXDeductionGuideDecl>(NewFD)) {
  8292. if (!CurContext->isRecord()) {
  8293. // 'explicit' was specified outside of the class.
  8294. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  8295. diag::err_explicit_out_of_class)
  8296. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  8297. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  8298. !isa<CXXConversionDecl>(NewFD)) {
  8299. // 'explicit' was specified on a function that wasn't a constructor
  8300. // or conversion function.
  8301. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  8302. diag::err_explicit_non_ctor_or_conv_function)
  8303. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  8304. }
  8305. }
  8306. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  8307. if (ConstexprKind != ConstexprSpecKind::Unspecified) {
  8308. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  8309. // are implicitly inline.
  8310. NewFD->setImplicitlyInline();
  8311. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  8312. // be either constructors or to return a literal type. Therefore,
  8313. // destructors cannot be declared constexpr.
  8314. if (isa<CXXDestructorDecl>(NewFD) &&
  8315. (!getLangOpts().CPlusPlus20 ||
  8316. ConstexprKind == ConstexprSpecKind::Consteval)) {
  8317. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  8318. << static_cast<int>(ConstexprKind);
  8319. NewFD->setConstexprKind(getLangOpts().CPlusPlus20
  8320. ? ConstexprSpecKind::Unspecified
  8321. : ConstexprSpecKind::Constexpr);
  8322. }
  8323. // C++20 [dcl.constexpr]p2: An allocation function, or a
  8324. // deallocation function shall not be declared with the consteval
  8325. // specifier.
  8326. if (ConstexprKind == ConstexprSpecKind::Consteval &&
  8327. (NewFD->getOverloadedOperator() == OO_New ||
  8328. NewFD->getOverloadedOperator() == OO_Array_New ||
  8329. NewFD->getOverloadedOperator() == OO_Delete ||
  8330. NewFD->getOverloadedOperator() == OO_Array_Delete)) {
  8331. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  8332. diag::err_invalid_consteval_decl_kind)
  8333. << NewFD;
  8334. NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
  8335. }
  8336. }
  8337. // If __module_private__ was specified, mark the function accordingly.
  8338. if (D.getDeclSpec().isModulePrivateSpecified()) {
  8339. if (isFunctionTemplateSpecialization) {
  8340. SourceLocation ModulePrivateLoc
  8341. = D.getDeclSpec().getModulePrivateSpecLoc();
  8342. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  8343. << 0
  8344. << FixItHint::CreateRemoval(ModulePrivateLoc);
  8345. } else {
  8346. NewFD->setModulePrivate();
  8347. if (FunctionTemplate)
  8348. FunctionTemplate->setModulePrivate();
  8349. }
  8350. }
  8351. if (isFriend) {
  8352. if (FunctionTemplate) {
  8353. FunctionTemplate->setObjectOfFriendDecl();
  8354. FunctionTemplate->setAccess(AS_public);
  8355. }
  8356. NewFD->setObjectOfFriendDecl();
  8357. NewFD->setAccess(AS_public);
  8358. }
  8359. // If a function is defined as defaulted or deleted, mark it as such now.
  8360. // We'll do the relevant checks on defaulted / deleted functions later.
  8361. switch (D.getFunctionDefinitionKind()) {
  8362. case FunctionDefinitionKind::Declaration:
  8363. case FunctionDefinitionKind::Definition:
  8364. break;
  8365. case FunctionDefinitionKind::Defaulted:
  8366. NewFD->setDefaulted();
  8367. break;
  8368. case FunctionDefinitionKind::Deleted:
  8369. NewFD->setDeletedAsWritten();
  8370. break;
  8371. }
  8372. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  8373. D.isFunctionDefinition()) {
  8374. // C++ [class.mfct]p2:
  8375. // A member function may be defined (8.4) in its class definition, in
  8376. // which case it is an inline member function (7.1.2)
  8377. NewFD->setImplicitlyInline();
  8378. }
  8379. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  8380. !CurContext->isRecord()) {
  8381. // C++ [class.static]p1:
  8382. // A data or function member of a class may be declared static
  8383. // in a class definition, in which case it is a static member of
  8384. // the class.
  8385. // Complain about the 'static' specifier if it's on an out-of-line
  8386. // member function definition.
  8387. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  8388. // member function template declaration and class member template
  8389. // declaration (MSVC versions before 2015), warn about this.
  8390. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  8391. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  8392. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  8393. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  8394. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  8395. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  8396. }
  8397. // C++11 [except.spec]p15:
  8398. // A deallocation function with no exception-specification is treated
  8399. // as if it were specified with noexcept(true).
  8400. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  8401. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  8402. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  8403. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  8404. NewFD->setType(Context.getFunctionType(
  8405. FPT->getReturnType(), FPT->getParamTypes(),
  8406. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  8407. }
  8408. // Filter out previous declarations that don't match the scope.
  8409. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  8410. D.getCXXScopeSpec().isNotEmpty() ||
  8411. isMemberSpecialization ||
  8412. isFunctionTemplateSpecialization);
  8413. // Handle GNU asm-label extension (encoded as an attribute).
  8414. if (Expr *E = (Expr*) D.getAsmLabel()) {
  8415. // The parser guarantees this is a string.
  8416. StringLiteral *SE = cast<StringLiteral>(E);
  8417. NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
  8418. /*IsLiteralLabel=*/true,
  8419. SE->getStrTokenLoc(0)));
  8420. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  8421. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  8422. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  8423. if (I != ExtnameUndeclaredIdentifiers.end()) {
  8424. if (isDeclExternC(NewFD)) {
  8425. NewFD->addAttr(I->second);
  8426. ExtnameUndeclaredIdentifiers.erase(I);
  8427. } else
  8428. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  8429. << /*Variable*/0 << NewFD;
  8430. }
  8431. }
  8432. // Copy the parameter declarations from the declarator D to the function
  8433. // declaration NewFD, if they are available. First scavenge them into Params.
  8434. SmallVector<ParmVarDecl*, 16> Params;
  8435. unsigned FTIIdx;
  8436. if (D.isFunctionDeclarator(FTIIdx)) {
  8437. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  8438. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  8439. // function that takes no arguments, not a function that takes a
  8440. // single void argument.
  8441. // We let through "const void" here because Sema::GetTypeForDeclarator
  8442. // already checks for that case.
  8443. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  8444. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  8445. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  8446. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  8447. Param->setDeclContext(NewFD);
  8448. Params.push_back(Param);
  8449. if (Param->isInvalidDecl())
  8450. NewFD->setInvalidDecl();
  8451. }
  8452. }
  8453. if (!getLangOpts().CPlusPlus) {
  8454. // In C, find all the tag declarations from the prototype and move them
  8455. // into the function DeclContext. Remove them from the surrounding tag
  8456. // injection context of the function, which is typically but not always
  8457. // the TU.
  8458. DeclContext *PrototypeTagContext =
  8459. getTagInjectionContext(NewFD->getLexicalDeclContext());
  8460. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  8461. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  8462. // We don't want to reparent enumerators. Look at their parent enum
  8463. // instead.
  8464. if (!TD) {
  8465. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  8466. TD = cast<EnumDecl>(ECD->getDeclContext());
  8467. }
  8468. if (!TD)
  8469. continue;
  8470. DeclContext *TagDC = TD->getLexicalDeclContext();
  8471. if (!TagDC->containsDecl(TD))
  8472. continue;
  8473. TagDC->removeDecl(TD);
  8474. TD->setDeclContext(NewFD);
  8475. NewFD->addDecl(TD);
  8476. // Preserve the lexical DeclContext if it is not the surrounding tag
  8477. // injection context of the FD. In this example, the semantic context of
  8478. // E will be f and the lexical context will be S, while both the
  8479. // semantic and lexical contexts of S will be f:
  8480. // void f(struct S { enum E { a } f; } s);
  8481. if (TagDC != PrototypeTagContext)
  8482. TD->setLexicalDeclContext(TagDC);
  8483. }
  8484. }
  8485. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  8486. // When we're declaring a function with a typedef, typeof, etc as in the
  8487. // following example, we'll need to synthesize (unnamed)
  8488. // parameters for use in the declaration.
  8489. //
  8490. // @code
  8491. // typedef void fn(int);
  8492. // fn f;
  8493. // @endcode
  8494. // Synthesize a parameter for each argument type.
  8495. for (const auto &AI : FT->param_types()) {
  8496. ParmVarDecl *Param =
  8497. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  8498. Param->setScopeInfo(0, Params.size());
  8499. Params.push_back(Param);
  8500. }
  8501. } else {
  8502. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  8503. "Should not need args for typedef of non-prototype fn");
  8504. }
  8505. // Finally, we know we have the right number of parameters, install them.
  8506. NewFD->setParams(Params);
  8507. if (D.getDeclSpec().isNoreturnSpecified())
  8508. NewFD->addAttr(C11NoReturnAttr::Create(Context,
  8509. D.getDeclSpec().getNoreturnSpecLoc(),
  8510. AttributeCommonInfo::AS_Keyword));
  8511. // Functions returning a variably modified type violate C99 6.7.5.2p2
  8512. // because all functions have linkage.
  8513. if (!NewFD->isInvalidDecl() &&
  8514. NewFD->getReturnType()->isVariablyModifiedType()) {
  8515. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  8516. NewFD->setInvalidDecl();
  8517. }
  8518. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  8519. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  8520. !NewFD->hasAttr<SectionAttr>())
  8521. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
  8522. Context, PragmaClangTextSection.SectionName,
  8523. PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
  8524. // Apply an implicit SectionAttr if #pragma code_seg is active.
  8525. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  8526. !NewFD->hasAttr<SectionAttr>()) {
  8527. NewFD->addAttr(SectionAttr::CreateImplicit(
  8528. Context, CodeSegStack.CurrentValue->getString(),
  8529. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8530. SectionAttr::Declspec_allocate));
  8531. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  8532. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  8533. ASTContext::PSF_Read,
  8534. NewFD))
  8535. NewFD->dropAttr<SectionAttr>();
  8536. }
  8537. // Apply an implicit CodeSegAttr from class declspec or
  8538. // apply an implicit SectionAttr from #pragma code_seg if active.
  8539. if (!NewFD->hasAttr<CodeSegAttr>()) {
  8540. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  8541. D.isFunctionDefinition())) {
  8542. NewFD->addAttr(SAttr);
  8543. }
  8544. }
  8545. // Handle attributes.
  8546. ProcessDeclAttributes(S, NewFD, D);
  8547. if (getLangOpts().OpenCL) {
  8548. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  8549. // type declaration will generate a compilation error.
  8550. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  8551. if (AddressSpace != LangAS::Default) {
  8552. Diag(NewFD->getLocation(),
  8553. diag::err_opencl_return_value_with_address_space);
  8554. NewFD->setInvalidDecl();
  8555. }
  8556. }
  8557. if (!getLangOpts().CPlusPlus) {
  8558. // Perform semantic checking on the function declaration.
  8559. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8560. CheckMain(NewFD, D.getDeclSpec());
  8561. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8562. CheckMSVCRTEntryPoint(NewFD);
  8563. if (!NewFD->isInvalidDecl())
  8564. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8565. isMemberSpecialization));
  8566. else if (!Previous.empty())
  8567. // Recover gracefully from an invalid redeclaration.
  8568. D.setRedeclaration(true);
  8569. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8570. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8571. "previous declaration set still overloaded");
  8572. // Diagnose no-prototype function declarations with calling conventions that
  8573. // don't support variadic calls. Only do this in C and do it after merging
  8574. // possibly prototyped redeclarations.
  8575. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  8576. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  8577. CallingConv CC = FT->getExtInfo().getCC();
  8578. if (!supportsVariadicCall(CC)) {
  8579. // Windows system headers sometimes accidentally use stdcall without
  8580. // (void) parameters, so we relax this to a warning.
  8581. int DiagID =
  8582. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  8583. Diag(NewFD->getLocation(), DiagID)
  8584. << FunctionType::getNameForCallConv(CC);
  8585. }
  8586. }
  8587. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  8588. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  8589. checkNonTrivialCUnion(NewFD->getReturnType(),
  8590. NewFD->getReturnTypeSourceRange().getBegin(),
  8591. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  8592. } else {
  8593. // C++11 [replacement.functions]p3:
  8594. // The program's definitions shall not be specified as inline.
  8595. //
  8596. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  8597. //
  8598. // Suppress the diagnostic if the function is __attribute__((used)), since
  8599. // that forces an external definition to be emitted.
  8600. if (D.getDeclSpec().isInlineSpecified() &&
  8601. NewFD->isReplaceableGlobalAllocationFunction() &&
  8602. !NewFD->hasAttr<UsedAttr>())
  8603. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8604. diag::ext_operator_new_delete_declared_inline)
  8605. << NewFD->getDeclName();
  8606. // If the declarator is a template-id, translate the parser's template
  8607. // argument list into our AST format.
  8608. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  8609. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  8610. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  8611. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  8612. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  8613. TemplateId->NumArgs);
  8614. translateTemplateArguments(TemplateArgsPtr,
  8615. TemplateArgs);
  8616. HasExplicitTemplateArgs = true;
  8617. if (NewFD->isInvalidDecl()) {
  8618. HasExplicitTemplateArgs = false;
  8619. } else if (FunctionTemplate) {
  8620. // Function template with explicit template arguments.
  8621. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  8622. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  8623. HasExplicitTemplateArgs = false;
  8624. } else {
  8625. assert((isFunctionTemplateSpecialization ||
  8626. D.getDeclSpec().isFriendSpecified()) &&
  8627. "should have a 'template<>' for this decl");
  8628. // "friend void foo<>(int);" is an implicit specialization decl.
  8629. isFunctionTemplateSpecialization = true;
  8630. }
  8631. } else if (isFriend && isFunctionTemplateSpecialization) {
  8632. // This combination is only possible in a recovery case; the user
  8633. // wrote something like:
  8634. // template <> friend void foo(int);
  8635. // which we're recovering from as if the user had written:
  8636. // friend void foo<>(int);
  8637. // Go ahead and fake up a template id.
  8638. HasExplicitTemplateArgs = true;
  8639. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  8640. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  8641. }
  8642. // We do not add HD attributes to specializations here because
  8643. // they may have different constexpr-ness compared to their
  8644. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  8645. // may end up with different effective targets. Instead, a
  8646. // specialization inherits its target attributes from its template
  8647. // in the CheckFunctionTemplateSpecialization() call below.
  8648. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  8649. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  8650. // If it's a friend (and only if it's a friend), it's possible
  8651. // that either the specialized function type or the specialized
  8652. // template is dependent, and therefore matching will fail. In
  8653. // this case, don't check the specialization yet.
  8654. if (isFunctionTemplateSpecialization && isFriend &&
  8655. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  8656. TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
  8657. TemplateArgs.arguments()))) {
  8658. assert(HasExplicitTemplateArgs &&
  8659. "friend function specialization without template args");
  8660. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  8661. Previous))
  8662. NewFD->setInvalidDecl();
  8663. } else if (isFunctionTemplateSpecialization) {
  8664. if (CurContext->isDependentContext() && CurContext->isRecord()
  8665. && !isFriend) {
  8666. isDependentClassScopeExplicitSpecialization = true;
  8667. } else if (!NewFD->isInvalidDecl() &&
  8668. CheckFunctionTemplateSpecialization(
  8669. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  8670. Previous))
  8671. NewFD->setInvalidDecl();
  8672. // C++ [dcl.stc]p1:
  8673. // A storage-class-specifier shall not be specified in an explicit
  8674. // specialization (14.7.3)
  8675. FunctionTemplateSpecializationInfo *Info =
  8676. NewFD->getTemplateSpecializationInfo();
  8677. if (Info && SC != SC_None) {
  8678. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  8679. Diag(NewFD->getLocation(),
  8680. diag::err_explicit_specialization_inconsistent_storage_class)
  8681. << SC
  8682. << FixItHint::CreateRemoval(
  8683. D.getDeclSpec().getStorageClassSpecLoc());
  8684. else
  8685. Diag(NewFD->getLocation(),
  8686. diag::ext_explicit_specialization_storage_class)
  8687. << FixItHint::CreateRemoval(
  8688. D.getDeclSpec().getStorageClassSpecLoc());
  8689. }
  8690. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  8691. if (CheckMemberSpecialization(NewFD, Previous))
  8692. NewFD->setInvalidDecl();
  8693. }
  8694. // Perform semantic checking on the function declaration.
  8695. if (!isDependentClassScopeExplicitSpecialization) {
  8696. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  8697. CheckMain(NewFD, D.getDeclSpec());
  8698. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  8699. CheckMSVCRTEntryPoint(NewFD);
  8700. if (!NewFD->isInvalidDecl())
  8701. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  8702. isMemberSpecialization));
  8703. else if (!Previous.empty())
  8704. // Recover gracefully from an invalid redeclaration.
  8705. D.setRedeclaration(true);
  8706. }
  8707. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  8708. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  8709. "previous declaration set still overloaded");
  8710. NamedDecl *PrincipalDecl = (FunctionTemplate
  8711. ? cast<NamedDecl>(FunctionTemplate)
  8712. : NewFD);
  8713. if (isFriend && NewFD->getPreviousDecl()) {
  8714. AccessSpecifier Access = AS_public;
  8715. if (!NewFD->isInvalidDecl())
  8716. Access = NewFD->getPreviousDecl()->getAccess();
  8717. NewFD->setAccess(Access);
  8718. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  8719. }
  8720. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  8721. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  8722. PrincipalDecl->setNonMemberOperator();
  8723. // If we have a function template, check the template parameter
  8724. // list. This will check and merge default template arguments.
  8725. if (FunctionTemplate) {
  8726. FunctionTemplateDecl *PrevTemplate =
  8727. FunctionTemplate->getPreviousDecl();
  8728. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  8729. PrevTemplate ? PrevTemplate->getTemplateParameters()
  8730. : nullptr,
  8731. D.getDeclSpec().isFriendSpecified()
  8732. ? (D.isFunctionDefinition()
  8733. ? TPC_FriendFunctionTemplateDefinition
  8734. : TPC_FriendFunctionTemplate)
  8735. : (D.getCXXScopeSpec().isSet() &&
  8736. DC && DC->isRecord() &&
  8737. DC->isDependentContext())
  8738. ? TPC_ClassTemplateMember
  8739. : TPC_FunctionTemplate);
  8740. }
  8741. if (NewFD->isInvalidDecl()) {
  8742. // Ignore all the rest of this.
  8743. } else if (!D.isRedeclaration()) {
  8744. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  8745. AddToScope };
  8746. // Fake up an access specifier if it's supposed to be a class member.
  8747. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  8748. NewFD->setAccess(AS_public);
  8749. // Qualified decls generally require a previous declaration.
  8750. if (D.getCXXScopeSpec().isSet()) {
  8751. // ...with the major exception of templated-scope or
  8752. // dependent-scope friend declarations.
  8753. // TODO: we currently also suppress this check in dependent
  8754. // contexts because (1) the parameter depth will be off when
  8755. // matching friend templates and (2) we might actually be
  8756. // selecting a friend based on a dependent factor. But there
  8757. // are situations where these conditions don't apply and we
  8758. // can actually do this check immediately.
  8759. //
  8760. // Unless the scope is dependent, it's always an error if qualified
  8761. // redeclaration lookup found nothing at all. Diagnose that now;
  8762. // nothing will diagnose that error later.
  8763. if (isFriend &&
  8764. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  8765. (!Previous.empty() && CurContext->isDependentContext()))) {
  8766. // ignore these
  8767. } else if (NewFD->isCPUDispatchMultiVersion() ||
  8768. NewFD->isCPUSpecificMultiVersion()) {
  8769. // ignore this, we allow the redeclaration behavior here to create new
  8770. // versions of the function.
  8771. } else {
  8772. // The user tried to provide an out-of-line definition for a
  8773. // function that is a member of a class or namespace, but there
  8774. // was no such member function declared (C++ [class.mfct]p2,
  8775. // C++ [namespace.memdef]p2). For example:
  8776. //
  8777. // class X {
  8778. // void f() const;
  8779. // };
  8780. //
  8781. // void X::f() { } // ill-formed
  8782. //
  8783. // Complain about this problem, and attempt to suggest close
  8784. // matches (e.g., those that differ only in cv-qualifiers and
  8785. // whether the parameter types are references).
  8786. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8787. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8788. AddToScope = ExtraArgs.AddToScope;
  8789. return Result;
  8790. }
  8791. }
  8792. // Unqualified local friend declarations are required to resolve
  8793. // to something.
  8794. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8795. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8796. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8797. AddToScope = ExtraArgs.AddToScope;
  8798. return Result;
  8799. }
  8800. }
  8801. } else if (!D.isFunctionDefinition() &&
  8802. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8803. !isFriend && !isFunctionTemplateSpecialization &&
  8804. !isMemberSpecialization) {
  8805. // An out-of-line member function declaration must also be a
  8806. // definition (C++ [class.mfct]p2).
  8807. // Note that this is not the case for explicit specializations of
  8808. // function templates or member functions of class templates, per
  8809. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8810. // extension for compatibility with old SWIG code which likes to
  8811. // generate them.
  8812. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8813. << D.getCXXScopeSpec().getRange();
  8814. }
  8815. }
  8816. // If this is the first declaration of a library builtin function, add
  8817. // attributes as appropriate.
  8818. if (!D.isRedeclaration() &&
  8819. NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
  8820. if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
  8821. if (unsigned BuiltinID = II->getBuiltinID()) {
  8822. if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
  8823. // Validate the type matches unless this builtin is specified as
  8824. // matching regardless of its declared type.
  8825. if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
  8826. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  8827. } else {
  8828. ASTContext::GetBuiltinTypeError Error;
  8829. LookupNecessaryTypesForBuiltin(S, BuiltinID);
  8830. QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
  8831. if (!Error && !BuiltinType.isNull() &&
  8832. Context.hasSameFunctionTypeIgnoringExceptionSpec(
  8833. NewFD->getType(), BuiltinType))
  8834. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  8835. }
  8836. } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
  8837. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  8838. // FIXME: We should consider this a builtin only in the std namespace.
  8839. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  8840. }
  8841. }
  8842. }
  8843. }
  8844. ProcessPragmaWeak(S, NewFD);
  8845. checkAttributesAfterMerging(*this, *NewFD);
  8846. AddKnownFunctionAttributes(NewFD);
  8847. if (NewFD->hasAttr<OverloadableAttr>() &&
  8848. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8849. Diag(NewFD->getLocation(),
  8850. diag::err_attribute_overloadable_no_prototype)
  8851. << NewFD;
  8852. // Turn this into a variadic function with no parameters.
  8853. const auto *FT = NewFD->getType()->castAs<FunctionType>();
  8854. FunctionProtoType::ExtProtoInfo EPI(
  8855. Context.getDefaultCallingConvention(true, false));
  8856. EPI.Variadic = true;
  8857. EPI.ExtInfo = FT->getExtInfo();
  8858. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8859. NewFD->setType(R);
  8860. }
  8861. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8862. // member, set the visibility of this function.
  8863. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8864. AddPushedVisibilityAttribute(NewFD);
  8865. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8866. // marking the function.
  8867. AddCFAuditedAttribute(NewFD);
  8868. // If this is a function definition, check if we have to apply optnone due to
  8869. // a pragma.
  8870. if(D.isFunctionDefinition())
  8871. AddRangeBasedOptnone(NewFD);
  8872. // If this is the first declaration of an extern C variable, update
  8873. // the map of such variables.
  8874. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8875. isIncompleteDeclExternC(*this, NewFD))
  8876. RegisterLocallyScopedExternCDecl(NewFD, S);
  8877. // Set this FunctionDecl's range up to the right paren.
  8878. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8879. if (D.isRedeclaration() && !Previous.empty()) {
  8880. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8881. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8882. isMemberSpecialization ||
  8883. isFunctionTemplateSpecialization,
  8884. D.isFunctionDefinition());
  8885. }
  8886. if (getLangOpts().CUDA) {
  8887. IdentifierInfo *II = NewFD->getIdentifier();
  8888. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8889. !NewFD->isInvalidDecl() &&
  8890. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8891. if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
  8892. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8893. << getCudaConfigureFuncName();
  8894. Context.setcudaConfigureCallDecl(NewFD);
  8895. }
  8896. // Variadic functions, other than a *declaration* of printf, are not allowed
  8897. // in device-side CUDA code, unless someone passed
  8898. // -fcuda-allow-variadic-functions.
  8899. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8900. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8901. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8902. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8903. !D.isFunctionDefinition())) {
  8904. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8905. }
  8906. }
  8907. MarkUnusedFileScopedDecl(NewFD);
  8908. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  8909. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8910. if (SC == SC_Static) {
  8911. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8912. D.setInvalidType();
  8913. }
  8914. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8915. if (!NewFD->getReturnType()->isVoidType()) {
  8916. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8917. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8918. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8919. : FixItHint());
  8920. D.setInvalidType();
  8921. }
  8922. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8923. for (auto Param : NewFD->parameters())
  8924. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8925. if (getLangOpts().OpenCLCPlusPlus) {
  8926. if (DC->isRecord()) {
  8927. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  8928. D.setInvalidType();
  8929. }
  8930. if (FunctionTemplate) {
  8931. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  8932. D.setInvalidType();
  8933. }
  8934. }
  8935. }
  8936. if (getLangOpts().CPlusPlus) {
  8937. if (FunctionTemplate) {
  8938. if (NewFD->isInvalidDecl())
  8939. FunctionTemplate->setInvalidDecl();
  8940. return FunctionTemplate;
  8941. }
  8942. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8943. CompleteMemberSpecialization(NewFD, Previous);
  8944. }
  8945. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8946. QualType PT = Param->getType();
  8947. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8948. // types.
  8949. if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
  8950. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8951. QualType ElemTy = PipeTy->getElementType();
  8952. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8953. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8954. D.setInvalidType();
  8955. }
  8956. }
  8957. }
  8958. }
  8959. // Here we have an function template explicit specialization at class scope.
  8960. // The actual specialization will be postponed to template instatiation
  8961. // time via the ClassScopeFunctionSpecializationDecl node.
  8962. if (isDependentClassScopeExplicitSpecialization) {
  8963. ClassScopeFunctionSpecializationDecl *NewSpec =
  8964. ClassScopeFunctionSpecializationDecl::Create(
  8965. Context, CurContext, NewFD->getLocation(),
  8966. cast<CXXMethodDecl>(NewFD),
  8967. HasExplicitTemplateArgs, TemplateArgs);
  8968. CurContext->addDecl(NewSpec);
  8969. AddToScope = false;
  8970. }
  8971. // Diagnose availability attributes. Availability cannot be used on functions
  8972. // that are run during load/unload.
  8973. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8974. if (NewFD->hasAttr<ConstructorAttr>()) {
  8975. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8976. << 1;
  8977. NewFD->dropAttr<AvailabilityAttr>();
  8978. }
  8979. if (NewFD->hasAttr<DestructorAttr>()) {
  8980. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8981. << 2;
  8982. NewFD->dropAttr<AvailabilityAttr>();
  8983. }
  8984. }
  8985. // Diagnose no_builtin attribute on function declaration that are not a
  8986. // definition.
  8987. // FIXME: We should really be doing this in
  8988. // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
  8989. // the FunctionDecl and at this point of the code
  8990. // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
  8991. // because Sema::ActOnStartOfFunctionDef has not been called yet.
  8992. if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
  8993. switch (D.getFunctionDefinitionKind()) {
  8994. case FunctionDefinitionKind::Defaulted:
  8995. case FunctionDefinitionKind::Deleted:
  8996. Diag(NBA->getLocation(),
  8997. diag::err_attribute_no_builtin_on_defaulted_deleted_function)
  8998. << NBA->getSpelling();
  8999. break;
  9000. case FunctionDefinitionKind::Declaration:
  9001. Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
  9002. << NBA->getSpelling();
  9003. break;
  9004. case FunctionDefinitionKind::Definition:
  9005. break;
  9006. }
  9007. return NewFD;
  9008. }
  9009. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  9010. /// when __declspec(code_seg) "is applied to a class, all member functions of
  9011. /// the class and nested classes -- this includes compiler-generated special
  9012. /// member functions -- are put in the specified segment."
  9013. /// The actual behavior is a little more complicated. The Microsoft compiler
  9014. /// won't check outer classes if there is an active value from #pragma code_seg.
  9015. /// The CodeSeg is always applied from the direct parent but only from outer
  9016. /// classes when the #pragma code_seg stack is empty. See:
  9017. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  9018. /// available since MS has removed the page.
  9019. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  9020. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  9021. if (!Method)
  9022. return nullptr;
  9023. const CXXRecordDecl *Parent = Method->getParent();
  9024. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  9025. Attr *NewAttr = SAttr->clone(S.getASTContext());
  9026. NewAttr->setImplicit(true);
  9027. return NewAttr;
  9028. }
  9029. // The Microsoft compiler won't check outer classes for the CodeSeg
  9030. // when the #pragma code_seg stack is active.
  9031. if (S.CodeSegStack.CurrentValue)
  9032. return nullptr;
  9033. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  9034. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  9035. Attr *NewAttr = SAttr->clone(S.getASTContext());
  9036. NewAttr->setImplicit(true);
  9037. return NewAttr;
  9038. }
  9039. }
  9040. return nullptr;
  9041. }
  9042. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  9043. /// containing class. Otherwise it will return implicit SectionAttr if the
  9044. /// function is a definition and there is an active value on CodeSegStack
  9045. /// (from the current #pragma code-seg value).
  9046. ///
  9047. /// \param FD Function being declared.
  9048. /// \param IsDefinition Whether it is a definition or just a declarartion.
  9049. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  9050. /// nullptr if no attribute should be added.
  9051. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  9052. bool IsDefinition) {
  9053. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  9054. return A;
  9055. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  9056. CodeSegStack.CurrentValue)
  9057. return SectionAttr::CreateImplicit(
  9058. getASTContext(), CodeSegStack.CurrentValue->getString(),
  9059. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  9060. SectionAttr::Declspec_allocate);
  9061. return nullptr;
  9062. }
  9063. /// Determines if we can perform a correct type check for \p D as a
  9064. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  9065. /// best-effort check.
  9066. ///
  9067. /// \param NewD The new declaration.
  9068. /// \param OldD The old declaration.
  9069. /// \param NewT The portion of the type of the new declaration to check.
  9070. /// \param OldT The portion of the type of the old declaration to check.
  9071. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  9072. QualType NewT, QualType OldT) {
  9073. if (!NewD->getLexicalDeclContext()->isDependentContext())
  9074. return true;
  9075. // For dependently-typed local extern declarations and friends, we can't
  9076. // perform a correct type check in general until instantiation:
  9077. //
  9078. // int f();
  9079. // template<typename T> void g() { T f(); }
  9080. //
  9081. // (valid if g() is only instantiated with T = int).
  9082. if (NewT->isDependentType() &&
  9083. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  9084. return false;
  9085. // Similarly, if the previous declaration was a dependent local extern
  9086. // declaration, we don't really know its type yet.
  9087. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  9088. return false;
  9089. return true;
  9090. }
  9091. /// Checks if the new declaration declared in dependent context must be
  9092. /// put in the same redeclaration chain as the specified declaration.
  9093. ///
  9094. /// \param D Declaration that is checked.
  9095. /// \param PrevDecl Previous declaration found with proper lookup method for the
  9096. /// same declaration name.
  9097. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  9098. /// belongs to.
  9099. ///
  9100. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  9101. if (!D->getLexicalDeclContext()->isDependentContext())
  9102. return true;
  9103. // Don't chain dependent friend function definitions until instantiation, to
  9104. // permit cases like
  9105. //
  9106. // void func();
  9107. // template<typename T> class C1 { friend void func() {} };
  9108. // template<typename T> class C2 { friend void func() {} };
  9109. //
  9110. // ... which is valid if only one of C1 and C2 is ever instantiated.
  9111. //
  9112. // FIXME: This need only apply to function definitions. For now, we proxy
  9113. // this by checking for a file-scope function. We do not want this to apply
  9114. // to friend declarations nominating member functions, because that gets in
  9115. // the way of access checks.
  9116. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  9117. return false;
  9118. auto *VD = dyn_cast<ValueDecl>(D);
  9119. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  9120. return !VD || !PrevVD ||
  9121. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  9122. PrevVD->getType());
  9123. }
  9124. /// Check the target attribute of the function for MultiVersion
  9125. /// validity.
  9126. ///
  9127. /// Returns true if there was an error, false otherwise.
  9128. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  9129. const auto *TA = FD->getAttr<TargetAttr>();
  9130. assert(TA && "MultiVersion Candidate requires a target attribute");
  9131. ParsedTargetAttr ParseInfo = TA->parse();
  9132. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  9133. enum ErrType { Feature = 0, Architecture = 1 };
  9134. if (!ParseInfo.Architecture.empty() &&
  9135. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  9136. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9137. << Architecture << ParseInfo.Architecture;
  9138. return true;
  9139. }
  9140. for (const auto &Feat : ParseInfo.Features) {
  9141. auto BareFeat = StringRef{Feat}.substr(1);
  9142. if (Feat[0] == '-') {
  9143. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9144. << Feature << ("no-" + BareFeat).str();
  9145. return true;
  9146. }
  9147. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  9148. !TargetInfo.isValidFeatureName(BareFeat)) {
  9149. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9150. << Feature << BareFeat;
  9151. return true;
  9152. }
  9153. }
  9154. return false;
  9155. }
  9156. // Provide a white-list of attributes that are allowed to be combined with
  9157. // multiversion functions.
  9158. static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
  9159. MultiVersionKind MVType) {
  9160. // Note: this list/diagnosis must match the list in
  9161. // checkMultiversionAttributesAllSame.
  9162. switch (Kind) {
  9163. default:
  9164. return false;
  9165. case attr::Used:
  9166. return MVType == MultiVersionKind::Target;
  9167. case attr::NonNull:
  9168. case attr::NoThrow:
  9169. return true;
  9170. }
  9171. }
  9172. static bool checkNonMultiVersionCompatAttributes(Sema &S,
  9173. const FunctionDecl *FD,
  9174. const FunctionDecl *CausedFD,
  9175. MultiVersionKind MVType) {
  9176. const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
  9177. S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
  9178. << static_cast<unsigned>(MVType) << A;
  9179. if (CausedFD)
  9180. S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
  9181. return true;
  9182. };
  9183. for (const Attr *A : FD->attrs()) {
  9184. switch (A->getKind()) {
  9185. case attr::CPUDispatch:
  9186. case attr::CPUSpecific:
  9187. if (MVType != MultiVersionKind::CPUDispatch &&
  9188. MVType != MultiVersionKind::CPUSpecific)
  9189. return Diagnose(S, A);
  9190. break;
  9191. case attr::Target:
  9192. if (MVType != MultiVersionKind::Target)
  9193. return Diagnose(S, A);
  9194. break;
  9195. case attr::TargetClones:
  9196. if (MVType != MultiVersionKind::TargetClones)
  9197. return Diagnose(S, A);
  9198. break;
  9199. default:
  9200. if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
  9201. return Diagnose(S, A);
  9202. break;
  9203. }
  9204. }
  9205. return false;
  9206. }
  9207. bool Sema::areMultiversionVariantFunctionsCompatible(
  9208. const FunctionDecl *OldFD, const FunctionDecl *NewFD,
  9209. const PartialDiagnostic &NoProtoDiagID,
  9210. const PartialDiagnosticAt &NoteCausedDiagIDAt,
  9211. const PartialDiagnosticAt &NoSupportDiagIDAt,
  9212. const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
  9213. bool ConstexprSupported, bool CLinkageMayDiffer) {
  9214. enum DoesntSupport {
  9215. FuncTemplates = 0,
  9216. VirtFuncs = 1,
  9217. DeducedReturn = 2,
  9218. Constructors = 3,
  9219. Destructors = 4,
  9220. DeletedFuncs = 5,
  9221. DefaultedFuncs = 6,
  9222. ConstexprFuncs = 7,
  9223. ConstevalFuncs = 8,
  9224. Lambda = 9,
  9225. };
  9226. enum Different {
  9227. CallingConv = 0,
  9228. ReturnType = 1,
  9229. ConstexprSpec = 2,
  9230. InlineSpec = 3,
  9231. Linkage = 4,
  9232. LanguageLinkage = 5,
  9233. };
  9234. if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
  9235. !OldFD->getType()->getAs<FunctionProtoType>()) {
  9236. Diag(OldFD->getLocation(), NoProtoDiagID);
  9237. Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
  9238. return true;
  9239. }
  9240. if (NoProtoDiagID.getDiagID() != 0 &&
  9241. !NewFD->getType()->getAs<FunctionProtoType>())
  9242. return Diag(NewFD->getLocation(), NoProtoDiagID);
  9243. if (!TemplatesSupported &&
  9244. NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  9245. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9246. << FuncTemplates;
  9247. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  9248. if (NewCXXFD->isVirtual())
  9249. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9250. << VirtFuncs;
  9251. if (isa<CXXConstructorDecl>(NewCXXFD))
  9252. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9253. << Constructors;
  9254. if (isa<CXXDestructorDecl>(NewCXXFD))
  9255. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9256. << Destructors;
  9257. }
  9258. if (NewFD->isDeleted())
  9259. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9260. << DeletedFuncs;
  9261. if (NewFD->isDefaulted())
  9262. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9263. << DefaultedFuncs;
  9264. if (!ConstexprSupported && NewFD->isConstexpr())
  9265. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9266. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  9267. QualType NewQType = Context.getCanonicalType(NewFD->getType());
  9268. const auto *NewType = cast<FunctionType>(NewQType);
  9269. QualType NewReturnType = NewType->getReturnType();
  9270. if (NewReturnType->isUndeducedType())
  9271. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9272. << DeducedReturn;
  9273. // Ensure the return type is identical.
  9274. if (OldFD) {
  9275. QualType OldQType = Context.getCanonicalType(OldFD->getType());
  9276. const auto *OldType = cast<FunctionType>(OldQType);
  9277. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  9278. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  9279. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  9280. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
  9281. QualType OldReturnType = OldType->getReturnType();
  9282. if (OldReturnType != NewReturnType)
  9283. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
  9284. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  9285. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
  9286. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  9287. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
  9288. if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
  9289. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
  9290. if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
  9291. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
  9292. if (CheckEquivalentExceptionSpec(
  9293. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  9294. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  9295. return true;
  9296. }
  9297. return false;
  9298. }
  9299. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  9300. const FunctionDecl *NewFD,
  9301. bool CausesMV,
  9302. MultiVersionKind MVType) {
  9303. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  9304. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  9305. if (OldFD)
  9306. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9307. return true;
  9308. }
  9309. bool IsCPUSpecificCPUDispatchMVType =
  9310. MVType == MultiVersionKind::CPUDispatch ||
  9311. MVType == MultiVersionKind::CPUSpecific;
  9312. if (CausesMV && OldFD &&
  9313. checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
  9314. return true;
  9315. if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
  9316. return true;
  9317. // Only allow transition to MultiVersion if it hasn't been used.
  9318. if (OldFD && CausesMV && OldFD->isUsed(false))
  9319. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  9320. return S.areMultiversionVariantFunctionsCompatible(
  9321. OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
  9322. PartialDiagnosticAt(NewFD->getLocation(),
  9323. S.PDiag(diag::note_multiversioning_caused_here)),
  9324. PartialDiagnosticAt(NewFD->getLocation(),
  9325. S.PDiag(diag::err_multiversion_doesnt_support)
  9326. << static_cast<unsigned>(MVType)),
  9327. PartialDiagnosticAt(NewFD->getLocation(),
  9328. S.PDiag(diag::err_multiversion_diff)),
  9329. /*TemplatesSupported=*/false,
  9330. /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
  9331. /*CLinkageMayDiffer=*/false);
  9332. }
  9333. /// Check the validity of a multiversion function declaration that is the
  9334. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  9335. ///
  9336. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9337. ///
  9338. /// Returns true if there was an error, false otherwise.
  9339. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  9340. MultiVersionKind MVType,
  9341. const TargetAttr *TA) {
  9342. assert(MVType != MultiVersionKind::None &&
  9343. "Function lacks multiversion attribute");
  9344. // Target only causes MV if it is default, otherwise this is a normal
  9345. // function.
  9346. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  9347. return false;
  9348. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  9349. FD->setInvalidDecl();
  9350. return true;
  9351. }
  9352. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  9353. FD->setInvalidDecl();
  9354. return true;
  9355. }
  9356. FD->setIsMultiVersion();
  9357. return false;
  9358. }
  9359. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  9360. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  9361. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  9362. return true;
  9363. }
  9364. return false;
  9365. }
  9366. static bool CheckTargetCausesMultiVersioning(
  9367. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  9368. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  9369. LookupResult &Previous) {
  9370. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  9371. ParsedTargetAttr NewParsed = NewTA->parse();
  9372. // Sort order doesn't matter, it just needs to be consistent.
  9373. llvm::sort(NewParsed.Features);
  9374. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  9375. // to change, this is a simple redeclaration.
  9376. if (!NewTA->isDefaultVersion() &&
  9377. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  9378. return false;
  9379. // Otherwise, this decl causes MultiVersioning.
  9380. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  9381. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  9382. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9383. NewFD->setInvalidDecl();
  9384. return true;
  9385. }
  9386. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  9387. MultiVersionKind::Target)) {
  9388. NewFD->setInvalidDecl();
  9389. return true;
  9390. }
  9391. if (CheckMultiVersionValue(S, NewFD)) {
  9392. NewFD->setInvalidDecl();
  9393. return true;
  9394. }
  9395. // If this is 'default', permit the forward declaration.
  9396. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  9397. Redeclaration = true;
  9398. OldDecl = OldFD;
  9399. OldFD->setIsMultiVersion();
  9400. NewFD->setIsMultiVersion();
  9401. return false;
  9402. }
  9403. if (CheckMultiVersionValue(S, OldFD)) {
  9404. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  9405. NewFD->setInvalidDecl();
  9406. return true;
  9407. }
  9408. ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
  9409. if (OldParsed == NewParsed) {
  9410. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  9411. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9412. NewFD->setInvalidDecl();
  9413. return true;
  9414. }
  9415. for (const auto *FD : OldFD->redecls()) {
  9416. const auto *CurTA = FD->getAttr<TargetAttr>();
  9417. // We allow forward declarations before ANY multiversioning attributes, but
  9418. // nothing after the fact.
  9419. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  9420. (!CurTA || CurTA->isInherited())) {
  9421. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  9422. << 0;
  9423. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  9424. NewFD->setInvalidDecl();
  9425. return true;
  9426. }
  9427. }
  9428. OldFD->setIsMultiVersion();
  9429. NewFD->setIsMultiVersion();
  9430. Redeclaration = false;
  9431. MergeTypeWithPrevious = false;
  9432. OldDecl = nullptr;
  9433. Previous.clear();
  9434. return false;
  9435. }
  9436. static bool MultiVersionTypesCompatible(MultiVersionKind Old,
  9437. MultiVersionKind New) {
  9438. if (Old == New || Old == MultiVersionKind::None ||
  9439. New == MultiVersionKind::None)
  9440. return true;
  9441. return (Old == MultiVersionKind::CPUDispatch &&
  9442. New == MultiVersionKind::CPUSpecific) ||
  9443. (Old == MultiVersionKind::CPUSpecific &&
  9444. New == MultiVersionKind::CPUDispatch);
  9445. }
  9446. /// Check the validity of a new function declaration being added to an existing
  9447. /// multiversioned declaration collection.
  9448. static bool CheckMultiVersionAdditionalDecl(
  9449. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  9450. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  9451. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  9452. const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
  9453. bool &MergeTypeWithPrevious, LookupResult &Previous) {
  9454. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  9455. // Disallow mixing of multiversioning types.
  9456. if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
  9457. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  9458. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9459. NewFD->setInvalidDecl();
  9460. return true;
  9461. }
  9462. ParsedTargetAttr NewParsed;
  9463. if (NewTA) {
  9464. NewParsed = NewTA->parse();
  9465. llvm::sort(NewParsed.Features);
  9466. }
  9467. bool UseMemberUsingDeclRules =
  9468. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  9469. // Next, check ALL non-overloads to see if this is a redeclaration of a
  9470. // previous member of the MultiVersion set.
  9471. for (NamedDecl *ND : Previous) {
  9472. FunctionDecl *CurFD = ND->getAsFunction();
  9473. if (!CurFD)
  9474. continue;
  9475. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  9476. continue;
  9477. switch (NewMVType) {
  9478. case MultiVersionKind::None:
  9479. assert(OldMVType == MultiVersionKind::TargetClones &&
  9480. "Only target_clones can be omitted in subsequent declarations");
  9481. break;
  9482. case MultiVersionKind::Target: {
  9483. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  9484. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  9485. NewFD->setIsMultiVersion();
  9486. Redeclaration = true;
  9487. OldDecl = ND;
  9488. return false;
  9489. }
  9490. ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
  9491. if (CurParsed == NewParsed) {
  9492. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  9493. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  9494. NewFD->setInvalidDecl();
  9495. return true;
  9496. }
  9497. break;
  9498. }
  9499. case MultiVersionKind::TargetClones: {
  9500. const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
  9501. Redeclaration = true;
  9502. OldDecl = CurFD;
  9503. MergeTypeWithPrevious = true;
  9504. NewFD->setIsMultiVersion();
  9505. if (CurClones && NewClones &&
  9506. (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
  9507. !std::equal(CurClones->featuresStrs_begin(),
  9508. CurClones->featuresStrs_end(),
  9509. NewClones->featuresStrs_begin()))) {
  9510. S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
  9511. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  9512. NewFD->setInvalidDecl();
  9513. return true;
  9514. }
  9515. return false;
  9516. }
  9517. case MultiVersionKind::CPUSpecific:
  9518. case MultiVersionKind::CPUDispatch: {
  9519. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  9520. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  9521. // Handle CPUDispatch/CPUSpecific versions.
  9522. // Only 1 CPUDispatch function is allowed, this will make it go through
  9523. // the redeclaration errors.
  9524. if (NewMVType == MultiVersionKind::CPUDispatch &&
  9525. CurFD->hasAttr<CPUDispatchAttr>()) {
  9526. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  9527. std::equal(
  9528. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  9529. NewCPUDisp->cpus_begin(),
  9530. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  9531. return Cur->getName() == New->getName();
  9532. })) {
  9533. NewFD->setIsMultiVersion();
  9534. Redeclaration = true;
  9535. OldDecl = ND;
  9536. return false;
  9537. }
  9538. // If the declarations don't match, this is an error condition.
  9539. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  9540. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  9541. NewFD->setInvalidDecl();
  9542. return true;
  9543. }
  9544. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  9545. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  9546. std::equal(
  9547. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  9548. NewCPUSpec->cpus_begin(),
  9549. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  9550. return Cur->getName() == New->getName();
  9551. })) {
  9552. NewFD->setIsMultiVersion();
  9553. Redeclaration = true;
  9554. OldDecl = ND;
  9555. return false;
  9556. }
  9557. // Only 1 version of CPUSpecific is allowed for each CPU.
  9558. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  9559. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  9560. if (CurII == NewII) {
  9561. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  9562. << NewII;
  9563. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  9564. NewFD->setInvalidDecl();
  9565. return true;
  9566. }
  9567. }
  9568. }
  9569. }
  9570. break;
  9571. }
  9572. }
  9573. }
  9574. // Else, this is simply a non-redecl case. Checking the 'value' is only
  9575. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  9576. // handled in the attribute adding step.
  9577. if (NewMVType == MultiVersionKind::Target &&
  9578. CheckMultiVersionValue(S, NewFD)) {
  9579. NewFD->setInvalidDecl();
  9580. return true;
  9581. }
  9582. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  9583. !OldFD->isMultiVersion(), NewMVType)) {
  9584. NewFD->setInvalidDecl();
  9585. return true;
  9586. }
  9587. // Permit forward declarations in the case where these two are compatible.
  9588. if (!OldFD->isMultiVersion()) {
  9589. OldFD->setIsMultiVersion();
  9590. NewFD->setIsMultiVersion();
  9591. Redeclaration = true;
  9592. OldDecl = OldFD;
  9593. return false;
  9594. }
  9595. NewFD->setIsMultiVersion();
  9596. Redeclaration = false;
  9597. MergeTypeWithPrevious = false;
  9598. OldDecl = nullptr;
  9599. Previous.clear();
  9600. return false;
  9601. }
  9602. /// Check the validity of a mulitversion function declaration.
  9603. /// Also sets the multiversion'ness' of the function itself.
  9604. ///
  9605. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9606. ///
  9607. /// Returns true if there was an error, false otherwise.
  9608. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  9609. bool &Redeclaration, NamedDecl *&OldDecl,
  9610. bool &MergeTypeWithPrevious,
  9611. LookupResult &Previous) {
  9612. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  9613. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  9614. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  9615. const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
  9616. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  9617. // Main isn't allowed to become a multiversion function, however it IS
  9618. // permitted to have 'main' be marked with the 'target' optimization hint.
  9619. if (NewFD->isMain()) {
  9620. if (MVType != MultiVersionKind::None &&
  9621. !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
  9622. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  9623. NewFD->setInvalidDecl();
  9624. return true;
  9625. }
  9626. return false;
  9627. }
  9628. if (!OldDecl || !OldDecl->getAsFunction() ||
  9629. OldDecl->getDeclContext()->getRedeclContext() !=
  9630. NewFD->getDeclContext()->getRedeclContext()) {
  9631. // If there's no previous declaration, AND this isn't attempting to cause
  9632. // multiversioning, this isn't an error condition.
  9633. if (MVType == MultiVersionKind::None)
  9634. return false;
  9635. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
  9636. }
  9637. FunctionDecl *OldFD = OldDecl->getAsFunction();
  9638. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  9639. return false;
  9640. // Multiversioned redeclarations aren't allowed to omit the attribute, except
  9641. // for target_clones.
  9642. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
  9643. OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
  9644. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  9645. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  9646. NewFD->setInvalidDecl();
  9647. return true;
  9648. }
  9649. if (!OldFD->isMultiVersion()) {
  9650. switch (MVType) {
  9651. case MultiVersionKind::Target:
  9652. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  9653. Redeclaration, OldDecl,
  9654. MergeTypeWithPrevious, Previous);
  9655. case MultiVersionKind::TargetClones:
  9656. if (OldFD->isUsed(false)) {
  9657. NewFD->setInvalidDecl();
  9658. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  9659. }
  9660. OldFD->setIsMultiVersion();
  9661. break;
  9662. case MultiVersionKind::CPUDispatch:
  9663. case MultiVersionKind::CPUSpecific:
  9664. case MultiVersionKind::None:
  9665. break;
  9666. }
  9667. }
  9668. // Handle the target potentially causes multiversioning case.
  9669. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  9670. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  9671. Redeclaration, OldDecl,
  9672. MergeTypeWithPrevious, Previous);
  9673. // At this point, we have a multiversion function decl (in OldFD) AND an
  9674. // appropriate attribute in the current function decl. Resolve that these are
  9675. // still compatible with previous declarations.
  9676. return CheckMultiVersionAdditionalDecl(
  9677. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
  9678. Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
  9679. }
  9680. /// Perform semantic checking of a new function declaration.
  9681. ///
  9682. /// Performs semantic analysis of the new function declaration
  9683. /// NewFD. This routine performs all semantic checking that does not
  9684. /// require the actual declarator involved in the declaration, and is
  9685. /// used both for the declaration of functions as they are parsed
  9686. /// (called via ActOnDeclarator) and for the declaration of functions
  9687. /// that have been instantiated via C++ template instantiation (called
  9688. /// via InstantiateDecl).
  9689. ///
  9690. /// \param IsMemberSpecialization whether this new function declaration is
  9691. /// a member specialization (that replaces any definition provided by the
  9692. /// previous declaration).
  9693. ///
  9694. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9695. ///
  9696. /// \returns true if the function declaration is a redeclaration.
  9697. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  9698. LookupResult &Previous,
  9699. bool IsMemberSpecialization) {
  9700. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  9701. "Variably modified return types are not handled here");
  9702. // Determine whether the type of this function should be merged with
  9703. // a previous visible declaration. This never happens for functions in C++,
  9704. // and always happens in C if the previous declaration was visible.
  9705. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  9706. !Previous.isShadowed();
  9707. bool Redeclaration = false;
  9708. NamedDecl *OldDecl = nullptr;
  9709. bool MayNeedOverloadableChecks = false;
  9710. // Merge or overload the declaration with an existing declaration of
  9711. // the same name, if appropriate.
  9712. if (!Previous.empty()) {
  9713. // Determine whether NewFD is an overload of PrevDecl or
  9714. // a declaration that requires merging. If it's an overload,
  9715. // there's no more work to do here; we'll just add the new
  9716. // function to the scope.
  9717. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  9718. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  9719. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  9720. Redeclaration = true;
  9721. OldDecl = Candidate;
  9722. }
  9723. } else {
  9724. MayNeedOverloadableChecks = true;
  9725. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  9726. /*NewIsUsingDecl*/ false)) {
  9727. case Ovl_Match:
  9728. Redeclaration = true;
  9729. break;
  9730. case Ovl_NonFunction:
  9731. Redeclaration = true;
  9732. break;
  9733. case Ovl_Overload:
  9734. Redeclaration = false;
  9735. break;
  9736. }
  9737. }
  9738. }
  9739. // Check for a previous extern "C" declaration with this name.
  9740. if (!Redeclaration &&
  9741. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  9742. if (!Previous.empty()) {
  9743. // This is an extern "C" declaration with the same name as a previous
  9744. // declaration, and thus redeclares that entity...
  9745. Redeclaration = true;
  9746. OldDecl = Previous.getFoundDecl();
  9747. MergeTypeWithPrevious = false;
  9748. // ... except in the presence of __attribute__((overloadable)).
  9749. if (OldDecl->hasAttr<OverloadableAttr>() ||
  9750. NewFD->hasAttr<OverloadableAttr>()) {
  9751. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  9752. MayNeedOverloadableChecks = true;
  9753. Redeclaration = false;
  9754. OldDecl = nullptr;
  9755. }
  9756. }
  9757. }
  9758. }
  9759. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  9760. MergeTypeWithPrevious, Previous))
  9761. return Redeclaration;
  9762. // PPC MMA non-pointer types are not allowed as function return types.
  9763. if (Context.getTargetInfo().getTriple().isPPC64() &&
  9764. CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
  9765. NewFD->setInvalidDecl();
  9766. }
  9767. // C++11 [dcl.constexpr]p8:
  9768. // A constexpr specifier for a non-static member function that is not
  9769. // a constructor declares that member function to be const.
  9770. //
  9771. // This needs to be delayed until we know whether this is an out-of-line
  9772. // definition of a static member function.
  9773. //
  9774. // This rule is not present in C++1y, so we produce a backwards
  9775. // compatibility warning whenever it happens in C++11.
  9776. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  9777. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  9778. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  9779. !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
  9780. CXXMethodDecl *OldMD = nullptr;
  9781. if (OldDecl)
  9782. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  9783. if (!OldMD || !OldMD->isStatic()) {
  9784. const FunctionProtoType *FPT =
  9785. MD->getType()->castAs<FunctionProtoType>();
  9786. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9787. EPI.TypeQuals.addConst();
  9788. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  9789. FPT->getParamTypes(), EPI));
  9790. // Warn that we did this, if we're not performing template instantiation.
  9791. // In that case, we'll have warned already when the template was defined.
  9792. if (!inTemplateInstantiation()) {
  9793. SourceLocation AddConstLoc;
  9794. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  9795. .IgnoreParens().getAs<FunctionTypeLoc>())
  9796. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  9797. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  9798. << FixItHint::CreateInsertion(AddConstLoc, " const");
  9799. }
  9800. }
  9801. }
  9802. if (Redeclaration) {
  9803. // NewFD and OldDecl represent declarations that need to be
  9804. // merged.
  9805. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  9806. NewFD->setInvalidDecl();
  9807. return Redeclaration;
  9808. }
  9809. Previous.clear();
  9810. Previous.addDecl(OldDecl);
  9811. if (FunctionTemplateDecl *OldTemplateDecl =
  9812. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  9813. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  9814. FunctionTemplateDecl *NewTemplateDecl
  9815. = NewFD->getDescribedFunctionTemplate();
  9816. assert(NewTemplateDecl && "Template/non-template mismatch");
  9817. // The call to MergeFunctionDecl above may have created some state in
  9818. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  9819. // can add it as a redeclaration.
  9820. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  9821. NewFD->setPreviousDeclaration(OldFD);
  9822. if (NewFD->isCXXClassMember()) {
  9823. NewFD->setAccess(OldTemplateDecl->getAccess());
  9824. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  9825. }
  9826. // If this is an explicit specialization of a member that is a function
  9827. // template, mark it as a member specialization.
  9828. if (IsMemberSpecialization &&
  9829. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  9830. NewTemplateDecl->setMemberSpecialization();
  9831. assert(OldTemplateDecl->isMemberSpecialization());
  9832. // Explicit specializations of a member template do not inherit deleted
  9833. // status from the parent member template that they are specializing.
  9834. if (OldFD->isDeleted()) {
  9835. // FIXME: This assert will not hold in the presence of modules.
  9836. assert(OldFD->getCanonicalDecl() == OldFD);
  9837. // FIXME: We need an update record for this AST mutation.
  9838. OldFD->setDeletedAsWritten(false);
  9839. }
  9840. }
  9841. } else {
  9842. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  9843. auto *OldFD = cast<FunctionDecl>(OldDecl);
  9844. // This needs to happen first so that 'inline' propagates.
  9845. NewFD->setPreviousDeclaration(OldFD);
  9846. if (NewFD->isCXXClassMember())
  9847. NewFD->setAccess(OldFD->getAccess());
  9848. }
  9849. }
  9850. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  9851. !NewFD->getAttr<OverloadableAttr>()) {
  9852. assert((Previous.empty() ||
  9853. llvm::any_of(Previous,
  9854. [](const NamedDecl *ND) {
  9855. return ND->hasAttr<OverloadableAttr>();
  9856. })) &&
  9857. "Non-redecls shouldn't happen without overloadable present");
  9858. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  9859. const auto *FD = dyn_cast<FunctionDecl>(ND);
  9860. return FD && !FD->hasAttr<OverloadableAttr>();
  9861. });
  9862. if (OtherUnmarkedIter != Previous.end()) {
  9863. Diag(NewFD->getLocation(),
  9864. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  9865. Diag((*OtherUnmarkedIter)->getLocation(),
  9866. diag::note_attribute_overloadable_prev_overload)
  9867. << false;
  9868. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  9869. }
  9870. }
  9871. if (LangOpts.OpenMP)
  9872. ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
  9873. // Semantic checking for this function declaration (in isolation).
  9874. if (getLangOpts().CPlusPlus) {
  9875. // C++-specific checks.
  9876. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  9877. CheckConstructor(Constructor);
  9878. } else if (CXXDestructorDecl *Destructor =
  9879. dyn_cast<CXXDestructorDecl>(NewFD)) {
  9880. CXXRecordDecl *Record = Destructor->getParent();
  9881. QualType ClassType = Context.getTypeDeclType(Record);
  9882. // FIXME: Shouldn't we be able to perform this check even when the class
  9883. // type is dependent? Both gcc and edg can handle that.
  9884. if (!ClassType->isDependentType()) {
  9885. DeclarationName Name
  9886. = Context.DeclarationNames.getCXXDestructorName(
  9887. Context.getCanonicalType(ClassType));
  9888. if (NewFD->getDeclName() != Name) {
  9889. Diag(NewFD->getLocation(), diag::err_destructor_name);
  9890. NewFD->setInvalidDecl();
  9891. return Redeclaration;
  9892. }
  9893. }
  9894. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  9895. if (auto *TD = Guide->getDescribedFunctionTemplate())
  9896. CheckDeductionGuideTemplate(TD);
  9897. // A deduction guide is not on the list of entities that can be
  9898. // explicitly specialized.
  9899. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  9900. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  9901. << /*explicit specialization*/ 1;
  9902. }
  9903. // Find any virtual functions that this function overrides.
  9904. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  9905. if (!Method->isFunctionTemplateSpecialization() &&
  9906. !Method->getDescribedFunctionTemplate() &&
  9907. Method->isCanonicalDecl()) {
  9908. AddOverriddenMethods(Method->getParent(), Method);
  9909. }
  9910. if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
  9911. // C++2a [class.virtual]p6
  9912. // A virtual method shall not have a requires-clause.
  9913. Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
  9914. diag::err_constrained_virtual_method);
  9915. if (Method->isStatic())
  9916. checkThisInStaticMemberFunctionType(Method);
  9917. }
  9918. if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
  9919. ActOnConversionDeclarator(Conversion);
  9920. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9921. if (NewFD->isOverloadedOperator() &&
  9922. CheckOverloadedOperatorDeclaration(NewFD)) {
  9923. NewFD->setInvalidDecl();
  9924. return Redeclaration;
  9925. }
  9926. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9927. if (NewFD->getLiteralIdentifier() &&
  9928. CheckLiteralOperatorDeclaration(NewFD)) {
  9929. NewFD->setInvalidDecl();
  9930. return Redeclaration;
  9931. }
  9932. // In C++, check default arguments now that we have merged decls. Unless
  9933. // the lexical context is the class, because in this case this is done
  9934. // during delayed parsing anyway.
  9935. if (!CurContext->isRecord())
  9936. CheckCXXDefaultArguments(NewFD);
  9937. // If this function is declared as being extern "C", then check to see if
  9938. // the function returns a UDT (class, struct, or union type) that is not C
  9939. // compatible, and if it does, warn the user.
  9940. // But, issue any diagnostic on the first declaration only.
  9941. if (Previous.empty() && NewFD->isExternC()) {
  9942. QualType R = NewFD->getReturnType();
  9943. if (R->isIncompleteType() && !R->isVoidType())
  9944. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9945. << NewFD << R;
  9946. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9947. !R->isObjCObjectPointerType())
  9948. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9949. }
  9950. // C++1z [dcl.fct]p6:
  9951. // [...] whether the function has a non-throwing exception-specification
  9952. // [is] part of the function type
  9953. //
  9954. // This results in an ABI break between C++14 and C++17 for functions whose
  9955. // declared type includes an exception-specification in a parameter or
  9956. // return type. (Exception specifications on the function itself are OK in
  9957. // most cases, and exception specifications are not permitted in most other
  9958. // contexts where they could make it into a mangling.)
  9959. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9960. auto HasNoexcept = [&](QualType T) -> bool {
  9961. // Strip off declarator chunks that could be between us and a function
  9962. // type. We don't need to look far, exception specifications are very
  9963. // restricted prior to C++17.
  9964. if (auto *RT = T->getAs<ReferenceType>())
  9965. T = RT->getPointeeType();
  9966. else if (T->isAnyPointerType())
  9967. T = T->getPointeeType();
  9968. else if (auto *MPT = T->getAs<MemberPointerType>())
  9969. T = MPT->getPointeeType();
  9970. if (auto *FPT = T->getAs<FunctionProtoType>())
  9971. if (FPT->isNothrow())
  9972. return true;
  9973. return false;
  9974. };
  9975. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9976. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9977. for (QualType T : FPT->param_types())
  9978. AnyNoexcept |= HasNoexcept(T);
  9979. if (AnyNoexcept)
  9980. Diag(NewFD->getLocation(),
  9981. diag::warn_cxx17_compat_exception_spec_in_signature)
  9982. << NewFD;
  9983. }
  9984. if (!Redeclaration && LangOpts.CUDA)
  9985. checkCUDATargetOverload(NewFD, Previous);
  9986. }
  9987. return Redeclaration;
  9988. }
  9989. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9990. // C++11 [basic.start.main]p3:
  9991. // A program that [...] declares main to be inline, static or
  9992. // constexpr is ill-formed.
  9993. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9994. // appear in a declaration of main.
  9995. // static main is not an error under C99, but we should warn about it.
  9996. // We accept _Noreturn main as an extension.
  9997. if (FD->getStorageClass() == SC_Static)
  9998. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9999. ? diag::err_static_main : diag::warn_static_main)
  10000. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10001. if (FD->isInlineSpecified())
  10002. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  10003. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  10004. if (DS.isNoreturnSpecified()) {
  10005. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  10006. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  10007. Diag(NoreturnLoc, diag::ext_noreturn_main);
  10008. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  10009. << FixItHint::CreateRemoval(NoreturnRange);
  10010. }
  10011. if (FD->isConstexpr()) {
  10012. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  10013. << FD->isConsteval()
  10014. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  10015. FD->setConstexprKind(ConstexprSpecKind::Unspecified);
  10016. }
  10017. if (getLangOpts().OpenCL) {
  10018. Diag(FD->getLocation(), diag::err_opencl_no_main)
  10019. << FD->hasAttr<OpenCLKernelAttr>();
  10020. FD->setInvalidDecl();
  10021. return;
  10022. }
  10023. QualType T = FD->getType();
  10024. assert(T->isFunctionType() && "function decl is not of function type");
  10025. const FunctionType* FT = T->castAs<FunctionType>();
  10026. // Set default calling convention for main()
  10027. if (FT->getCallConv() != CC_C) {
  10028. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  10029. FD->setType(QualType(FT, 0));
  10030. T = Context.getCanonicalType(FD->getType());
  10031. }
  10032. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  10033. // In C with GNU extensions we allow main() to have non-integer return
  10034. // type, but we should warn about the extension, and we disable the
  10035. // implicit-return-zero rule.
  10036. // GCC in C mode accepts qualified 'int'.
  10037. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  10038. FD->setHasImplicitReturnZero(true);
  10039. else {
  10040. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  10041. SourceRange RTRange = FD->getReturnTypeSourceRange();
  10042. if (RTRange.isValid())
  10043. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  10044. << FixItHint::CreateReplacement(RTRange, "int");
  10045. }
  10046. } else {
  10047. // In C and C++, main magically returns 0 if you fall off the end;
  10048. // set the flag which tells us that.
  10049. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  10050. // All the standards say that main() should return 'int'.
  10051. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  10052. FD->setHasImplicitReturnZero(true);
  10053. else {
  10054. // Otherwise, this is just a flat-out error.
  10055. SourceRange RTRange = FD->getReturnTypeSourceRange();
  10056. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  10057. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  10058. : FixItHint());
  10059. FD->setInvalidDecl(true);
  10060. }
  10061. }
  10062. // Treat protoless main() as nullary.
  10063. if (isa<FunctionNoProtoType>(FT)) return;
  10064. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  10065. unsigned nparams = FTP->getNumParams();
  10066. assert(FD->getNumParams() == nparams);
  10067. bool HasExtraParameters = (nparams > 3);
  10068. if (FTP->isVariadic()) {
  10069. Diag(FD->getLocation(), diag::ext_variadic_main);
  10070. // FIXME: if we had information about the location of the ellipsis, we
  10071. // could add a FixIt hint to remove it as a parameter.
  10072. }
  10073. // Darwin passes an undocumented fourth argument of type char**. If
  10074. // other platforms start sprouting these, the logic below will start
  10075. // getting shifty.
  10076. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  10077. HasExtraParameters = false;
  10078. if (HasExtraParameters) {
  10079. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  10080. FD->setInvalidDecl(true);
  10081. nparams = 3;
  10082. }
  10083. // FIXME: a lot of the following diagnostics would be improved
  10084. // if we had some location information about types.
  10085. QualType CharPP =
  10086. Context.getPointerType(Context.getPointerType(Context.CharTy));
  10087. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  10088. for (unsigned i = 0; i < nparams; ++i) {
  10089. QualType AT = FTP->getParamType(i);
  10090. bool mismatch = true;
  10091. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  10092. mismatch = false;
  10093. else if (Expected[i] == CharPP) {
  10094. // As an extension, the following forms are okay:
  10095. // char const **
  10096. // char const * const *
  10097. // char * const *
  10098. QualifierCollector qs;
  10099. const PointerType* PT;
  10100. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  10101. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  10102. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  10103. Context.CharTy)) {
  10104. qs.removeConst();
  10105. mismatch = !qs.empty();
  10106. }
  10107. }
  10108. if (mismatch) {
  10109. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  10110. // TODO: suggest replacing given type with expected type
  10111. FD->setInvalidDecl(true);
  10112. }
  10113. }
  10114. if (nparams == 1 && !FD->isInvalidDecl()) {
  10115. Diag(FD->getLocation(), diag::warn_main_one_arg);
  10116. }
  10117. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  10118. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  10119. FD->setInvalidDecl();
  10120. }
  10121. }
  10122. static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
  10123. // Default calling convention for main and wmain is __cdecl
  10124. if (FD->getName() == "main" || FD->getName() == "wmain")
  10125. return false;
  10126. // Default calling convention for MinGW is __cdecl
  10127. const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
  10128. if (T.isWindowsGNUEnvironment())
  10129. return false;
  10130. // Default calling convention for WinMain, wWinMain and DllMain
  10131. // is __stdcall on 32 bit Windows
  10132. if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
  10133. return true;
  10134. return false;
  10135. }
  10136. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  10137. QualType T = FD->getType();
  10138. assert(T->isFunctionType() && "function decl is not of function type");
  10139. const FunctionType *FT = T->castAs<FunctionType>();
  10140. // Set an implicit return of 'zero' if the function can return some integral,
  10141. // enumeration, pointer or nullptr type.
  10142. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  10143. FT->getReturnType()->isAnyPointerType() ||
  10144. FT->getReturnType()->isNullPtrType())
  10145. // DllMain is exempt because a return value of zero means it failed.
  10146. if (FD->getName() != "DllMain")
  10147. FD->setHasImplicitReturnZero(true);
  10148. // Explicity specified calling conventions are applied to MSVC entry points
  10149. if (!hasExplicitCallingConv(T)) {
  10150. if (isDefaultStdCall(FD, *this)) {
  10151. if (FT->getCallConv() != CC_X86StdCall) {
  10152. FT = Context.adjustFunctionType(
  10153. FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
  10154. FD->setType(QualType(FT, 0));
  10155. }
  10156. } else if (FT->getCallConv() != CC_C) {
  10157. FT = Context.adjustFunctionType(FT,
  10158. FT->getExtInfo().withCallingConv(CC_C));
  10159. FD->setType(QualType(FT, 0));
  10160. }
  10161. }
  10162. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  10163. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  10164. FD->setInvalidDecl();
  10165. }
  10166. }
  10167. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  10168. // FIXME: Need strict checking. In C89, we need to check for
  10169. // any assignment, increment, decrement, function-calls, or
  10170. // commas outside of a sizeof. In C99, it's the same list,
  10171. // except that the aforementioned are allowed in unevaluated
  10172. // expressions. Everything else falls under the
  10173. // "may accept other forms of constant expressions" exception.
  10174. //
  10175. // Regular C++ code will not end up here (exceptions: language extensions,
  10176. // OpenCL C++ etc), so the constant expression rules there don't matter.
  10177. if (Init->isValueDependent()) {
  10178. assert(Init->containsErrors() &&
  10179. "Dependent code should only occur in error-recovery path.");
  10180. return true;
  10181. }
  10182. const Expr *Culprit;
  10183. if (Init->isConstantInitializer(Context, false, &Culprit))
  10184. return false;
  10185. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  10186. << Culprit->getSourceRange();
  10187. return true;
  10188. }
  10189. namespace {
  10190. // Visits an initialization expression to see if OrigDecl is evaluated in
  10191. // its own initialization and throws a warning if it does.
  10192. class SelfReferenceChecker
  10193. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  10194. Sema &S;
  10195. Decl *OrigDecl;
  10196. bool isRecordType;
  10197. bool isPODType;
  10198. bool isReferenceType;
  10199. bool isInitList;
  10200. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  10201. public:
  10202. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  10203. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  10204. S(S), OrigDecl(OrigDecl) {
  10205. isPODType = false;
  10206. isRecordType = false;
  10207. isReferenceType = false;
  10208. isInitList = false;
  10209. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  10210. isPODType = VD->getType().isPODType(S.Context);
  10211. isRecordType = VD->getType()->isRecordType();
  10212. isReferenceType = VD->getType()->isReferenceType();
  10213. }
  10214. }
  10215. // For most expressions, just call the visitor. For initializer lists,
  10216. // track the index of the field being initialized since fields are
  10217. // initialized in order allowing use of previously initialized fields.
  10218. void CheckExpr(Expr *E) {
  10219. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  10220. if (!InitList) {
  10221. Visit(E);
  10222. return;
  10223. }
  10224. // Track and increment the index here.
  10225. isInitList = true;
  10226. InitFieldIndex.push_back(0);
  10227. for (auto Child : InitList->children()) {
  10228. CheckExpr(cast<Expr>(Child));
  10229. ++InitFieldIndex.back();
  10230. }
  10231. InitFieldIndex.pop_back();
  10232. }
  10233. // Returns true if MemberExpr is checked and no further checking is needed.
  10234. // Returns false if additional checking is required.
  10235. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  10236. llvm::SmallVector<FieldDecl*, 4> Fields;
  10237. Expr *Base = E;
  10238. bool ReferenceField = false;
  10239. // Get the field members used.
  10240. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  10241. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  10242. if (!FD)
  10243. return false;
  10244. Fields.push_back(FD);
  10245. if (FD->getType()->isReferenceType())
  10246. ReferenceField = true;
  10247. Base = ME->getBase()->IgnoreParenImpCasts();
  10248. }
  10249. // Keep checking only if the base Decl is the same.
  10250. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  10251. if (!DRE || DRE->getDecl() != OrigDecl)
  10252. return false;
  10253. // A reference field can be bound to an unininitialized field.
  10254. if (CheckReference && !ReferenceField)
  10255. return true;
  10256. // Convert FieldDecls to their index number.
  10257. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  10258. for (const FieldDecl *I : llvm::reverse(Fields))
  10259. UsedFieldIndex.push_back(I->getFieldIndex());
  10260. // See if a warning is needed by checking the first difference in index
  10261. // numbers. If field being used has index less than the field being
  10262. // initialized, then the use is safe.
  10263. for (auto UsedIter = UsedFieldIndex.begin(),
  10264. UsedEnd = UsedFieldIndex.end(),
  10265. OrigIter = InitFieldIndex.begin(),
  10266. OrigEnd = InitFieldIndex.end();
  10267. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  10268. if (*UsedIter < *OrigIter)
  10269. return true;
  10270. if (*UsedIter > *OrigIter)
  10271. break;
  10272. }
  10273. // TODO: Add a different warning which will print the field names.
  10274. HandleDeclRefExpr(DRE);
  10275. return true;
  10276. }
  10277. // For most expressions, the cast is directly above the DeclRefExpr.
  10278. // For conditional operators, the cast can be outside the conditional
  10279. // operator if both expressions are DeclRefExpr's.
  10280. void HandleValue(Expr *E) {
  10281. E = E->IgnoreParens();
  10282. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  10283. HandleDeclRefExpr(DRE);
  10284. return;
  10285. }
  10286. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  10287. Visit(CO->getCond());
  10288. HandleValue(CO->getTrueExpr());
  10289. HandleValue(CO->getFalseExpr());
  10290. return;
  10291. }
  10292. if (BinaryConditionalOperator *BCO =
  10293. dyn_cast<BinaryConditionalOperator>(E)) {
  10294. Visit(BCO->getCond());
  10295. HandleValue(BCO->getFalseExpr());
  10296. return;
  10297. }
  10298. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  10299. HandleValue(OVE->getSourceExpr());
  10300. return;
  10301. }
  10302. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10303. if (BO->getOpcode() == BO_Comma) {
  10304. Visit(BO->getLHS());
  10305. HandleValue(BO->getRHS());
  10306. return;
  10307. }
  10308. }
  10309. if (isa<MemberExpr>(E)) {
  10310. if (isInitList) {
  10311. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  10312. false /*CheckReference*/))
  10313. return;
  10314. }
  10315. Expr *Base = E->IgnoreParenImpCasts();
  10316. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  10317. // Check for static member variables and don't warn on them.
  10318. if (!isa<FieldDecl>(ME->getMemberDecl()))
  10319. return;
  10320. Base = ME->getBase()->IgnoreParenImpCasts();
  10321. }
  10322. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  10323. HandleDeclRefExpr(DRE);
  10324. return;
  10325. }
  10326. Visit(E);
  10327. }
  10328. // Reference types not handled in HandleValue are handled here since all
  10329. // uses of references are bad, not just r-value uses.
  10330. void VisitDeclRefExpr(DeclRefExpr *E) {
  10331. if (isReferenceType)
  10332. HandleDeclRefExpr(E);
  10333. }
  10334. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  10335. if (E->getCastKind() == CK_LValueToRValue) {
  10336. HandleValue(E->getSubExpr());
  10337. return;
  10338. }
  10339. Inherited::VisitImplicitCastExpr(E);
  10340. }
  10341. void VisitMemberExpr(MemberExpr *E) {
  10342. if (isInitList) {
  10343. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  10344. return;
  10345. }
  10346. // Don't warn on arrays since they can be treated as pointers.
  10347. if (E->getType()->canDecayToPointerType()) return;
  10348. // Warn when a non-static method call is followed by non-static member
  10349. // field accesses, which is followed by a DeclRefExpr.
  10350. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  10351. bool Warn = (MD && !MD->isStatic());
  10352. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  10353. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  10354. if (!isa<FieldDecl>(ME->getMemberDecl()))
  10355. Warn = false;
  10356. Base = ME->getBase()->IgnoreParenImpCasts();
  10357. }
  10358. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  10359. if (Warn)
  10360. HandleDeclRefExpr(DRE);
  10361. return;
  10362. }
  10363. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  10364. // Visit that expression.
  10365. Visit(Base);
  10366. }
  10367. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  10368. Expr *Callee = E->getCallee();
  10369. if (isa<UnresolvedLookupExpr>(Callee))
  10370. return Inherited::VisitCXXOperatorCallExpr(E);
  10371. Visit(Callee);
  10372. for (auto Arg: E->arguments())
  10373. HandleValue(Arg->IgnoreParenImpCasts());
  10374. }
  10375. void VisitUnaryOperator(UnaryOperator *E) {
  10376. // For POD record types, addresses of its own members are well-defined.
  10377. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  10378. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  10379. if (!isPODType)
  10380. HandleValue(E->getSubExpr());
  10381. return;
  10382. }
  10383. if (E->isIncrementDecrementOp()) {
  10384. HandleValue(E->getSubExpr());
  10385. return;
  10386. }
  10387. Inherited::VisitUnaryOperator(E);
  10388. }
  10389. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  10390. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  10391. if (E->getConstructor()->isCopyConstructor()) {
  10392. Expr *ArgExpr = E->getArg(0);
  10393. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  10394. if (ILE->getNumInits() == 1)
  10395. ArgExpr = ILE->getInit(0);
  10396. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  10397. if (ICE->getCastKind() == CK_NoOp)
  10398. ArgExpr = ICE->getSubExpr();
  10399. HandleValue(ArgExpr);
  10400. return;
  10401. }
  10402. Inherited::VisitCXXConstructExpr(E);
  10403. }
  10404. void VisitCallExpr(CallExpr *E) {
  10405. // Treat std::move as a use.
  10406. if (E->isCallToStdMove()) {
  10407. HandleValue(E->getArg(0));
  10408. return;
  10409. }
  10410. Inherited::VisitCallExpr(E);
  10411. }
  10412. void VisitBinaryOperator(BinaryOperator *E) {
  10413. if (E->isCompoundAssignmentOp()) {
  10414. HandleValue(E->getLHS());
  10415. Visit(E->getRHS());
  10416. return;
  10417. }
  10418. Inherited::VisitBinaryOperator(E);
  10419. }
  10420. // A custom visitor for BinaryConditionalOperator is needed because the
  10421. // regular visitor would check the condition and true expression separately
  10422. // but both point to the same place giving duplicate diagnostics.
  10423. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  10424. Visit(E->getCond());
  10425. Visit(E->getFalseExpr());
  10426. }
  10427. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  10428. Decl* ReferenceDecl = DRE->getDecl();
  10429. if (OrigDecl != ReferenceDecl) return;
  10430. unsigned diag;
  10431. if (isReferenceType) {
  10432. diag = diag::warn_uninit_self_reference_in_reference_init;
  10433. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  10434. diag = diag::warn_static_self_reference_in_init;
  10435. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  10436. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  10437. DRE->getDecl()->getType()->isRecordType()) {
  10438. diag = diag::warn_uninit_self_reference_in_init;
  10439. } else {
  10440. // Local variables will be handled by the CFG analysis.
  10441. return;
  10442. }
  10443. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  10444. S.PDiag(diag)
  10445. << DRE->getDecl() << OrigDecl->getLocation()
  10446. << DRE->getSourceRange());
  10447. }
  10448. };
  10449. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  10450. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  10451. bool DirectInit) {
  10452. // Parameters arguments are occassionially constructed with itself,
  10453. // for instance, in recursive functions. Skip them.
  10454. if (isa<ParmVarDecl>(OrigDecl))
  10455. return;
  10456. E = E->IgnoreParens();
  10457. // Skip checking T a = a where T is not a record or reference type.
  10458. // Doing so is a way to silence uninitialized warnings.
  10459. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  10460. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  10461. if (ICE->getCastKind() == CK_LValueToRValue)
  10462. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  10463. if (DRE->getDecl() == OrigDecl)
  10464. return;
  10465. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  10466. }
  10467. } // end anonymous namespace
  10468. namespace {
  10469. // Simple wrapper to add the name of a variable or (if no variable is
  10470. // available) a DeclarationName into a diagnostic.
  10471. struct VarDeclOrName {
  10472. VarDecl *VDecl;
  10473. DeclarationName Name;
  10474. friend const Sema::SemaDiagnosticBuilder &
  10475. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  10476. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  10477. }
  10478. };
  10479. } // end anonymous namespace
  10480. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  10481. DeclarationName Name, QualType Type,
  10482. TypeSourceInfo *TSI,
  10483. SourceRange Range, bool DirectInit,
  10484. Expr *Init) {
  10485. bool IsInitCapture = !VDecl;
  10486. assert((!VDecl || !VDecl->isInitCapture()) &&
  10487. "init captures are expected to be deduced prior to initialization");
  10488. VarDeclOrName VN{VDecl, Name};
  10489. DeducedType *Deduced = Type->getContainedDeducedType();
  10490. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  10491. // C++11 [dcl.spec.auto]p3
  10492. if (!Init) {
  10493. assert(VDecl && "no init for init capture deduction?");
  10494. // Except for class argument deduction, and then for an initializing
  10495. // declaration only, i.e. no static at class scope or extern.
  10496. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  10497. VDecl->hasExternalStorage() ||
  10498. VDecl->isStaticDataMember()) {
  10499. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  10500. << VDecl->getDeclName() << Type;
  10501. return QualType();
  10502. }
  10503. }
  10504. ArrayRef<Expr*> DeduceInits;
  10505. if (Init)
  10506. DeduceInits = Init;
  10507. if (DirectInit) {
  10508. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  10509. DeduceInits = PL->exprs();
  10510. }
  10511. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  10512. assert(VDecl && "non-auto type for init capture deduction?");
  10513. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  10514. InitializationKind Kind = InitializationKind::CreateForInit(
  10515. VDecl->getLocation(), DirectInit, Init);
  10516. // FIXME: Initialization should not be taking a mutable list of inits.
  10517. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  10518. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  10519. InitsCopy);
  10520. }
  10521. if (DirectInit) {
  10522. if (auto *IL = dyn_cast<InitListExpr>(Init))
  10523. DeduceInits = IL->inits();
  10524. }
  10525. // Deduction only works if we have exactly one source expression.
  10526. if (DeduceInits.empty()) {
  10527. // It isn't possible to write this directly, but it is possible to
  10528. // end up in this situation with "auto x(some_pack...);"
  10529. Diag(Init->getBeginLoc(), IsInitCapture
  10530. ? diag::err_init_capture_no_expression
  10531. : diag::err_auto_var_init_no_expression)
  10532. << VN << Type << Range;
  10533. return QualType();
  10534. }
  10535. if (DeduceInits.size() > 1) {
  10536. Diag(DeduceInits[1]->getBeginLoc(),
  10537. IsInitCapture ? diag::err_init_capture_multiple_expressions
  10538. : diag::err_auto_var_init_multiple_expressions)
  10539. << VN << Type << Range;
  10540. return QualType();
  10541. }
  10542. Expr *DeduceInit = DeduceInits[0];
  10543. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  10544. Diag(Init->getBeginLoc(), IsInitCapture
  10545. ? diag::err_init_capture_paren_braces
  10546. : diag::err_auto_var_init_paren_braces)
  10547. << isa<InitListExpr>(Init) << VN << Type << Range;
  10548. return QualType();
  10549. }
  10550. // Expressions default to 'id' when we're in a debugger.
  10551. bool DefaultedAnyToId = false;
  10552. if (getLangOpts().DebuggerCastResultToId &&
  10553. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  10554. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10555. if (Result.isInvalid()) {
  10556. return QualType();
  10557. }
  10558. Init = Result.get();
  10559. DefaultedAnyToId = true;
  10560. }
  10561. // C++ [dcl.decomp]p1:
  10562. // If the assignment-expression [...] has array type A and no ref-qualifier
  10563. // is present, e has type cv A
  10564. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  10565. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  10566. DeduceInit->getType()->isConstantArrayType())
  10567. return Context.getQualifiedType(DeduceInit->getType(),
  10568. Type.getQualifiers());
  10569. QualType DeducedType;
  10570. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  10571. if (!IsInitCapture)
  10572. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  10573. else if (isa<InitListExpr>(Init))
  10574. Diag(Range.getBegin(),
  10575. diag::err_init_capture_deduction_failure_from_init_list)
  10576. << VN
  10577. << (DeduceInit->getType().isNull() ? TSI->getType()
  10578. : DeduceInit->getType())
  10579. << DeduceInit->getSourceRange();
  10580. else
  10581. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  10582. << VN << TSI->getType()
  10583. << (DeduceInit->getType().isNull() ? TSI->getType()
  10584. : DeduceInit->getType())
  10585. << DeduceInit->getSourceRange();
  10586. }
  10587. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  10588. // 'id' instead of a specific object type prevents most of our usual
  10589. // checks.
  10590. // We only want to warn outside of template instantiations, though:
  10591. // inside a template, the 'id' could have come from a parameter.
  10592. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  10593. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  10594. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  10595. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  10596. }
  10597. return DeducedType;
  10598. }
  10599. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  10600. Expr *Init) {
  10601. assert(!Init || !Init->containsErrors());
  10602. QualType DeducedType = deduceVarTypeFromInitializer(
  10603. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  10604. VDecl->getSourceRange(), DirectInit, Init);
  10605. if (DeducedType.isNull()) {
  10606. VDecl->setInvalidDecl();
  10607. return true;
  10608. }
  10609. VDecl->setType(DeducedType);
  10610. assert(VDecl->isLinkageValid());
  10611. // In ARC, infer lifetime.
  10612. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  10613. VDecl->setInvalidDecl();
  10614. if (getLangOpts().OpenCL)
  10615. deduceOpenCLAddressSpace(VDecl);
  10616. // If this is a redeclaration, check that the type we just deduced matches
  10617. // the previously declared type.
  10618. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  10619. // We never need to merge the type, because we cannot form an incomplete
  10620. // array of auto, nor deduce such a type.
  10621. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  10622. }
  10623. // Check the deduced type is valid for a variable declaration.
  10624. CheckVariableDeclarationType(VDecl);
  10625. return VDecl->isInvalidDecl();
  10626. }
  10627. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  10628. SourceLocation Loc) {
  10629. if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
  10630. Init = EWC->getSubExpr();
  10631. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  10632. Init = CE->getSubExpr();
  10633. QualType InitType = Init->getType();
  10634. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10635. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  10636. "shouldn't be called if type doesn't have a non-trivial C struct");
  10637. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  10638. for (auto I : ILE->inits()) {
  10639. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  10640. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  10641. continue;
  10642. SourceLocation SL = I->getExprLoc();
  10643. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  10644. }
  10645. return;
  10646. }
  10647. if (isa<ImplicitValueInitExpr>(Init)) {
  10648. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10649. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  10650. NTCUK_Init);
  10651. } else {
  10652. // Assume all other explicit initializers involving copying some existing
  10653. // object.
  10654. // TODO: ignore any explicit initializers where we can guarantee
  10655. // copy-elision.
  10656. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  10657. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  10658. }
  10659. }
  10660. namespace {
  10661. bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
  10662. // Ignore unavailable fields. A field can be marked as unavailable explicitly
  10663. // in the source code or implicitly by the compiler if it is in a union
  10664. // defined in a system header and has non-trivial ObjC ownership
  10665. // qualifications. We don't want those fields to participate in determining
  10666. // whether the containing union is non-trivial.
  10667. return FD->hasAttr<UnavailableAttr>();
  10668. }
  10669. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  10670. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  10671. void> {
  10672. using Super =
  10673. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  10674. void>;
  10675. DiagNonTrivalCUnionDefaultInitializeVisitor(
  10676. QualType OrigTy, SourceLocation OrigLoc,
  10677. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10678. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10679. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  10680. const FieldDecl *FD, bool InNonTrivialUnion) {
  10681. if (const auto *AT = S.Context.getAsArrayType(QT))
  10682. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10683. InNonTrivialUnion);
  10684. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  10685. }
  10686. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10687. bool InNonTrivialUnion) {
  10688. if (InNonTrivialUnion)
  10689. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10690. << 1 << 0 << QT << FD->getName();
  10691. }
  10692. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10693. if (InNonTrivialUnion)
  10694. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10695. << 1 << 0 << QT << FD->getName();
  10696. }
  10697. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10698. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10699. if (RD->isUnion()) {
  10700. if (OrigLoc.isValid()) {
  10701. bool IsUnion = false;
  10702. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10703. IsUnion = OrigRD->isUnion();
  10704. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10705. << 0 << OrigTy << IsUnion << UseContext;
  10706. // Reset OrigLoc so that this diagnostic is emitted only once.
  10707. OrigLoc = SourceLocation();
  10708. }
  10709. InNonTrivialUnion = true;
  10710. }
  10711. if (InNonTrivialUnion)
  10712. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10713. << 0 << 0 << QT.getUnqualifiedType() << "";
  10714. for (const FieldDecl *FD : RD->fields())
  10715. if (!shouldIgnoreForRecordTriviality(FD))
  10716. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10717. }
  10718. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10719. // The non-trivial C union type or the struct/union type that contains a
  10720. // non-trivial C union.
  10721. QualType OrigTy;
  10722. SourceLocation OrigLoc;
  10723. Sema::NonTrivialCUnionContext UseContext;
  10724. Sema &S;
  10725. };
  10726. struct DiagNonTrivalCUnionDestructedTypeVisitor
  10727. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  10728. using Super =
  10729. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  10730. DiagNonTrivalCUnionDestructedTypeVisitor(
  10731. QualType OrigTy, SourceLocation OrigLoc,
  10732. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  10733. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10734. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  10735. const FieldDecl *FD, bool InNonTrivialUnion) {
  10736. if (const auto *AT = S.Context.getAsArrayType(QT))
  10737. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10738. InNonTrivialUnion);
  10739. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  10740. }
  10741. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10742. bool InNonTrivialUnion) {
  10743. if (InNonTrivialUnion)
  10744. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10745. << 1 << 1 << QT << FD->getName();
  10746. }
  10747. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10748. if (InNonTrivialUnion)
  10749. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10750. << 1 << 1 << QT << FD->getName();
  10751. }
  10752. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10753. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10754. if (RD->isUnion()) {
  10755. if (OrigLoc.isValid()) {
  10756. bool IsUnion = false;
  10757. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10758. IsUnion = OrigRD->isUnion();
  10759. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10760. << 1 << OrigTy << IsUnion << UseContext;
  10761. // Reset OrigLoc so that this diagnostic is emitted only once.
  10762. OrigLoc = SourceLocation();
  10763. }
  10764. InNonTrivialUnion = true;
  10765. }
  10766. if (InNonTrivialUnion)
  10767. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10768. << 0 << 1 << QT.getUnqualifiedType() << "";
  10769. for (const FieldDecl *FD : RD->fields())
  10770. if (!shouldIgnoreForRecordTriviality(FD))
  10771. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10772. }
  10773. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10774. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  10775. bool InNonTrivialUnion) {}
  10776. // The non-trivial C union type or the struct/union type that contains a
  10777. // non-trivial C union.
  10778. QualType OrigTy;
  10779. SourceLocation OrigLoc;
  10780. Sema::NonTrivialCUnionContext UseContext;
  10781. Sema &S;
  10782. };
  10783. struct DiagNonTrivalCUnionCopyVisitor
  10784. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  10785. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  10786. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  10787. Sema::NonTrivialCUnionContext UseContext,
  10788. Sema &S)
  10789. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  10790. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  10791. const FieldDecl *FD, bool InNonTrivialUnion) {
  10792. if (const auto *AT = S.Context.getAsArrayType(QT))
  10793. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  10794. InNonTrivialUnion);
  10795. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  10796. }
  10797. void visitARCStrong(QualType QT, const FieldDecl *FD,
  10798. bool InNonTrivialUnion) {
  10799. if (InNonTrivialUnion)
  10800. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10801. << 1 << 2 << QT << FD->getName();
  10802. }
  10803. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10804. if (InNonTrivialUnion)
  10805. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  10806. << 1 << 2 << QT << FD->getName();
  10807. }
  10808. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  10809. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  10810. if (RD->isUnion()) {
  10811. if (OrigLoc.isValid()) {
  10812. bool IsUnion = false;
  10813. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  10814. IsUnion = OrigRD->isUnion();
  10815. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  10816. << 2 << OrigTy << IsUnion << UseContext;
  10817. // Reset OrigLoc so that this diagnostic is emitted only once.
  10818. OrigLoc = SourceLocation();
  10819. }
  10820. InNonTrivialUnion = true;
  10821. }
  10822. if (InNonTrivialUnion)
  10823. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  10824. << 0 << 2 << QT.getUnqualifiedType() << "";
  10825. for (const FieldDecl *FD : RD->fields())
  10826. if (!shouldIgnoreForRecordTriviality(FD))
  10827. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  10828. }
  10829. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  10830. const FieldDecl *FD, bool InNonTrivialUnion) {}
  10831. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  10832. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  10833. bool InNonTrivialUnion) {}
  10834. // The non-trivial C union type or the struct/union type that contains a
  10835. // non-trivial C union.
  10836. QualType OrigTy;
  10837. SourceLocation OrigLoc;
  10838. Sema::NonTrivialCUnionContext UseContext;
  10839. Sema &S;
  10840. };
  10841. } // namespace
  10842. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  10843. NonTrivialCUnionContext UseContext,
  10844. unsigned NonTrivialKind) {
  10845. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  10846. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  10847. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  10848. "shouldn't be called if type doesn't have a non-trivial C union");
  10849. if ((NonTrivialKind & NTCUK_Init) &&
  10850. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  10851. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  10852. .visit(QT, nullptr, false);
  10853. if ((NonTrivialKind & NTCUK_Destruct) &&
  10854. QT.hasNonTrivialToPrimitiveDestructCUnion())
  10855. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  10856. .visit(QT, nullptr, false);
  10857. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  10858. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  10859. .visit(QT, nullptr, false);
  10860. }
  10861. /// AddInitializerToDecl - Adds the initializer Init to the
  10862. /// declaration dcl. If DirectInit is true, this is C++ direct
  10863. /// initialization rather than copy initialization.
  10864. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  10865. // If there is no declaration, there was an error parsing it. Just ignore
  10866. // the initializer.
  10867. if (!RealDecl || RealDecl->isInvalidDecl()) {
  10868. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  10869. return;
  10870. }
  10871. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  10872. // Pure-specifiers are handled in ActOnPureSpecifier.
  10873. Diag(Method->getLocation(), diag::err_member_function_initialization)
  10874. << Method->getDeclName() << Init->getSourceRange();
  10875. Method->setInvalidDecl();
  10876. return;
  10877. }
  10878. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  10879. if (!VDecl) {
  10880. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  10881. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  10882. RealDecl->setInvalidDecl();
  10883. return;
  10884. }
  10885. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  10886. if (VDecl->getType()->isUndeducedType()) {
  10887. // Attempt typo correction early so that the type of the init expression can
  10888. // be deduced based on the chosen correction if the original init contains a
  10889. // TypoExpr.
  10890. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  10891. if (!Res.isUsable()) {
  10892. // There are unresolved typos in Init, just drop them.
  10893. // FIXME: improve the recovery strategy to preserve the Init.
  10894. RealDecl->setInvalidDecl();
  10895. return;
  10896. }
  10897. if (Res.get()->containsErrors()) {
  10898. // Invalidate the decl as we don't know the type for recovery-expr yet.
  10899. RealDecl->setInvalidDecl();
  10900. VDecl->setInit(Res.get());
  10901. return;
  10902. }
  10903. Init = Res.get();
  10904. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  10905. return;
  10906. }
  10907. // dllimport cannot be used on variable definitions.
  10908. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  10909. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  10910. VDecl->setInvalidDecl();
  10911. return;
  10912. }
  10913. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  10914. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  10915. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  10916. VDecl->setInvalidDecl();
  10917. return;
  10918. }
  10919. if (!VDecl->getType()->isDependentType()) {
  10920. // A definition must end up with a complete type, which means it must be
  10921. // complete with the restriction that an array type might be completed by
  10922. // the initializer; note that later code assumes this restriction.
  10923. QualType BaseDeclType = VDecl->getType();
  10924. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  10925. BaseDeclType = Array->getElementType();
  10926. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  10927. diag::err_typecheck_decl_incomplete_type)) {
  10928. RealDecl->setInvalidDecl();
  10929. return;
  10930. }
  10931. // The variable can not have an abstract class type.
  10932. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  10933. diag::err_abstract_type_in_decl,
  10934. AbstractVariableType))
  10935. VDecl->setInvalidDecl();
  10936. }
  10937. // If adding the initializer will turn this declaration into a definition,
  10938. // and we already have a definition for this variable, diagnose or otherwise
  10939. // handle the situation.
  10940. if (VarDecl *Def = VDecl->getDefinition())
  10941. if (Def != VDecl &&
  10942. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  10943. !VDecl->isThisDeclarationADemotedDefinition() &&
  10944. checkVarDeclRedefinition(Def, VDecl))
  10945. return;
  10946. if (getLangOpts().CPlusPlus) {
  10947. // C++ [class.static.data]p4
  10948. // If a static data member is of const integral or const
  10949. // enumeration type, its declaration in the class definition can
  10950. // specify a constant-initializer which shall be an integral
  10951. // constant expression (5.19). In that case, the member can appear
  10952. // in integral constant expressions. The member shall still be
  10953. // defined in a namespace scope if it is used in the program and the
  10954. // namespace scope definition shall not contain an initializer.
  10955. //
  10956. // We already performed a redefinition check above, but for static
  10957. // data members we also need to check whether there was an in-class
  10958. // declaration with an initializer.
  10959. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  10960. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  10961. << VDecl->getDeclName();
  10962. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  10963. diag::note_previous_initializer)
  10964. << 0;
  10965. return;
  10966. }
  10967. if (VDecl->hasLocalStorage())
  10968. setFunctionHasBranchProtectedScope();
  10969. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  10970. VDecl->setInvalidDecl();
  10971. return;
  10972. }
  10973. }
  10974. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  10975. // a kernel function cannot be initialized."
  10976. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  10977. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  10978. VDecl->setInvalidDecl();
  10979. return;
  10980. }
  10981. // The LoaderUninitialized attribute acts as a definition (of undef).
  10982. if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
  10983. Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
  10984. VDecl->setInvalidDecl();
  10985. return;
  10986. }
  10987. // Get the decls type and save a reference for later, since
  10988. // CheckInitializerTypes may change it.
  10989. QualType DclT = VDecl->getType(), SavT = DclT;
  10990. // Expressions default to 'id' when we're in a debugger
  10991. // and we are assigning it to a variable of Objective-C pointer type.
  10992. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  10993. Init->getType() == Context.UnknownAnyTy) {
  10994. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  10995. if (Result.isInvalid()) {
  10996. VDecl->setInvalidDecl();
  10997. return;
  10998. }
  10999. Init = Result.get();
  11000. }
  11001. // Perform the initialization.
  11002. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  11003. if (!VDecl->isInvalidDecl()) {
  11004. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  11005. InitializationKind Kind = InitializationKind::CreateForInit(
  11006. VDecl->getLocation(), DirectInit, Init);
  11007. MultiExprArg Args = Init;
  11008. if (CXXDirectInit)
  11009. Args = MultiExprArg(CXXDirectInit->getExprs(),
  11010. CXXDirectInit->getNumExprs());
  11011. // Try to correct any TypoExprs in the initialization arguments.
  11012. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  11013. ExprResult Res = CorrectDelayedTyposInExpr(
  11014. Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
  11015. [this, Entity, Kind](Expr *E) {
  11016. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  11017. return Init.Failed() ? ExprError() : E;
  11018. });
  11019. if (Res.isInvalid()) {
  11020. VDecl->setInvalidDecl();
  11021. } else if (Res.get() != Args[Idx]) {
  11022. Args[Idx] = Res.get();
  11023. }
  11024. }
  11025. if (VDecl->isInvalidDecl())
  11026. return;
  11027. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  11028. /*TopLevelOfInitList=*/false,
  11029. /*TreatUnavailableAsInvalid=*/false);
  11030. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  11031. if (Result.isInvalid()) {
  11032. // If the provided initializer fails to initialize the var decl,
  11033. // we attach a recovery expr for better recovery.
  11034. auto RecoveryExpr =
  11035. CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
  11036. if (RecoveryExpr.get())
  11037. VDecl->setInit(RecoveryExpr.get());
  11038. return;
  11039. }
  11040. Init = Result.getAs<Expr>();
  11041. }
  11042. // Check for self-references within variable initializers.
  11043. // Variables declared within a function/method body (except for references)
  11044. // are handled by a dataflow analysis.
  11045. // This is undefined behavior in C++, but valid in C.
  11046. if (getLangOpts().CPlusPlus)
  11047. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  11048. VDecl->getType()->isReferenceType())
  11049. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  11050. // If the type changed, it means we had an incomplete type that was
  11051. // completed by the initializer. For example:
  11052. // int ary[] = { 1, 3, 5 };
  11053. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  11054. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  11055. VDecl->setType(DclT);
  11056. if (!VDecl->isInvalidDecl()) {
  11057. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  11058. if (VDecl->hasAttr<BlocksAttr>())
  11059. checkRetainCycles(VDecl, Init);
  11060. // It is safe to assign a weak reference into a strong variable.
  11061. // Although this code can still have problems:
  11062. // id x = self.weakProp;
  11063. // id y = self.weakProp;
  11064. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  11065. // paths through the function. This should be revisited if
  11066. // -Wrepeated-use-of-weak is made flow-sensitive.
  11067. if (FunctionScopeInfo *FSI = getCurFunction())
  11068. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  11069. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  11070. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  11071. Init->getBeginLoc()))
  11072. FSI->markSafeWeakUse(Init);
  11073. }
  11074. // The initialization is usually a full-expression.
  11075. //
  11076. // FIXME: If this is a braced initialization of an aggregate, it is not
  11077. // an expression, and each individual field initializer is a separate
  11078. // full-expression. For instance, in:
  11079. //
  11080. // struct Temp { ~Temp(); };
  11081. // struct S { S(Temp); };
  11082. // struct T { S a, b; } t = { Temp(), Temp() }
  11083. //
  11084. // we should destroy the first Temp before constructing the second.
  11085. ExprResult Result =
  11086. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  11087. /*DiscardedValue*/ false, VDecl->isConstexpr());
  11088. if (Result.isInvalid()) {
  11089. VDecl->setInvalidDecl();
  11090. return;
  11091. }
  11092. Init = Result.get();
  11093. // Attach the initializer to the decl.
  11094. VDecl->setInit(Init);
  11095. if (VDecl->isLocalVarDecl()) {
  11096. // Don't check the initializer if the declaration is malformed.
  11097. if (VDecl->isInvalidDecl()) {
  11098. // do nothing
  11099. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  11100. // This is true even in C++ for OpenCL.
  11101. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  11102. CheckForConstantInitializer(Init, DclT);
  11103. // Otherwise, C++ does not restrict the initializer.
  11104. } else if (getLangOpts().CPlusPlus) {
  11105. // do nothing
  11106. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  11107. // static storage duration shall be constant expressions or string literals.
  11108. } else if (VDecl->getStorageClass() == SC_Static) {
  11109. CheckForConstantInitializer(Init, DclT);
  11110. // C89 is stricter than C99 for aggregate initializers.
  11111. // C89 6.5.7p3: All the expressions [...] in an initializer list
  11112. // for an object that has aggregate or union type shall be
  11113. // constant expressions.
  11114. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  11115. isa<InitListExpr>(Init)) {
  11116. const Expr *Culprit;
  11117. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  11118. Diag(Culprit->getExprLoc(),
  11119. diag::ext_aggregate_init_not_constant)
  11120. << Culprit->getSourceRange();
  11121. }
  11122. }
  11123. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  11124. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  11125. if (VDecl->hasLocalStorage())
  11126. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11127. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  11128. VDecl->getLexicalDeclContext()->isRecord()) {
  11129. // This is an in-class initialization for a static data member, e.g.,
  11130. //
  11131. // struct S {
  11132. // static const int value = 17;
  11133. // };
  11134. // C++ [class.mem]p4:
  11135. // A member-declarator can contain a constant-initializer only
  11136. // if it declares a static member (9.4) of const integral or
  11137. // const enumeration type, see 9.4.2.
  11138. //
  11139. // C++11 [class.static.data]p3:
  11140. // If a non-volatile non-inline const static data member is of integral
  11141. // or enumeration type, its declaration in the class definition can
  11142. // specify a brace-or-equal-initializer in which every initializer-clause
  11143. // that is an assignment-expression is a constant expression. A static
  11144. // data member of literal type can be declared in the class definition
  11145. // with the constexpr specifier; if so, its declaration shall specify a
  11146. // brace-or-equal-initializer in which every initializer-clause that is
  11147. // an assignment-expression is a constant expression.
  11148. // Do nothing on dependent types.
  11149. if (DclT->isDependentType()) {
  11150. // Allow any 'static constexpr' members, whether or not they are of literal
  11151. // type. We separately check that every constexpr variable is of literal
  11152. // type.
  11153. } else if (VDecl->isConstexpr()) {
  11154. // Require constness.
  11155. } else if (!DclT.isConstQualified()) {
  11156. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  11157. << Init->getSourceRange();
  11158. VDecl->setInvalidDecl();
  11159. // We allow integer constant expressions in all cases.
  11160. } else if (DclT->isIntegralOrEnumerationType()) {
  11161. // Check whether the expression is a constant expression.
  11162. SourceLocation Loc;
  11163. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  11164. // In C++11, a non-constexpr const static data member with an
  11165. // in-class initializer cannot be volatile.
  11166. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  11167. else if (Init->isValueDependent())
  11168. ; // Nothing to check.
  11169. else if (Init->isIntegerConstantExpr(Context, &Loc))
  11170. ; // Ok, it's an ICE!
  11171. else if (Init->getType()->isScopedEnumeralType() &&
  11172. Init->isCXX11ConstantExpr(Context))
  11173. ; // Ok, it is a scoped-enum constant expression.
  11174. else if (Init->isEvaluatable(Context)) {
  11175. // If we can constant fold the initializer through heroics, accept it,
  11176. // but report this as a use of an extension for -pedantic.
  11177. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  11178. << Init->getSourceRange();
  11179. } else {
  11180. // Otherwise, this is some crazy unknown case. Report the issue at the
  11181. // location provided by the isIntegerConstantExpr failed check.
  11182. Diag(Loc, diag::err_in_class_initializer_non_constant)
  11183. << Init->getSourceRange();
  11184. VDecl->setInvalidDecl();
  11185. }
  11186. // We allow foldable floating-point constants as an extension.
  11187. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  11188. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  11189. // it anyway and provide a fixit to add the 'constexpr'.
  11190. if (getLangOpts().CPlusPlus11) {
  11191. Diag(VDecl->getLocation(),
  11192. diag::ext_in_class_initializer_float_type_cxx11)
  11193. << DclT << Init->getSourceRange();
  11194. Diag(VDecl->getBeginLoc(),
  11195. diag::note_in_class_initializer_float_type_cxx11)
  11196. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  11197. } else {
  11198. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  11199. << DclT << Init->getSourceRange();
  11200. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  11201. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  11202. << Init->getSourceRange();
  11203. VDecl->setInvalidDecl();
  11204. }
  11205. }
  11206. // Suggest adding 'constexpr' in C++11 for literal types.
  11207. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  11208. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  11209. << DclT << Init->getSourceRange()
  11210. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  11211. VDecl->setConstexpr(true);
  11212. } else {
  11213. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  11214. << DclT << Init->getSourceRange();
  11215. VDecl->setInvalidDecl();
  11216. }
  11217. } else if (VDecl->isFileVarDecl()) {
  11218. // In C, extern is typically used to avoid tentative definitions when
  11219. // declaring variables in headers, but adding an intializer makes it a
  11220. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  11221. // In C++, extern is often used to give implictly static const variables
  11222. // external linkage, so don't warn in that case. If selectany is present,
  11223. // this might be header code intended for C and C++ inclusion, so apply the
  11224. // C++ rules.
  11225. if (VDecl->getStorageClass() == SC_Extern &&
  11226. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  11227. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  11228. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  11229. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  11230. Diag(VDecl->getLocation(), diag::warn_extern_init);
  11231. // In Microsoft C++ mode, a const variable defined in namespace scope has
  11232. // external linkage by default if the variable is declared with
  11233. // __declspec(dllexport).
  11234. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  11235. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  11236. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  11237. VDecl->setStorageClass(SC_Extern);
  11238. // C99 6.7.8p4. All file scoped initializers need to be constant.
  11239. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  11240. CheckForConstantInitializer(Init, DclT);
  11241. }
  11242. QualType InitType = Init->getType();
  11243. if (!InitType.isNull() &&
  11244. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  11245. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  11246. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  11247. // We will represent direct-initialization similarly to copy-initialization:
  11248. // int x(1); -as-> int x = 1;
  11249. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  11250. //
  11251. // Clients that want to distinguish between the two forms, can check for
  11252. // direct initializer using VarDecl::getInitStyle().
  11253. // A major benefit is that clients that don't particularly care about which
  11254. // exactly form was it (like the CodeGen) can handle both cases without
  11255. // special case code.
  11256. // C++ 8.5p11:
  11257. // The form of initialization (using parentheses or '=') is generally
  11258. // insignificant, but does matter when the entity being initialized has a
  11259. // class type.
  11260. if (CXXDirectInit) {
  11261. assert(DirectInit && "Call-style initializer must be direct init.");
  11262. VDecl->setInitStyle(VarDecl::CallInit);
  11263. } else if (DirectInit) {
  11264. // This must be list-initialization. No other way is direct-initialization.
  11265. VDecl->setInitStyle(VarDecl::ListInit);
  11266. }
  11267. if (LangOpts.OpenMP &&
  11268. (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
  11269. VDecl->isFileVarDecl())
  11270. DeclsToCheckForDeferredDiags.insert(VDecl);
  11271. CheckCompleteVariableDeclaration(VDecl);
  11272. }
  11273. /// ActOnInitializerError - Given that there was an error parsing an
  11274. /// initializer for the given declaration, try to at least re-establish
  11275. /// invariants such as whether a variable's type is either dependent or
  11276. /// complete.
  11277. void Sema::ActOnInitializerError(Decl *D) {
  11278. // Our main concern here is re-establishing invariants like "a
  11279. // variable's type is either dependent or complete".
  11280. if (!D || D->isInvalidDecl()) return;
  11281. VarDecl *VD = dyn_cast<VarDecl>(D);
  11282. if (!VD) return;
  11283. // Bindings are not usable if we can't make sense of the initializer.
  11284. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  11285. for (auto *BD : DD->bindings())
  11286. BD->setInvalidDecl();
  11287. // Auto types are meaningless if we can't make sense of the initializer.
  11288. if (VD->getType()->isUndeducedType()) {
  11289. D->setInvalidDecl();
  11290. return;
  11291. }
  11292. QualType Ty = VD->getType();
  11293. if (Ty->isDependentType()) return;
  11294. // Require a complete type.
  11295. if (RequireCompleteType(VD->getLocation(),
  11296. Context.getBaseElementType(Ty),
  11297. diag::err_typecheck_decl_incomplete_type)) {
  11298. VD->setInvalidDecl();
  11299. return;
  11300. }
  11301. // Require a non-abstract type.
  11302. if (RequireNonAbstractType(VD->getLocation(), Ty,
  11303. diag::err_abstract_type_in_decl,
  11304. AbstractVariableType)) {
  11305. VD->setInvalidDecl();
  11306. return;
  11307. }
  11308. // Don't bother complaining about constructors or destructors,
  11309. // though.
  11310. }
  11311. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  11312. // If there is no declaration, there was an error parsing it. Just ignore it.
  11313. if (!RealDecl)
  11314. return;
  11315. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  11316. QualType Type = Var->getType();
  11317. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  11318. if (isa<DecompositionDecl>(RealDecl)) {
  11319. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  11320. Var->setInvalidDecl();
  11321. return;
  11322. }
  11323. if (Type->isUndeducedType() &&
  11324. DeduceVariableDeclarationType(Var, false, nullptr))
  11325. return;
  11326. // C++11 [class.static.data]p3: A static data member can be declared with
  11327. // the constexpr specifier; if so, its declaration shall specify
  11328. // a brace-or-equal-initializer.
  11329. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  11330. // the definition of a variable [...] or the declaration of a static data
  11331. // member.
  11332. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  11333. !Var->isThisDeclarationADemotedDefinition()) {
  11334. if (Var->isStaticDataMember()) {
  11335. // C++1z removes the relevant rule; the in-class declaration is always
  11336. // a definition there.
  11337. if (!getLangOpts().CPlusPlus17 &&
  11338. !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  11339. Diag(Var->getLocation(),
  11340. diag::err_constexpr_static_mem_var_requires_init)
  11341. << Var;
  11342. Var->setInvalidDecl();
  11343. return;
  11344. }
  11345. } else {
  11346. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  11347. Var->setInvalidDecl();
  11348. return;
  11349. }
  11350. }
  11351. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  11352. // be initialized.
  11353. if (!Var->isInvalidDecl() &&
  11354. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  11355. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  11356. bool HasConstExprDefaultConstructor = false;
  11357. if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
  11358. for (auto *Ctor : RD->ctors()) {
  11359. if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
  11360. Ctor->getMethodQualifiers().getAddressSpace() ==
  11361. LangAS::opencl_constant) {
  11362. HasConstExprDefaultConstructor = true;
  11363. }
  11364. }
  11365. }
  11366. if (!HasConstExprDefaultConstructor) {
  11367. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  11368. Var->setInvalidDecl();
  11369. return;
  11370. }
  11371. }
  11372. if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
  11373. if (Var->getStorageClass() == SC_Extern) {
  11374. Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
  11375. << Var;
  11376. Var->setInvalidDecl();
  11377. return;
  11378. }
  11379. if (RequireCompleteType(Var->getLocation(), Var->getType(),
  11380. diag::err_typecheck_decl_incomplete_type)) {
  11381. Var->setInvalidDecl();
  11382. return;
  11383. }
  11384. if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
  11385. if (!RD->hasTrivialDefaultConstructor()) {
  11386. Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
  11387. Var->setInvalidDecl();
  11388. return;
  11389. }
  11390. }
  11391. // The declaration is unitialized, no need for further checks.
  11392. return;
  11393. }
  11394. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  11395. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  11396. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  11397. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  11398. NTCUC_DefaultInitializedObject, NTCUK_Init);
  11399. switch (DefKind) {
  11400. case VarDecl::Definition:
  11401. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  11402. break;
  11403. // We have an out-of-line definition of a static data member
  11404. // that has an in-class initializer, so we type-check this like
  11405. // a declaration.
  11406. //
  11407. LLVM_FALLTHROUGH;
  11408. case VarDecl::DeclarationOnly:
  11409. // It's only a declaration.
  11410. // Block scope. C99 6.7p7: If an identifier for an object is
  11411. // declared with no linkage (C99 6.2.2p6), the type for the
  11412. // object shall be complete.
  11413. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  11414. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  11415. RequireCompleteType(Var->getLocation(), Type,
  11416. diag::err_typecheck_decl_incomplete_type))
  11417. Var->setInvalidDecl();
  11418. // Make sure that the type is not abstract.
  11419. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  11420. RequireNonAbstractType(Var->getLocation(), Type,
  11421. diag::err_abstract_type_in_decl,
  11422. AbstractVariableType))
  11423. Var->setInvalidDecl();
  11424. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  11425. Var->getStorageClass() == SC_PrivateExtern) {
  11426. Diag(Var->getLocation(), diag::warn_private_extern);
  11427. Diag(Var->getLocation(), diag::note_private_extern);
  11428. }
  11429. if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
  11430. !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
  11431. ExternalDeclarations.push_back(Var);
  11432. return;
  11433. case VarDecl::TentativeDefinition:
  11434. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  11435. // object that has file scope without an initializer, and without a
  11436. // storage-class specifier or with the storage-class specifier "static",
  11437. // constitutes a tentative definition. Note: A tentative definition with
  11438. // external linkage is valid (C99 6.2.2p5).
  11439. if (!Var->isInvalidDecl()) {
  11440. if (const IncompleteArrayType *ArrayT
  11441. = Context.getAsIncompleteArrayType(Type)) {
  11442. if (RequireCompleteSizedType(
  11443. Var->getLocation(), ArrayT->getElementType(),
  11444. diag::err_array_incomplete_or_sizeless_type))
  11445. Var->setInvalidDecl();
  11446. } else if (Var->getStorageClass() == SC_Static) {
  11447. // C99 6.9.2p3: If the declaration of an identifier for an object is
  11448. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  11449. // declared type shall not be an incomplete type.
  11450. // NOTE: code such as the following
  11451. // static struct s;
  11452. // struct s { int a; };
  11453. // is accepted by gcc. Hence here we issue a warning instead of
  11454. // an error and we do not invalidate the static declaration.
  11455. // NOTE: to avoid multiple warnings, only check the first declaration.
  11456. if (Var->isFirstDecl())
  11457. RequireCompleteType(Var->getLocation(), Type,
  11458. diag::ext_typecheck_decl_incomplete_type);
  11459. }
  11460. }
  11461. // Record the tentative definition; we're done.
  11462. if (!Var->isInvalidDecl())
  11463. TentativeDefinitions.push_back(Var);
  11464. return;
  11465. }
  11466. // Provide a specific diagnostic for uninitialized variable
  11467. // definitions with incomplete array type.
  11468. if (Type->isIncompleteArrayType()) {
  11469. Diag(Var->getLocation(),
  11470. diag::err_typecheck_incomplete_array_needs_initializer);
  11471. Var->setInvalidDecl();
  11472. return;
  11473. }
  11474. // Provide a specific diagnostic for uninitialized variable
  11475. // definitions with reference type.
  11476. if (Type->isReferenceType()) {
  11477. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  11478. << Var << SourceRange(Var->getLocation(), Var->getLocation());
  11479. Var->setInvalidDecl();
  11480. return;
  11481. }
  11482. // Do not attempt to type-check the default initializer for a
  11483. // variable with dependent type.
  11484. if (Type->isDependentType())
  11485. return;
  11486. if (Var->isInvalidDecl())
  11487. return;
  11488. if (!Var->hasAttr<AliasAttr>()) {
  11489. if (RequireCompleteType(Var->getLocation(),
  11490. Context.getBaseElementType(Type),
  11491. diag::err_typecheck_decl_incomplete_type)) {
  11492. Var->setInvalidDecl();
  11493. return;
  11494. }
  11495. } else {
  11496. return;
  11497. }
  11498. // The variable can not have an abstract class type.
  11499. if (RequireNonAbstractType(Var->getLocation(), Type,
  11500. diag::err_abstract_type_in_decl,
  11501. AbstractVariableType)) {
  11502. Var->setInvalidDecl();
  11503. return;
  11504. }
  11505. // Check for jumps past the implicit initializer. C++0x
  11506. // clarifies that this applies to a "variable with automatic
  11507. // storage duration", not a "local variable".
  11508. // C++11 [stmt.dcl]p3
  11509. // A program that jumps from a point where a variable with automatic
  11510. // storage duration is not in scope to a point where it is in scope is
  11511. // ill-formed unless the variable has scalar type, class type with a
  11512. // trivial default constructor and a trivial destructor, a cv-qualified
  11513. // version of one of these types, or an array of one of the preceding
  11514. // types and is declared without an initializer.
  11515. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  11516. if (const RecordType *Record
  11517. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  11518. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  11519. // Mark the function (if we're in one) for further checking even if the
  11520. // looser rules of C++11 do not require such checks, so that we can
  11521. // diagnose incompatibilities with C++98.
  11522. if (!CXXRecord->isPOD())
  11523. setFunctionHasBranchProtectedScope();
  11524. }
  11525. }
  11526. // In OpenCL, we can't initialize objects in the __local address space,
  11527. // even implicitly, so don't synthesize an implicit initializer.
  11528. if (getLangOpts().OpenCL &&
  11529. Var->getType().getAddressSpace() == LangAS::opencl_local)
  11530. return;
  11531. // C++03 [dcl.init]p9:
  11532. // If no initializer is specified for an object, and the
  11533. // object is of (possibly cv-qualified) non-POD class type (or
  11534. // array thereof), the object shall be default-initialized; if
  11535. // the object is of const-qualified type, the underlying class
  11536. // type shall have a user-declared default
  11537. // constructor. Otherwise, if no initializer is specified for
  11538. // a non- static object, the object and its subobjects, if
  11539. // any, have an indeterminate initial value); if the object
  11540. // or any of its subobjects are of const-qualified type, the
  11541. // program is ill-formed.
  11542. // C++0x [dcl.init]p11:
  11543. // If no initializer is specified for an object, the object is
  11544. // default-initialized; [...].
  11545. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  11546. InitializationKind Kind
  11547. = InitializationKind::CreateDefault(Var->getLocation());
  11548. InitializationSequence InitSeq(*this, Entity, Kind, None);
  11549. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  11550. if (Init.get()) {
  11551. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  11552. // This is important for template substitution.
  11553. Var->setInitStyle(VarDecl::CallInit);
  11554. } else if (Init.isInvalid()) {
  11555. // If default-init fails, attach a recovery-expr initializer to track
  11556. // that initialization was attempted and failed.
  11557. auto RecoveryExpr =
  11558. CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
  11559. if (RecoveryExpr.get())
  11560. Var->setInit(RecoveryExpr.get());
  11561. }
  11562. CheckCompleteVariableDeclaration(Var);
  11563. }
  11564. }
  11565. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  11566. // If there is no declaration, there was an error parsing it. Ignore it.
  11567. if (!D)
  11568. return;
  11569. VarDecl *VD = dyn_cast<VarDecl>(D);
  11570. if (!VD) {
  11571. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  11572. D->setInvalidDecl();
  11573. return;
  11574. }
  11575. VD->setCXXForRangeDecl(true);
  11576. // for-range-declaration cannot be given a storage class specifier.
  11577. int Error = -1;
  11578. switch (VD->getStorageClass()) {
  11579. case SC_None:
  11580. break;
  11581. case SC_Extern:
  11582. Error = 0;
  11583. break;
  11584. case SC_Static:
  11585. Error = 1;
  11586. break;
  11587. case SC_PrivateExtern:
  11588. Error = 2;
  11589. break;
  11590. case SC_Auto:
  11591. Error = 3;
  11592. break;
  11593. case SC_Register:
  11594. Error = 4;
  11595. break;
  11596. }
  11597. // for-range-declaration cannot be given a storage class specifier con't.
  11598. switch (VD->getTSCSpec()) {
  11599. case TSCS_thread_local:
  11600. Error = 6;
  11601. break;
  11602. case TSCS___thread:
  11603. case TSCS__Thread_local:
  11604. case TSCS_unspecified:
  11605. break;
  11606. }
  11607. if (Error != -1) {
  11608. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  11609. << VD << Error;
  11610. D->setInvalidDecl();
  11611. }
  11612. }
  11613. StmtResult
  11614. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  11615. IdentifierInfo *Ident,
  11616. ParsedAttributes &Attrs,
  11617. SourceLocation AttrEnd) {
  11618. // C++1y [stmt.iter]p1:
  11619. // A range-based for statement of the form
  11620. // for ( for-range-identifier : for-range-initializer ) statement
  11621. // is equivalent to
  11622. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  11623. DeclSpec DS(Attrs.getPool().getFactory());
  11624. const char *PrevSpec;
  11625. unsigned DiagID;
  11626. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  11627. getPrintingPolicy());
  11628. Declarator D(DS, DeclaratorContext::ForInit);
  11629. D.SetIdentifier(Ident, IdentLoc);
  11630. D.takeAttributes(Attrs, AttrEnd);
  11631. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  11632. IdentLoc);
  11633. Decl *Var = ActOnDeclarator(S, D);
  11634. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  11635. FinalizeDeclaration(Var);
  11636. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  11637. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  11638. }
  11639. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  11640. if (var->isInvalidDecl()) return;
  11641. MaybeAddCUDAConstantAttr(var);
  11642. if (getLangOpts().OpenCL) {
  11643. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  11644. // initialiser
  11645. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  11646. !var->hasInit()) {
  11647. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  11648. << 1 /*Init*/;
  11649. var->setInvalidDecl();
  11650. return;
  11651. }
  11652. }
  11653. // In Objective-C, don't allow jumps past the implicit initialization of a
  11654. // local retaining variable.
  11655. if (getLangOpts().ObjC &&
  11656. var->hasLocalStorage()) {
  11657. switch (var->getType().getObjCLifetime()) {
  11658. case Qualifiers::OCL_None:
  11659. case Qualifiers::OCL_ExplicitNone:
  11660. case Qualifiers::OCL_Autoreleasing:
  11661. break;
  11662. case Qualifiers::OCL_Weak:
  11663. case Qualifiers::OCL_Strong:
  11664. setFunctionHasBranchProtectedScope();
  11665. break;
  11666. }
  11667. }
  11668. if (var->hasLocalStorage() &&
  11669. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  11670. setFunctionHasBranchProtectedScope();
  11671. // Warn about externally-visible variables being defined without a
  11672. // prior declaration. We only want to do this for global
  11673. // declarations, but we also specifically need to avoid doing it for
  11674. // class members because the linkage of an anonymous class can
  11675. // change if it's later given a typedef name.
  11676. if (var->isThisDeclarationADefinition() &&
  11677. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  11678. var->isExternallyVisible() && var->hasLinkage() &&
  11679. !var->isInline() && !var->getDescribedVarTemplate() &&
  11680. !isa<VarTemplatePartialSpecializationDecl>(var) &&
  11681. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  11682. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  11683. var->getLocation())) {
  11684. // Find a previous declaration that's not a definition.
  11685. VarDecl *prev = var->getPreviousDecl();
  11686. while (prev && prev->isThisDeclarationADefinition())
  11687. prev = prev->getPreviousDecl();
  11688. if (!prev) {
  11689. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  11690. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  11691. << /* variable */ 0;
  11692. }
  11693. }
  11694. // Cache the result of checking for constant initialization.
  11695. Optional<bool> CacheHasConstInit;
  11696. const Expr *CacheCulprit = nullptr;
  11697. auto checkConstInit = [&]() mutable {
  11698. if (!CacheHasConstInit)
  11699. CacheHasConstInit = var->getInit()->isConstantInitializer(
  11700. Context, var->getType()->isReferenceType(), &CacheCulprit);
  11701. return *CacheHasConstInit;
  11702. };
  11703. if (var->getTLSKind() == VarDecl::TLS_Static) {
  11704. if (var->getType().isDestructedType()) {
  11705. // GNU C++98 edits for __thread, [basic.start.term]p3:
  11706. // The type of an object with thread storage duration shall not
  11707. // have a non-trivial destructor.
  11708. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  11709. if (getLangOpts().CPlusPlus11)
  11710. Diag(var->getLocation(), diag::note_use_thread_local);
  11711. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  11712. if (!checkConstInit()) {
  11713. // GNU C++98 edits for __thread, [basic.start.init]p4:
  11714. // An object of thread storage duration shall not require dynamic
  11715. // initialization.
  11716. // FIXME: Need strict checking here.
  11717. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  11718. << CacheCulprit->getSourceRange();
  11719. if (getLangOpts().CPlusPlus11)
  11720. Diag(var->getLocation(), diag::note_use_thread_local);
  11721. }
  11722. }
  11723. }
  11724. if (!var->getType()->isStructureType() && var->hasInit() &&
  11725. isa<InitListExpr>(var->getInit())) {
  11726. const auto *ILE = cast<InitListExpr>(var->getInit());
  11727. unsigned NumInits = ILE->getNumInits();
  11728. if (NumInits > 2)
  11729. for (unsigned I = 0; I < NumInits; ++I) {
  11730. const auto *Init = ILE->getInit(I);
  11731. if (!Init)
  11732. break;
  11733. const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
  11734. if (!SL)
  11735. break;
  11736. unsigned NumConcat = SL->getNumConcatenated();
  11737. // Diagnose missing comma in string array initialization.
  11738. // Do not warn when all the elements in the initializer are concatenated
  11739. // together. Do not warn for macros too.
  11740. if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
  11741. bool OnlyOneMissingComma = true;
  11742. for (unsigned J = I + 1; J < NumInits; ++J) {
  11743. const auto *Init = ILE->getInit(J);
  11744. if (!Init)
  11745. break;
  11746. const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
  11747. if (!SLJ || SLJ->getNumConcatenated() > 1) {
  11748. OnlyOneMissingComma = false;
  11749. break;
  11750. }
  11751. }
  11752. if (OnlyOneMissingComma) {
  11753. SmallVector<FixItHint, 1> Hints;
  11754. for (unsigned i = 0; i < NumConcat - 1; ++i)
  11755. Hints.push_back(FixItHint::CreateInsertion(
  11756. PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
  11757. Diag(SL->getStrTokenLoc(1),
  11758. diag::warn_concatenated_literal_array_init)
  11759. << Hints;
  11760. Diag(SL->getBeginLoc(),
  11761. diag::note_concatenated_string_literal_silence);
  11762. }
  11763. // In any case, stop now.
  11764. break;
  11765. }
  11766. }
  11767. }
  11768. QualType type = var->getType();
  11769. if (var->hasAttr<BlocksAttr>())
  11770. getCurFunction()->addByrefBlockVar(var);
  11771. Expr *Init = var->getInit();
  11772. bool GlobalStorage = var->hasGlobalStorage();
  11773. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  11774. QualType baseType = Context.getBaseElementType(type);
  11775. bool HasConstInit = true;
  11776. // Check whether the initializer is sufficiently constant.
  11777. if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
  11778. !Init->isValueDependent() &&
  11779. (GlobalStorage || var->isConstexpr() ||
  11780. var->mightBeUsableInConstantExpressions(Context))) {
  11781. // If this variable might have a constant initializer or might be usable in
  11782. // constant expressions, check whether or not it actually is now. We can't
  11783. // do this lazily, because the result might depend on things that change
  11784. // later, such as which constexpr functions happen to be defined.
  11785. SmallVector<PartialDiagnosticAt, 8> Notes;
  11786. if (!getLangOpts().CPlusPlus11) {
  11787. // Prior to C++11, in contexts where a constant initializer is required,
  11788. // the set of valid constant initializers is described by syntactic rules
  11789. // in [expr.const]p2-6.
  11790. // FIXME: Stricter checking for these rules would be useful for constinit /
  11791. // -Wglobal-constructors.
  11792. HasConstInit = checkConstInit();
  11793. // Compute and cache the constant value, and remember that we have a
  11794. // constant initializer.
  11795. if (HasConstInit) {
  11796. (void)var->checkForConstantInitialization(Notes);
  11797. Notes.clear();
  11798. } else if (CacheCulprit) {
  11799. Notes.emplace_back(CacheCulprit->getExprLoc(),
  11800. PDiag(diag::note_invalid_subexpr_in_const_expr));
  11801. Notes.back().second << CacheCulprit->getSourceRange();
  11802. }
  11803. } else {
  11804. // Evaluate the initializer to see if it's a constant initializer.
  11805. HasConstInit = var->checkForConstantInitialization(Notes);
  11806. }
  11807. if (HasConstInit) {
  11808. // FIXME: Consider replacing the initializer with a ConstantExpr.
  11809. } else if (var->isConstexpr()) {
  11810. SourceLocation DiagLoc = var->getLocation();
  11811. // If the note doesn't add any useful information other than a source
  11812. // location, fold it into the primary diagnostic.
  11813. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  11814. diag::note_invalid_subexpr_in_const_expr) {
  11815. DiagLoc = Notes[0].first;
  11816. Notes.clear();
  11817. }
  11818. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  11819. << var << Init->getSourceRange();
  11820. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  11821. Diag(Notes[I].first, Notes[I].second);
  11822. } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  11823. auto *Attr = var->getAttr<ConstInitAttr>();
  11824. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  11825. << Init->getSourceRange();
  11826. Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
  11827. << Attr->getRange() << Attr->isConstinit();
  11828. for (auto &it : Notes)
  11829. Diag(it.first, it.second);
  11830. } else if (IsGlobal &&
  11831. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  11832. var->getLocation())) {
  11833. // Warn about globals which don't have a constant initializer. Don't
  11834. // warn about globals with a non-trivial destructor because we already
  11835. // warned about them.
  11836. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  11837. if (!(RD && !RD->hasTrivialDestructor())) {
  11838. // checkConstInit() here permits trivial default initialization even in
  11839. // C++11 onwards, where such an initializer is not a constant initializer
  11840. // but nonetheless doesn't require a global constructor.
  11841. if (!checkConstInit())
  11842. Diag(var->getLocation(), diag::warn_global_constructor)
  11843. << Init->getSourceRange();
  11844. }
  11845. }
  11846. }
  11847. // Apply section attributes and pragmas to global variables.
  11848. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  11849. !inTemplateInstantiation()) {
  11850. PragmaStack<StringLiteral *> *Stack = nullptr;
  11851. int SectionFlags = ASTContext::PSF_Read;
  11852. if (var->getType().isConstQualified()) {
  11853. if (HasConstInit)
  11854. Stack = &ConstSegStack;
  11855. else {
  11856. Stack = &BSSSegStack;
  11857. SectionFlags |= ASTContext::PSF_Write;
  11858. }
  11859. } else if (var->hasInit() && HasConstInit) {
  11860. Stack = &DataSegStack;
  11861. SectionFlags |= ASTContext::PSF_Write;
  11862. } else {
  11863. Stack = &BSSSegStack;
  11864. SectionFlags |= ASTContext::PSF_Write;
  11865. }
  11866. if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
  11867. if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
  11868. SectionFlags |= ASTContext::PSF_Implicit;
  11869. UnifySection(SA->getName(), SectionFlags, var);
  11870. } else if (Stack->CurrentValue) {
  11871. SectionFlags |= ASTContext::PSF_Implicit;
  11872. auto SectionName = Stack->CurrentValue->getString();
  11873. var->addAttr(SectionAttr::CreateImplicit(
  11874. Context, SectionName, Stack->CurrentPragmaLocation,
  11875. AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
  11876. if (UnifySection(SectionName, SectionFlags, var))
  11877. var->dropAttr<SectionAttr>();
  11878. }
  11879. // Apply the init_seg attribute if this has an initializer. If the
  11880. // initializer turns out to not be dynamic, we'll end up ignoring this
  11881. // attribute.
  11882. if (CurInitSeg && var->getInit())
  11883. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  11884. CurInitSegLoc,
  11885. AttributeCommonInfo::AS_Pragma));
  11886. }
  11887. // All the following checks are C++ only.
  11888. if (!getLangOpts().CPlusPlus) {
  11889. // If this variable must be emitted, add it as an initializer for the
  11890. // current module.
  11891. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11892. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11893. return;
  11894. }
  11895. // Require the destructor.
  11896. if (!type->isDependentType())
  11897. if (const RecordType *recordType = baseType->getAs<RecordType>())
  11898. FinalizeVarWithDestructor(var, recordType);
  11899. // If this variable must be emitted, add it as an initializer for the current
  11900. // module.
  11901. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  11902. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  11903. // Build the bindings if this is a structured binding declaration.
  11904. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  11905. CheckCompleteDecompositionDeclaration(DD);
  11906. }
  11907. /// Check if VD needs to be dllexport/dllimport due to being in a
  11908. /// dllexport/import function.
  11909. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  11910. assert(VD->isStaticLocal());
  11911. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  11912. // Find outermost function when VD is in lambda function.
  11913. while (FD && !getDLLAttr(FD) &&
  11914. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  11915. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  11916. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  11917. }
  11918. if (!FD)
  11919. return;
  11920. // Static locals inherit dll attributes from their function.
  11921. if (Attr *A = getDLLAttr(FD)) {
  11922. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  11923. NewAttr->setInherited(true);
  11924. VD->addAttr(NewAttr);
  11925. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  11926. auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
  11927. NewAttr->setInherited(true);
  11928. VD->addAttr(NewAttr);
  11929. // Export this function to enforce exporting this static variable even
  11930. // if it is not used in this compilation unit.
  11931. if (!FD->hasAttr<DLLExportAttr>())
  11932. FD->addAttr(NewAttr);
  11933. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  11934. auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
  11935. NewAttr->setInherited(true);
  11936. VD->addAttr(NewAttr);
  11937. }
  11938. }
  11939. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  11940. /// any semantic actions necessary after any initializer has been attached.
  11941. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  11942. // Note that we are no longer parsing the initializer for this declaration.
  11943. ParsingInitForAutoVars.erase(ThisDecl);
  11944. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  11945. if (!VD)
  11946. return;
  11947. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  11948. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  11949. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  11950. if (PragmaClangBSSSection.Valid)
  11951. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
  11952. Context, PragmaClangBSSSection.SectionName,
  11953. PragmaClangBSSSection.PragmaLocation,
  11954. AttributeCommonInfo::AS_Pragma));
  11955. if (PragmaClangDataSection.Valid)
  11956. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
  11957. Context, PragmaClangDataSection.SectionName,
  11958. PragmaClangDataSection.PragmaLocation,
  11959. AttributeCommonInfo::AS_Pragma));
  11960. if (PragmaClangRodataSection.Valid)
  11961. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
  11962. Context, PragmaClangRodataSection.SectionName,
  11963. PragmaClangRodataSection.PragmaLocation,
  11964. AttributeCommonInfo::AS_Pragma));
  11965. if (PragmaClangRelroSection.Valid)
  11966. VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
  11967. Context, PragmaClangRelroSection.SectionName,
  11968. PragmaClangRelroSection.PragmaLocation,
  11969. AttributeCommonInfo::AS_Pragma));
  11970. }
  11971. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  11972. for (auto *BD : DD->bindings()) {
  11973. FinalizeDeclaration(BD);
  11974. }
  11975. }
  11976. checkAttributesAfterMerging(*this, *VD);
  11977. // Perform TLS alignment check here after attributes attached to the variable
  11978. // which may affect the alignment have been processed. Only perform the check
  11979. // if the target has a maximum TLS alignment (zero means no constraints).
  11980. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  11981. // Protect the check so that it's not performed on dependent types and
  11982. // dependent alignments (we can't determine the alignment in that case).
  11983. if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
  11984. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  11985. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  11986. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  11987. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  11988. << (unsigned)MaxAlignChars.getQuantity();
  11989. }
  11990. }
  11991. }
  11992. if (VD->isStaticLocal())
  11993. CheckStaticLocalForDllExport(VD);
  11994. // Perform check for initializers of device-side global variables.
  11995. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  11996. // 7.5). We must also apply the same checks to all __shared__
  11997. // variables whether they are local or not. CUDA also allows
  11998. // constant initializers for __constant__ and __device__ variables.
  11999. if (getLangOpts().CUDA)
  12000. checkAllowedCUDAInitializer(VD);
  12001. // Grab the dllimport or dllexport attribute off of the VarDecl.
  12002. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  12003. // Imported static data members cannot be defined out-of-line.
  12004. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  12005. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  12006. VD->isThisDeclarationADefinition()) {
  12007. // We allow definitions of dllimport class template static data members
  12008. // with a warning.
  12009. CXXRecordDecl *Context =
  12010. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  12011. bool IsClassTemplateMember =
  12012. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  12013. Context->getDescribedClassTemplate();
  12014. Diag(VD->getLocation(),
  12015. IsClassTemplateMember
  12016. ? diag::warn_attribute_dllimport_static_field_definition
  12017. : diag::err_attribute_dllimport_static_field_definition);
  12018. Diag(IA->getLocation(), diag::note_attribute);
  12019. if (!IsClassTemplateMember)
  12020. VD->setInvalidDecl();
  12021. }
  12022. }
  12023. // dllimport/dllexport variables cannot be thread local, their TLS index
  12024. // isn't exported with the variable.
  12025. if (DLLAttr && VD->getTLSKind()) {
  12026. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  12027. if (F && getDLLAttr(F)) {
  12028. assert(VD->isStaticLocal());
  12029. // But if this is a static local in a dlimport/dllexport function, the
  12030. // function will never be inlined, which means the var would never be
  12031. // imported, so having it marked import/export is safe.
  12032. } else {
  12033. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  12034. << DLLAttr;
  12035. VD->setInvalidDecl();
  12036. }
  12037. }
  12038. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  12039. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  12040. Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
  12041. << Attr;
  12042. VD->dropAttr<UsedAttr>();
  12043. }
  12044. }
  12045. if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
  12046. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  12047. Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
  12048. << Attr;
  12049. VD->dropAttr<RetainAttr>();
  12050. }
  12051. }
  12052. const DeclContext *DC = VD->getDeclContext();
  12053. // If there's a #pragma GCC visibility in scope, and this isn't a class
  12054. // member, set the visibility of this variable.
  12055. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  12056. AddPushedVisibilityAttribute(VD);
  12057. // FIXME: Warn on unused var template partial specializations.
  12058. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  12059. MarkUnusedFileScopedDecl(VD);
  12060. // Now we have parsed the initializer and can update the table of magic
  12061. // tag values.
  12062. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  12063. !VD->getType()->isIntegralOrEnumerationType())
  12064. return;
  12065. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  12066. const Expr *MagicValueExpr = VD->getInit();
  12067. if (!MagicValueExpr) {
  12068. continue;
  12069. }
  12070. Optional<llvm::APSInt> MagicValueInt;
  12071. if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
  12072. Diag(I->getRange().getBegin(),
  12073. diag::err_type_tag_for_datatype_not_ice)
  12074. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  12075. continue;
  12076. }
  12077. if (MagicValueInt->getActiveBits() > 64) {
  12078. Diag(I->getRange().getBegin(),
  12079. diag::err_type_tag_for_datatype_too_large)
  12080. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  12081. continue;
  12082. }
  12083. uint64_t MagicValue = MagicValueInt->getZExtValue();
  12084. RegisterTypeTagForDatatype(I->getArgumentKind(),
  12085. MagicValue,
  12086. I->getMatchingCType(),
  12087. I->getLayoutCompatible(),
  12088. I->getMustBeNull());
  12089. }
  12090. }
  12091. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  12092. auto *VD = dyn_cast<VarDecl>(DD);
  12093. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  12094. }
  12095. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  12096. ArrayRef<Decl *> Group) {
  12097. SmallVector<Decl*, 8> Decls;
  12098. if (DS.isTypeSpecOwned())
  12099. Decls.push_back(DS.getRepAsDecl());
  12100. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  12101. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  12102. bool DiagnosedMultipleDecomps = false;
  12103. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  12104. bool DiagnosedNonDeducedAuto = false;
  12105. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  12106. if (Decl *D = Group[i]) {
  12107. // For declarators, there are some additional syntactic-ish checks we need
  12108. // to perform.
  12109. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  12110. if (!FirstDeclaratorInGroup)
  12111. FirstDeclaratorInGroup = DD;
  12112. if (!FirstDecompDeclaratorInGroup)
  12113. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  12114. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  12115. !hasDeducedAuto(DD))
  12116. FirstNonDeducedAutoInGroup = DD;
  12117. if (FirstDeclaratorInGroup != DD) {
  12118. // A decomposition declaration cannot be combined with any other
  12119. // declaration in the same group.
  12120. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  12121. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  12122. diag::err_decomp_decl_not_alone)
  12123. << FirstDeclaratorInGroup->getSourceRange()
  12124. << DD->getSourceRange();
  12125. DiagnosedMultipleDecomps = true;
  12126. }
  12127. // A declarator that uses 'auto' in any way other than to declare a
  12128. // variable with a deduced type cannot be combined with any other
  12129. // declarator in the same group.
  12130. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  12131. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  12132. diag::err_auto_non_deduced_not_alone)
  12133. << FirstNonDeducedAutoInGroup->getType()
  12134. ->hasAutoForTrailingReturnType()
  12135. << FirstDeclaratorInGroup->getSourceRange()
  12136. << DD->getSourceRange();
  12137. DiagnosedNonDeducedAuto = true;
  12138. }
  12139. }
  12140. }
  12141. Decls.push_back(D);
  12142. }
  12143. }
  12144. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  12145. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  12146. handleTagNumbering(Tag, S);
  12147. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  12148. getLangOpts().CPlusPlus)
  12149. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  12150. }
  12151. }
  12152. return BuildDeclaratorGroup(Decls);
  12153. }
  12154. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  12155. /// group, performing any necessary semantic checking.
  12156. Sema::DeclGroupPtrTy
  12157. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  12158. // C++14 [dcl.spec.auto]p7: (DR1347)
  12159. // If the type that replaces the placeholder type is not the same in each
  12160. // deduction, the program is ill-formed.
  12161. if (Group.size() > 1) {
  12162. QualType Deduced;
  12163. VarDecl *DeducedDecl = nullptr;
  12164. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  12165. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  12166. if (!D || D->isInvalidDecl())
  12167. break;
  12168. DeducedType *DT = D->getType()->getContainedDeducedType();
  12169. if (!DT || DT->getDeducedType().isNull())
  12170. continue;
  12171. if (Deduced.isNull()) {
  12172. Deduced = DT->getDeducedType();
  12173. DeducedDecl = D;
  12174. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  12175. auto *AT = dyn_cast<AutoType>(DT);
  12176. auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  12177. diag::err_auto_different_deductions)
  12178. << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
  12179. << DeducedDecl->getDeclName() << DT->getDeducedType()
  12180. << D->getDeclName();
  12181. if (DeducedDecl->hasInit())
  12182. Dia << DeducedDecl->getInit()->getSourceRange();
  12183. if (D->getInit())
  12184. Dia << D->getInit()->getSourceRange();
  12185. D->setInvalidDecl();
  12186. break;
  12187. }
  12188. }
  12189. }
  12190. ActOnDocumentableDecls(Group);
  12191. return DeclGroupPtrTy::make(
  12192. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  12193. }
  12194. void Sema::ActOnDocumentableDecl(Decl *D) {
  12195. ActOnDocumentableDecls(D);
  12196. }
  12197. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  12198. // Don't parse the comment if Doxygen diagnostics are ignored.
  12199. if (Group.empty() || !Group[0])
  12200. return;
  12201. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  12202. Group[0]->getLocation()) &&
  12203. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  12204. Group[0]->getLocation()))
  12205. return;
  12206. if (Group.size() >= 2) {
  12207. // This is a decl group. Normally it will contain only declarations
  12208. // produced from declarator list. But in case we have any definitions or
  12209. // additional declaration references:
  12210. // 'typedef struct S {} S;'
  12211. // 'typedef struct S *S;'
  12212. // 'struct S *pS;'
  12213. // FinalizeDeclaratorGroup adds these as separate declarations.
  12214. Decl *MaybeTagDecl = Group[0];
  12215. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  12216. Group = Group.slice(1);
  12217. }
  12218. }
  12219. // FIMXE: We assume every Decl in the group is in the same file.
  12220. // This is false when preprocessor constructs the group from decls in
  12221. // different files (e. g. macros or #include).
  12222. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  12223. }
  12224. /// Common checks for a parameter-declaration that should apply to both function
  12225. /// parameters and non-type template parameters.
  12226. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  12227. // Check that there are no default arguments inside the type of this
  12228. // parameter.
  12229. if (getLangOpts().CPlusPlus)
  12230. CheckExtraCXXDefaultArguments(D);
  12231. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  12232. if (D.getCXXScopeSpec().isSet()) {
  12233. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  12234. << D.getCXXScopeSpec().getRange();
  12235. }
  12236. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  12237. // simple identifier except [...irrelevant cases...].
  12238. switch (D.getName().getKind()) {
  12239. case UnqualifiedIdKind::IK_Identifier:
  12240. break;
  12241. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12242. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12243. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12244. case UnqualifiedIdKind::IK_ConstructorName:
  12245. case UnqualifiedIdKind::IK_DestructorName:
  12246. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12247. case UnqualifiedIdKind::IK_DeductionGuideName:
  12248. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  12249. << GetNameForDeclarator(D).getName();
  12250. break;
  12251. case UnqualifiedIdKind::IK_TemplateId:
  12252. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12253. // GetNameForDeclarator would not produce a useful name in this case.
  12254. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  12255. break;
  12256. }
  12257. }
  12258. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  12259. /// to introduce parameters into function prototype scope.
  12260. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  12261. const DeclSpec &DS = D.getDeclSpec();
  12262. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  12263. // C++03 [dcl.stc]p2 also permits 'auto'.
  12264. StorageClass SC = SC_None;
  12265. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  12266. SC = SC_Register;
  12267. // In C++11, the 'register' storage class specifier is deprecated.
  12268. // In C++17, it is not allowed, but we tolerate it as an extension.
  12269. if (getLangOpts().CPlusPlus11) {
  12270. Diag(DS.getStorageClassSpecLoc(),
  12271. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  12272. : diag::warn_deprecated_register)
  12273. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  12274. }
  12275. } else if (getLangOpts().CPlusPlus &&
  12276. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  12277. SC = SC_Auto;
  12278. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  12279. Diag(DS.getStorageClassSpecLoc(),
  12280. diag::err_invalid_storage_class_in_func_decl);
  12281. D.getMutableDeclSpec().ClearStorageClassSpecs();
  12282. }
  12283. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  12284. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  12285. << DeclSpec::getSpecifierName(TSCS);
  12286. if (DS.isInlineSpecified())
  12287. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  12288. << getLangOpts().CPlusPlus17;
  12289. if (DS.hasConstexprSpecifier())
  12290. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  12291. << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  12292. DiagnoseFunctionSpecifiers(DS);
  12293. CheckFunctionOrTemplateParamDeclarator(S, D);
  12294. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12295. QualType parmDeclType = TInfo->getType();
  12296. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  12297. IdentifierInfo *II = D.getIdentifier();
  12298. if (II) {
  12299. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  12300. ForVisibleRedeclaration);
  12301. LookupName(R, S);
  12302. if (R.isSingleResult()) {
  12303. NamedDecl *PrevDecl = R.getFoundDecl();
  12304. if (PrevDecl->isTemplateParameter()) {
  12305. // Maybe we will complain about the shadowed template parameter.
  12306. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12307. // Just pretend that we didn't see the previous declaration.
  12308. PrevDecl = nullptr;
  12309. } else if (S->isDeclScope(PrevDecl)) {
  12310. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  12311. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12312. // Recover by removing the name
  12313. II = nullptr;
  12314. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  12315. D.setInvalidType(true);
  12316. }
  12317. }
  12318. }
  12319. // Temporarily put parameter variables in the translation unit, not
  12320. // the enclosing context. This prevents them from accidentally
  12321. // looking like class members in C++.
  12322. ParmVarDecl *New =
  12323. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  12324. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  12325. if (D.isInvalidType())
  12326. New->setInvalidDecl();
  12327. assert(S->isFunctionPrototypeScope());
  12328. assert(S->getFunctionPrototypeDepth() >= 1);
  12329. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  12330. S->getNextFunctionPrototypeIndex());
  12331. // Add the parameter declaration into this scope.
  12332. S->AddDecl(New);
  12333. if (II)
  12334. IdResolver.AddDecl(New);
  12335. ProcessDeclAttributes(S, New, D);
  12336. if (D.getDeclSpec().isModulePrivateSpecified())
  12337. Diag(New->getLocation(), diag::err_module_private_local)
  12338. << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12339. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12340. if (New->hasAttr<BlocksAttr>()) {
  12341. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  12342. }
  12343. if (getLangOpts().OpenCL)
  12344. deduceOpenCLAddressSpace(New);
  12345. return New;
  12346. }
  12347. /// Synthesizes a variable for a parameter arising from a
  12348. /// typedef.
  12349. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  12350. SourceLocation Loc,
  12351. QualType T) {
  12352. /* FIXME: setting StartLoc == Loc.
  12353. Would it be worth to modify callers so as to provide proper source
  12354. location for the unnamed parameters, embedding the parameter's type? */
  12355. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  12356. T, Context.getTrivialTypeSourceInfo(T, Loc),
  12357. SC_None, nullptr);
  12358. Param->setImplicit();
  12359. return Param;
  12360. }
  12361. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  12362. // Don't diagnose unused-parameter errors in template instantiations; we
  12363. // will already have done so in the template itself.
  12364. if (inTemplateInstantiation())
  12365. return;
  12366. for (const ParmVarDecl *Parameter : Parameters) {
  12367. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  12368. !Parameter->hasAttr<UnusedAttr>()) {
  12369. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  12370. << Parameter->getDeclName();
  12371. }
  12372. }
  12373. }
  12374. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  12375. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  12376. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  12377. return;
  12378. // Warn if the return value is pass-by-value and larger than the specified
  12379. // threshold.
  12380. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  12381. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  12382. if (Size > LangOpts.NumLargeByValueCopy)
  12383. Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
  12384. }
  12385. // Warn if any parameter is pass-by-value and larger than the specified
  12386. // threshold.
  12387. for (const ParmVarDecl *Parameter : Parameters) {
  12388. QualType T = Parameter->getType();
  12389. if (T->isDependentType() || !T.isPODType(Context))
  12390. continue;
  12391. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  12392. if (Size > LangOpts.NumLargeByValueCopy)
  12393. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  12394. << Parameter << Size;
  12395. }
  12396. }
  12397. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  12398. SourceLocation NameLoc, IdentifierInfo *Name,
  12399. QualType T, TypeSourceInfo *TSInfo,
  12400. StorageClass SC) {
  12401. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  12402. if (getLangOpts().ObjCAutoRefCount &&
  12403. T.getObjCLifetime() == Qualifiers::OCL_None &&
  12404. T->isObjCLifetimeType()) {
  12405. Qualifiers::ObjCLifetime lifetime;
  12406. // Special cases for arrays:
  12407. // - if it's const, use __unsafe_unretained
  12408. // - otherwise, it's an error
  12409. if (T->isArrayType()) {
  12410. if (!T.isConstQualified()) {
  12411. if (DelayedDiagnostics.shouldDelayDiagnostics())
  12412. DelayedDiagnostics.add(
  12413. sema::DelayedDiagnostic::makeForbiddenType(
  12414. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  12415. else
  12416. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  12417. << TSInfo->getTypeLoc().getSourceRange();
  12418. }
  12419. lifetime = Qualifiers::OCL_ExplicitNone;
  12420. } else {
  12421. lifetime = T->getObjCARCImplicitLifetime();
  12422. }
  12423. T = Context.getLifetimeQualifiedType(T, lifetime);
  12424. }
  12425. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  12426. Context.getAdjustedParameterType(T),
  12427. TSInfo, SC, nullptr);
  12428. // Make a note if we created a new pack in the scope of a lambda, so that
  12429. // we know that references to that pack must also be expanded within the
  12430. // lambda scope.
  12431. if (New->isParameterPack())
  12432. if (auto *LSI = getEnclosingLambda())
  12433. LSI->LocalPacks.push_back(New);
  12434. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  12435. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  12436. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  12437. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  12438. // Parameters can not be abstract class types.
  12439. // For record types, this is done by the AbstractClassUsageDiagnoser once
  12440. // the class has been completely parsed.
  12441. if (!CurContext->isRecord() &&
  12442. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  12443. AbstractParamType))
  12444. New->setInvalidDecl();
  12445. // Parameter declarators cannot be interface types. All ObjC objects are
  12446. // passed by reference.
  12447. if (T->isObjCObjectType()) {
  12448. SourceLocation TypeEndLoc =
  12449. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  12450. Diag(NameLoc,
  12451. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  12452. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  12453. T = Context.getObjCObjectPointerType(T);
  12454. New->setType(T);
  12455. }
  12456. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  12457. // duration shall not be qualified by an address-space qualifier."
  12458. // Since all parameters have automatic store duration, they can not have
  12459. // an address space.
  12460. if (T.getAddressSpace() != LangAS::Default &&
  12461. // OpenCL allows function arguments declared to be an array of a type
  12462. // to be qualified with an address space.
  12463. !(getLangOpts().OpenCL &&
  12464. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  12465. Diag(NameLoc, diag::err_arg_with_address_space);
  12466. New->setInvalidDecl();
  12467. }
  12468. // PPC MMA non-pointer types are not allowed as function argument types.
  12469. if (Context.getTargetInfo().getTriple().isPPC64() &&
  12470. CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
  12471. New->setInvalidDecl();
  12472. }
  12473. return New;
  12474. }
  12475. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  12476. SourceLocation LocAfterDecls) {
  12477. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  12478. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  12479. // for a K&R function.
  12480. if (!FTI.hasPrototype) {
  12481. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  12482. --i;
  12483. if (FTI.Params[i].Param == nullptr) {
  12484. SmallString<256> Code;
  12485. llvm::raw_svector_ostream(Code)
  12486. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  12487. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  12488. << FTI.Params[i].Ident
  12489. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  12490. // Implicitly declare the argument as type 'int' for lack of a better
  12491. // type.
  12492. AttributeFactory attrs;
  12493. DeclSpec DS(attrs);
  12494. const char* PrevSpec; // unused
  12495. unsigned DiagID; // unused
  12496. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  12497. DiagID, Context.getPrintingPolicy());
  12498. // Use the identifier location for the type source range.
  12499. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  12500. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  12501. Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
  12502. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  12503. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  12504. }
  12505. }
  12506. }
  12507. }
  12508. Decl *
  12509. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  12510. MultiTemplateParamsArg TemplateParameterLists,
  12511. SkipBodyInfo *SkipBody) {
  12512. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  12513. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  12514. Scope *ParentScope = FnBodyScope->getParent();
  12515. // Check if we are in an `omp begin/end declare variant` scope. If we are, and
  12516. // we define a non-templated function definition, we will create a declaration
  12517. // instead (=BaseFD), and emit the definition with a mangled name afterwards.
  12518. // The base function declaration will have the equivalent of an `omp declare
  12519. // variant` annotation which specifies the mangled definition as a
  12520. // specialization function under the OpenMP context defined as part of the
  12521. // `omp begin declare variant`.
  12522. SmallVector<FunctionDecl *, 4> Bases;
  12523. if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
  12524. ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
  12525. ParentScope, D, TemplateParameterLists, Bases);
  12526. D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
  12527. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  12528. Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  12529. if (!Bases.empty())
  12530. ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
  12531. return Dcl;
  12532. }
  12533. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  12534. Consumer.HandleInlineFunctionDefinition(D);
  12535. }
  12536. static bool
  12537. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  12538. const FunctionDecl *&PossiblePrototype) {
  12539. // Don't warn about invalid declarations.
  12540. if (FD->isInvalidDecl())
  12541. return false;
  12542. // Or declarations that aren't global.
  12543. if (!FD->isGlobal())
  12544. return false;
  12545. if (!FD->isExternallyVisible())
  12546. return false;
  12547. // Don't warn about C++ member functions.
  12548. if (isa<CXXMethodDecl>(FD))
  12549. return false;
  12550. // Don't warn about 'main'.
  12551. if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
  12552. if (IdentifierInfo *II = FD->getIdentifier())
  12553. if (II->isStr("main") || II->isStr("efi_main"))
  12554. return false;
  12555. // Don't warn about inline functions.
  12556. if (FD->isInlined())
  12557. return false;
  12558. // Don't warn about function templates.
  12559. if (FD->getDescribedFunctionTemplate())
  12560. return false;
  12561. // Don't warn about function template specializations.
  12562. if (FD->isFunctionTemplateSpecialization())
  12563. return false;
  12564. // Don't warn for OpenCL kernels.
  12565. if (FD->hasAttr<OpenCLKernelAttr>())
  12566. return false;
  12567. // Don't warn on explicitly deleted functions.
  12568. if (FD->isDeleted())
  12569. return false;
  12570. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  12571. Prev; Prev = Prev->getPreviousDecl()) {
  12572. // Ignore any declarations that occur in function or method
  12573. // scope, because they aren't visible from the header.
  12574. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  12575. continue;
  12576. PossiblePrototype = Prev;
  12577. return Prev->getType()->isFunctionNoProtoType();
  12578. }
  12579. return true;
  12580. }
  12581. void
  12582. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  12583. const FunctionDecl *EffectiveDefinition,
  12584. SkipBodyInfo *SkipBody) {
  12585. const FunctionDecl *Definition = EffectiveDefinition;
  12586. if (!Definition &&
  12587. !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
  12588. return;
  12589. if (Definition->getFriendObjectKind() != Decl::FOK_None) {
  12590. if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
  12591. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  12592. // A merged copy of the same function, instantiated as a member of
  12593. // the same class, is OK.
  12594. if (declaresSameEntity(OrigFD, OrigDef) &&
  12595. declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
  12596. cast<Decl>(FD->getLexicalDeclContext())))
  12597. return;
  12598. }
  12599. }
  12600. }
  12601. if (canRedefineFunction(Definition, getLangOpts()))
  12602. return;
  12603. // Don't emit an error when this is redefinition of a typo-corrected
  12604. // definition.
  12605. if (TypoCorrectedFunctionDefinitions.count(Definition))
  12606. return;
  12607. // If we don't have a visible definition of the function, and it's inline or
  12608. // a template, skip the new definition.
  12609. if (SkipBody && !hasVisibleDefinition(Definition) &&
  12610. (Definition->getFormalLinkage() == InternalLinkage ||
  12611. Definition->isInlined() ||
  12612. Definition->getDescribedFunctionTemplate() ||
  12613. Definition->getNumTemplateParameterLists())) {
  12614. SkipBody->ShouldSkip = true;
  12615. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  12616. if (auto *TD = Definition->getDescribedFunctionTemplate())
  12617. makeMergedDefinitionVisible(TD);
  12618. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  12619. return;
  12620. }
  12621. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  12622. Definition->getStorageClass() == SC_Extern)
  12623. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  12624. << FD << getLangOpts().CPlusPlus;
  12625. else
  12626. Diag(FD->getLocation(), diag::err_redefinition) << FD;
  12627. Diag(Definition->getLocation(), diag::note_previous_definition);
  12628. FD->setInvalidDecl();
  12629. }
  12630. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  12631. Sema &S) {
  12632. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  12633. LambdaScopeInfo *LSI = S.PushLambdaScope();
  12634. LSI->CallOperator = CallOperator;
  12635. LSI->Lambda = LambdaClass;
  12636. LSI->ReturnType = CallOperator->getReturnType();
  12637. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  12638. if (LCD == LCD_None)
  12639. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  12640. else if (LCD == LCD_ByCopy)
  12641. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  12642. else if (LCD == LCD_ByRef)
  12643. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  12644. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  12645. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  12646. LSI->Mutable = !CallOperator->isConst();
  12647. // Add the captures to the LSI so they can be noted as already
  12648. // captured within tryCaptureVar.
  12649. auto I = LambdaClass->field_begin();
  12650. for (const auto &C : LambdaClass->captures()) {
  12651. if (C.capturesVariable()) {
  12652. VarDecl *VD = C.getCapturedVar();
  12653. if (VD->isInitCapture())
  12654. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  12655. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  12656. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  12657. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  12658. /*EllipsisLoc*/C.isPackExpansion()
  12659. ? C.getEllipsisLoc() : SourceLocation(),
  12660. I->getType(), /*Invalid*/false);
  12661. } else if (C.capturesThis()) {
  12662. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  12663. C.getCaptureKind() == LCK_StarThis);
  12664. } else {
  12665. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  12666. I->getType());
  12667. }
  12668. ++I;
  12669. }
  12670. }
  12671. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  12672. SkipBodyInfo *SkipBody) {
  12673. if (!D) {
  12674. // Parsing the function declaration failed in some way. Push on a fake scope
  12675. // anyway so we can try to parse the function body.
  12676. PushFunctionScope();
  12677. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  12678. return D;
  12679. }
  12680. FunctionDecl *FD = nullptr;
  12681. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  12682. FD = FunTmpl->getTemplatedDecl();
  12683. else
  12684. FD = cast<FunctionDecl>(D);
  12685. // Do not push if it is a lambda because one is already pushed when building
  12686. // the lambda in ActOnStartOfLambdaDefinition().
  12687. if (!isLambdaCallOperator(FD))
  12688. PushExpressionEvaluationContext(
  12689. FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
  12690. : ExprEvalContexts.back().Context);
  12691. // Check for defining attributes before the check for redefinition.
  12692. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  12693. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  12694. FD->dropAttr<AliasAttr>();
  12695. FD->setInvalidDecl();
  12696. }
  12697. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  12698. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  12699. FD->dropAttr<IFuncAttr>();
  12700. FD->setInvalidDecl();
  12701. }
  12702. if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
  12703. if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  12704. Ctor->isDefaultConstructor() &&
  12705. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12706. // If this is an MS ABI dllexport default constructor, instantiate any
  12707. // default arguments.
  12708. InstantiateDefaultCtorDefaultArgs(Ctor);
  12709. }
  12710. }
  12711. // See if this is a redefinition. If 'will have body' (or similar) is already
  12712. // set, then these checks were already performed when it was set.
  12713. if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
  12714. !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
  12715. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  12716. // If we're skipping the body, we're done. Don't enter the scope.
  12717. if (SkipBody && SkipBody->ShouldSkip)
  12718. return D;
  12719. }
  12720. // Mark this function as "will have a body eventually". This lets users to
  12721. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  12722. // this function.
  12723. FD->setWillHaveBody();
  12724. // If we are instantiating a generic lambda call operator, push
  12725. // a LambdaScopeInfo onto the function stack. But use the information
  12726. // that's already been calculated (ActOnLambdaExpr) to prime the current
  12727. // LambdaScopeInfo.
  12728. // When the template operator is being specialized, the LambdaScopeInfo,
  12729. // has to be properly restored so that tryCaptureVariable doesn't try
  12730. // and capture any new variables. In addition when calculating potential
  12731. // captures during transformation of nested lambdas, it is necessary to
  12732. // have the LSI properly restored.
  12733. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  12734. assert(inTemplateInstantiation() &&
  12735. "There should be an active template instantiation on the stack "
  12736. "when instantiating a generic lambda!");
  12737. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  12738. } else {
  12739. // Enter a new function scope
  12740. PushFunctionScope();
  12741. }
  12742. // Builtin functions cannot be defined.
  12743. if (unsigned BuiltinID = FD->getBuiltinID()) {
  12744. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  12745. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  12746. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  12747. FD->setInvalidDecl();
  12748. }
  12749. }
  12750. // The return type of a function definition must be complete
  12751. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  12752. QualType ResultType = FD->getReturnType();
  12753. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  12754. !FD->isInvalidDecl() &&
  12755. RequireCompleteType(FD->getLocation(), ResultType,
  12756. diag::err_func_def_incomplete_result))
  12757. FD->setInvalidDecl();
  12758. if (FnBodyScope)
  12759. PushDeclContext(FnBodyScope, FD);
  12760. // Check the validity of our function parameters
  12761. CheckParmsForFunctionDef(FD->parameters(),
  12762. /*CheckParameterNames=*/true);
  12763. // Add non-parameter declarations already in the function to the current
  12764. // scope.
  12765. if (FnBodyScope) {
  12766. for (Decl *NPD : FD->decls()) {
  12767. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  12768. if (!NonParmDecl)
  12769. continue;
  12770. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  12771. "parameters should not be in newly created FD yet");
  12772. // If the decl has a name, make it accessible in the current scope.
  12773. if (NonParmDecl->getDeclName())
  12774. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  12775. // Similarly, dive into enums and fish their constants out, making them
  12776. // accessible in this scope.
  12777. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  12778. for (auto *EI : ED->enumerators())
  12779. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  12780. }
  12781. }
  12782. }
  12783. // Introduce our parameters into the function scope
  12784. for (auto Param : FD->parameters()) {
  12785. Param->setOwningFunction(FD);
  12786. // If this has an identifier, add it to the scope stack.
  12787. if (Param->getIdentifier() && FnBodyScope) {
  12788. CheckShadow(FnBodyScope, Param);
  12789. PushOnScopeChains(Param, FnBodyScope);
  12790. }
  12791. }
  12792. // Ensure that the function's exception specification is instantiated.
  12793. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  12794. ResolveExceptionSpec(D->getLocation(), FPT);
  12795. // dllimport cannot be applied to non-inline function definitions.
  12796. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  12797. !FD->isTemplateInstantiation()) {
  12798. assert(!FD->hasAttr<DLLExportAttr>());
  12799. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  12800. FD->setInvalidDecl();
  12801. return D;
  12802. }
  12803. // We want to attach documentation to original Decl (which might be
  12804. // a function template).
  12805. ActOnDocumentableDecl(D);
  12806. if (getCurLexicalContext()->isObjCContainer() &&
  12807. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  12808. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  12809. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  12810. return D;
  12811. }
  12812. /// Given the set of return statements within a function body,
  12813. /// compute the variables that are subject to the named return value
  12814. /// optimization.
  12815. ///
  12816. /// Each of the variables that is subject to the named return value
  12817. /// optimization will be marked as NRVO variables in the AST, and any
  12818. /// return statement that has a marked NRVO variable as its NRVO candidate can
  12819. /// use the named return value optimization.
  12820. ///
  12821. /// This function applies a very simplistic algorithm for NRVO: if every return
  12822. /// statement in the scope of a variable has the same NRVO candidate, that
  12823. /// candidate is an NRVO variable.
  12824. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  12825. ReturnStmt **Returns = Scope->Returns.data();
  12826. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  12827. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  12828. if (!NRVOCandidate->isNRVOVariable())
  12829. Returns[I]->setNRVOCandidate(nullptr);
  12830. }
  12831. }
  12832. }
  12833. bool Sema::canDelayFunctionBody(const Declarator &D) {
  12834. // We can't delay parsing the body of a constexpr function template (yet).
  12835. if (D.getDeclSpec().hasConstexprSpecifier())
  12836. return false;
  12837. // We can't delay parsing the body of a function template with a deduced
  12838. // return type (yet).
  12839. if (D.getDeclSpec().hasAutoTypeSpec()) {
  12840. // If the placeholder introduces a non-deduced trailing return type,
  12841. // we can still delay parsing it.
  12842. if (D.getNumTypeObjects()) {
  12843. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  12844. if (Outer.Kind == DeclaratorChunk::Function &&
  12845. Outer.Fun.hasTrailingReturnType()) {
  12846. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  12847. return Ty.isNull() || !Ty->isUndeducedType();
  12848. }
  12849. }
  12850. return false;
  12851. }
  12852. return true;
  12853. }
  12854. bool Sema::canSkipFunctionBody(Decl *D) {
  12855. // We cannot skip the body of a function (or function template) which is
  12856. // constexpr, since we may need to evaluate its body in order to parse the
  12857. // rest of the file.
  12858. // We cannot skip the body of a function with an undeduced return type,
  12859. // because any callers of that function need to know the type.
  12860. if (const FunctionDecl *FD = D->getAsFunction()) {
  12861. if (FD->isConstexpr())
  12862. return false;
  12863. // We can't simply call Type::isUndeducedType here, because inside template
  12864. // auto can be deduced to a dependent type, which is not considered
  12865. // "undeduced".
  12866. if (FD->getReturnType()->getContainedDeducedType())
  12867. return false;
  12868. }
  12869. return Consumer.shouldSkipFunctionBody(D);
  12870. }
  12871. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  12872. if (!Decl)
  12873. return nullptr;
  12874. if (FunctionDecl *FD = Decl->getAsFunction())
  12875. FD->setHasSkippedBody();
  12876. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  12877. MD->setHasSkippedBody();
  12878. return Decl;
  12879. }
  12880. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  12881. return ActOnFinishFunctionBody(D, BodyArg, false);
  12882. }
  12883. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  12884. /// body.
  12885. class ExitFunctionBodyRAII {
  12886. public:
  12887. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  12888. ~ExitFunctionBodyRAII() {
  12889. if (!IsLambda)
  12890. S.PopExpressionEvaluationContext();
  12891. }
  12892. private:
  12893. Sema &S;
  12894. bool IsLambda = false;
  12895. };
  12896. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  12897. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  12898. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  12899. if (EscapeInfo.count(BD))
  12900. return EscapeInfo[BD];
  12901. bool R = false;
  12902. const BlockDecl *CurBD = BD;
  12903. do {
  12904. R = !CurBD->doesNotEscape();
  12905. if (R)
  12906. break;
  12907. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  12908. } while (CurBD);
  12909. return EscapeInfo[BD] = R;
  12910. };
  12911. // If the location where 'self' is implicitly retained is inside a escaping
  12912. // block, emit a diagnostic.
  12913. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  12914. S.ImplicitlyRetainedSelfLocs)
  12915. if (IsOrNestedInEscapingBlock(P.second))
  12916. S.Diag(P.first, diag::warn_implicitly_retains_self)
  12917. << FixItHint::CreateInsertion(P.first, "self->");
  12918. }
  12919. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  12920. bool IsInstantiation) {
  12921. FunctionScopeInfo *FSI = getCurFunction();
  12922. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  12923. if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
  12924. FD->addAttr(StrictFPAttr::CreateImplicit(Context));
  12925. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  12926. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  12927. if (getLangOpts().Coroutines && FSI->isCoroutine())
  12928. CheckCompletedCoroutineBody(FD, Body);
  12929. {
  12930. // Do not call PopExpressionEvaluationContext() if it is a lambda because
  12931. // one is already popped when finishing the lambda in BuildLambdaExpr().
  12932. // This is meant to pop the context added in ActOnStartOfFunctionDef().
  12933. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  12934. if (FD) {
  12935. FD->setBody(Body);
  12936. FD->setWillHaveBody(false);
  12937. if (getLangOpts().CPlusPlus14) {
  12938. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  12939. FD->getReturnType()->isUndeducedType()) {
  12940. // If the function has a deduced result type but contains no 'return'
  12941. // statements, the result type as written must be exactly 'auto', and
  12942. // the deduced result type is 'void'.
  12943. if (!FD->getReturnType()->getAs<AutoType>()) {
  12944. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  12945. << FD->getReturnType();
  12946. FD->setInvalidDecl();
  12947. } else {
  12948. // Substitute 'void' for the 'auto' in the type.
  12949. TypeLoc ResultType = getReturnTypeLoc(FD);
  12950. Context.adjustDeducedFunctionResultType(
  12951. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  12952. }
  12953. }
  12954. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  12955. // In C++11, we don't use 'auto' deduction rules for lambda call
  12956. // operators because we don't support return type deduction.
  12957. auto *LSI = getCurLambda();
  12958. if (LSI->HasImplicitReturnType) {
  12959. deduceClosureReturnType(*LSI);
  12960. // C++11 [expr.prim.lambda]p4:
  12961. // [...] if there are no return statements in the compound-statement
  12962. // [the deduced type is] the type void
  12963. QualType RetType =
  12964. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  12965. // Update the return type to the deduced type.
  12966. const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
  12967. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  12968. Proto->getExtProtoInfo()));
  12969. }
  12970. }
  12971. // If the function implicitly returns zero (like 'main') or is naked,
  12972. // don't complain about missing return statements.
  12973. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  12974. WP.disableCheckFallThrough();
  12975. // MSVC permits the use of pure specifier (=0) on function definition,
  12976. // defined at class scope, warn about this non-standard construct.
  12977. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  12978. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  12979. if (!FD->isInvalidDecl()) {
  12980. // Don't diagnose unused parameters of defaulted, deleted or naked
  12981. // functions.
  12982. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
  12983. !FD->hasAttr<NakedAttr>())
  12984. DiagnoseUnusedParameters(FD->parameters());
  12985. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  12986. FD->getReturnType(), FD);
  12987. // If this is a structor, we need a vtable.
  12988. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  12989. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  12990. else if (CXXDestructorDecl *Destructor =
  12991. dyn_cast<CXXDestructorDecl>(FD))
  12992. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  12993. // Try to apply the named return value optimization. We have to check
  12994. // if we can do this here because lambdas keep return statements around
  12995. // to deduce an implicit return type.
  12996. if (FD->getReturnType()->isRecordType() &&
  12997. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  12998. computeNRVO(Body, FSI);
  12999. }
  13000. // GNU warning -Wmissing-prototypes:
  13001. // Warn if a global function is defined without a previous
  13002. // prototype declaration. This warning is issued even if the
  13003. // definition itself provides a prototype. The aim is to detect
  13004. // global functions that fail to be declared in header files.
  13005. const FunctionDecl *PossiblePrototype = nullptr;
  13006. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  13007. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  13008. if (PossiblePrototype) {
  13009. // We found a declaration that is not a prototype,
  13010. // but that could be a zero-parameter prototype
  13011. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  13012. TypeLoc TL = TI->getTypeLoc();
  13013. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  13014. Diag(PossiblePrototype->getLocation(),
  13015. diag::note_declaration_not_a_prototype)
  13016. << (FD->getNumParams() != 0)
  13017. << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
  13018. FTL.getRParenLoc(), "void")
  13019. : FixItHint{});
  13020. }
  13021. } else {
  13022. // Returns true if the token beginning at this Loc is `const`.
  13023. auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
  13024. const LangOptions &LangOpts) {
  13025. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  13026. if (LocInfo.first.isInvalid())
  13027. return false;
  13028. bool Invalid = false;
  13029. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  13030. if (Invalid)
  13031. return false;
  13032. if (LocInfo.second > Buffer.size())
  13033. return false;
  13034. const char *LexStart = Buffer.data() + LocInfo.second;
  13035. StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
  13036. return StartTok.consume_front("const") &&
  13037. (StartTok.empty() || isWhitespace(StartTok[0]) ||
  13038. StartTok.startswith("/*") || StartTok.startswith("//"));
  13039. };
  13040. auto findBeginLoc = [&]() {
  13041. // If the return type has `const` qualifier, we want to insert
  13042. // `static` before `const` (and not before the typename).
  13043. if ((FD->getReturnType()->isAnyPointerType() &&
  13044. FD->getReturnType()->getPointeeType().isConstQualified()) ||
  13045. FD->getReturnType().isConstQualified()) {
  13046. // But only do this if we can determine where the `const` is.
  13047. if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
  13048. getLangOpts()))
  13049. return FD->getBeginLoc();
  13050. }
  13051. return FD->getTypeSpecStartLoc();
  13052. };
  13053. Diag(FD->getTypeSpecStartLoc(),
  13054. diag::note_static_for_internal_linkage)
  13055. << /* function */ 1
  13056. << (FD->getStorageClass() == SC_None
  13057. ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
  13058. : FixItHint{});
  13059. }
  13060. // GNU warning -Wstrict-prototypes
  13061. // Warn if K&R function is defined without a previous declaration.
  13062. // This warning is issued only if the definition itself does not
  13063. // provide a prototype. Only K&R definitions do not provide a
  13064. // prototype.
  13065. if (!FD->hasWrittenPrototype()) {
  13066. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  13067. TypeLoc TL = TI->getTypeLoc();
  13068. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  13069. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  13070. }
  13071. }
  13072. // Warn on CPUDispatch with an actual body.
  13073. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  13074. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  13075. if (!CmpndBody->body_empty())
  13076. Diag(CmpndBody->body_front()->getBeginLoc(),
  13077. diag::warn_dispatch_body_ignored);
  13078. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  13079. const CXXMethodDecl *KeyFunction;
  13080. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  13081. MD->isVirtual() &&
  13082. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  13083. MD == KeyFunction->getCanonicalDecl()) {
  13084. // Update the key-function state if necessary for this ABI.
  13085. if (FD->isInlined() &&
  13086. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  13087. Context.setNonKeyFunction(MD);
  13088. // If the newly-chosen key function is already defined, then we
  13089. // need to mark the vtable as used retroactively.
  13090. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  13091. const FunctionDecl *Definition;
  13092. if (KeyFunction && KeyFunction->isDefined(Definition))
  13093. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  13094. } else {
  13095. // We just defined they key function; mark the vtable as used.
  13096. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  13097. }
  13098. }
  13099. }
  13100. assert(
  13101. (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  13102. "Function parsing confused");
  13103. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  13104. assert(MD == getCurMethodDecl() && "Method parsing confused");
  13105. MD->setBody(Body);
  13106. if (!MD->isInvalidDecl()) {
  13107. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  13108. MD->getReturnType(), MD);
  13109. if (Body)
  13110. computeNRVO(Body, FSI);
  13111. }
  13112. if (FSI->ObjCShouldCallSuper) {
  13113. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  13114. << MD->getSelector().getAsString();
  13115. FSI->ObjCShouldCallSuper = false;
  13116. }
  13117. if (FSI->ObjCWarnForNoDesignatedInitChain) {
  13118. const ObjCMethodDecl *InitMethod = nullptr;
  13119. bool isDesignated =
  13120. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  13121. assert(isDesignated && InitMethod);
  13122. (void)isDesignated;
  13123. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  13124. auto IFace = MD->getClassInterface();
  13125. if (!IFace)
  13126. return false;
  13127. auto SuperD = IFace->getSuperClass();
  13128. if (!SuperD)
  13129. return false;
  13130. return SuperD->getIdentifier() ==
  13131. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  13132. };
  13133. // Don't issue this warning for unavailable inits or direct subclasses
  13134. // of NSObject.
  13135. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  13136. Diag(MD->getLocation(),
  13137. diag::warn_objc_designated_init_missing_super_call);
  13138. Diag(InitMethod->getLocation(),
  13139. diag::note_objc_designated_init_marked_here);
  13140. }
  13141. FSI->ObjCWarnForNoDesignatedInitChain = false;
  13142. }
  13143. if (FSI->ObjCWarnForNoInitDelegation) {
  13144. // Don't issue this warning for unavaialable inits.
  13145. if (!MD->isUnavailable())
  13146. Diag(MD->getLocation(),
  13147. diag::warn_objc_secondary_init_missing_init_call);
  13148. FSI->ObjCWarnForNoInitDelegation = false;
  13149. }
  13150. diagnoseImplicitlyRetainedSelf(*this);
  13151. } else {
  13152. // Parsing the function declaration failed in some way. Pop the fake scope
  13153. // we pushed on.
  13154. PopFunctionScopeInfo(ActivePolicy, dcl);
  13155. return nullptr;
  13156. }
  13157. if (Body && FSI->HasPotentialAvailabilityViolations)
  13158. DiagnoseUnguardedAvailabilityViolations(dcl);
  13159. assert(!FSI->ObjCShouldCallSuper &&
  13160. "This should only be set for ObjC methods, which should have been "
  13161. "handled in the block above.");
  13162. // Verify and clean out per-function state.
  13163. if (Body && (!FD || !FD->isDefaulted())) {
  13164. // C++ constructors that have function-try-blocks can't have return
  13165. // statements in the handlers of that block. (C++ [except.handle]p14)
  13166. // Verify this.
  13167. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  13168. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  13169. // Verify that gotos and switch cases don't jump into scopes illegally.
  13170. if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
  13171. DiagnoseInvalidJumps(Body);
  13172. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  13173. if (!Destructor->getParent()->isDependentType())
  13174. CheckDestructor(Destructor);
  13175. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  13176. Destructor->getParent());
  13177. }
  13178. // If any errors have occurred, clear out any temporaries that may have
  13179. // been leftover. This ensures that these temporaries won't be picked up
  13180. // for deletion in some later function.
  13181. if (hasUncompilableErrorOccurred() ||
  13182. getDiagnostics().getSuppressAllDiagnostics()) {
  13183. DiscardCleanupsInEvaluationContext();
  13184. }
  13185. if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
  13186. // Since the body is valid, issue any analysis-based warnings that are
  13187. // enabled.
  13188. ActivePolicy = &WP;
  13189. }
  13190. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  13191. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  13192. FD->setInvalidDecl();
  13193. if (FD && FD->hasAttr<NakedAttr>()) {
  13194. for (const Stmt *S : Body->children()) {
  13195. // Allow local register variables without initializer as they don't
  13196. // require prologue.
  13197. bool RegisterVariables = false;
  13198. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  13199. for (const auto *Decl : DS->decls()) {
  13200. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  13201. RegisterVariables =
  13202. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  13203. if (!RegisterVariables)
  13204. break;
  13205. }
  13206. }
  13207. }
  13208. if (RegisterVariables)
  13209. continue;
  13210. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  13211. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  13212. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  13213. FD->setInvalidDecl();
  13214. break;
  13215. }
  13216. }
  13217. }
  13218. assert(ExprCleanupObjects.size() ==
  13219. ExprEvalContexts.back().NumCleanupObjects &&
  13220. "Leftover temporaries in function");
  13221. assert(!Cleanup.exprNeedsCleanups() &&
  13222. "Unaccounted cleanups in function");
  13223. assert(MaybeODRUseExprs.empty() &&
  13224. "Leftover expressions for odr-use checking");
  13225. }
  13226. } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
  13227. // the declaration context below. Otherwise, we're unable to transform
  13228. // 'this' expressions when transforming immediate context functions.
  13229. if (!IsInstantiation)
  13230. PopDeclContext();
  13231. PopFunctionScopeInfo(ActivePolicy, dcl);
  13232. // If any errors have occurred, clear out any temporaries that may have
  13233. // been leftover. This ensures that these temporaries won't be picked up for
  13234. // deletion in some later function.
  13235. if (hasUncompilableErrorOccurred()) {
  13236. DiscardCleanupsInEvaluationContext();
  13237. }
  13238. if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
  13239. !LangOpts.OMPTargetTriples.empty())) ||
  13240. LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
  13241. auto ES = getEmissionStatus(FD);
  13242. if (ES == Sema::FunctionEmissionStatus::Emitted ||
  13243. ES == Sema::FunctionEmissionStatus::Unknown)
  13244. DeclsToCheckForDeferredDiags.insert(FD);
  13245. }
  13246. if (FD && !FD->isDeleted())
  13247. checkTypeSupport(FD->getType(), FD->getLocation(), FD);
  13248. return dcl;
  13249. }
  13250. /// When we finish delayed parsing of an attribute, we must attach it to the
  13251. /// relevant Decl.
  13252. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  13253. ParsedAttributes &Attrs) {
  13254. // Always attach attributes to the underlying decl.
  13255. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  13256. D = TD->getTemplatedDecl();
  13257. ProcessDeclAttributeList(S, D, Attrs);
  13258. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  13259. if (Method->isStatic())
  13260. checkThisInStaticMemberFunctionAttributes(Method);
  13261. }
  13262. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  13263. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  13264. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  13265. IdentifierInfo &II, Scope *S) {
  13266. // Find the scope in which the identifier is injected and the corresponding
  13267. // DeclContext.
  13268. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  13269. // In that case, we inject the declaration into the translation unit scope
  13270. // instead.
  13271. Scope *BlockScope = S;
  13272. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  13273. BlockScope = BlockScope->getParent();
  13274. Scope *ContextScope = BlockScope;
  13275. while (!ContextScope->getEntity())
  13276. ContextScope = ContextScope->getParent();
  13277. ContextRAII SavedContext(*this, ContextScope->getEntity());
  13278. // Before we produce a declaration for an implicitly defined
  13279. // function, see whether there was a locally-scoped declaration of
  13280. // this name as a function or variable. If so, use that
  13281. // (non-visible) declaration, and complain about it.
  13282. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  13283. if (ExternCPrev) {
  13284. // We still need to inject the function into the enclosing block scope so
  13285. // that later (non-call) uses can see it.
  13286. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  13287. // C89 footnote 38:
  13288. // If in fact it is not defined as having type "function returning int",
  13289. // the behavior is undefined.
  13290. if (!isa<FunctionDecl>(ExternCPrev) ||
  13291. !Context.typesAreCompatible(
  13292. cast<FunctionDecl>(ExternCPrev)->getType(),
  13293. Context.getFunctionNoProtoType(Context.IntTy))) {
  13294. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  13295. << ExternCPrev << !getLangOpts().C99;
  13296. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  13297. return ExternCPrev;
  13298. }
  13299. }
  13300. // Extension in C99. Legal in C90, but warn about it.
  13301. unsigned diag_id;
  13302. if (II.getName().startswith("__builtin_"))
  13303. diag_id = diag::warn_builtin_unknown;
  13304. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  13305. else if (getLangOpts().OpenCL)
  13306. diag_id = diag::err_opencl_implicit_function_decl;
  13307. else if (getLangOpts().C99)
  13308. diag_id = diag::ext_implicit_function_decl;
  13309. else
  13310. diag_id = diag::warn_implicit_function_decl;
  13311. TypoCorrection Corrected;
  13312. // Because typo correction is expensive, only do it if the implicit
  13313. // function declaration is going to be treated as an error.
  13314. //
  13315. // Perform the corection before issuing the main diagnostic, as some consumers
  13316. // use typo-correction callbacks to enhance the main diagnostic.
  13317. if (S && !ExternCPrev &&
  13318. (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
  13319. DeclFilterCCC<FunctionDecl> CCC{};
  13320. Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  13321. S, nullptr, CCC, CTK_NonError);
  13322. }
  13323. Diag(Loc, diag_id) << &II;
  13324. if (Corrected)
  13325. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  13326. /*ErrorRecovery*/ false);
  13327. // If we found a prior declaration of this function, don't bother building
  13328. // another one. We've already pushed that one into scope, so there's nothing
  13329. // more to do.
  13330. if (ExternCPrev)
  13331. return ExternCPrev;
  13332. // Set a Declarator for the implicit definition: int foo();
  13333. const char *Dummy;
  13334. AttributeFactory attrFactory;
  13335. DeclSpec DS(attrFactory);
  13336. unsigned DiagID;
  13337. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  13338. Context.getPrintingPolicy());
  13339. (void)Error; // Silence warning.
  13340. assert(!Error && "Error setting up implicit decl!");
  13341. SourceLocation NoLoc;
  13342. Declarator D(DS, DeclaratorContext::Block);
  13343. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  13344. /*IsAmbiguous=*/false,
  13345. /*LParenLoc=*/NoLoc,
  13346. /*Params=*/nullptr,
  13347. /*NumParams=*/0,
  13348. /*EllipsisLoc=*/NoLoc,
  13349. /*RParenLoc=*/NoLoc,
  13350. /*RefQualifierIsLvalueRef=*/true,
  13351. /*RefQualifierLoc=*/NoLoc,
  13352. /*MutableLoc=*/NoLoc, EST_None,
  13353. /*ESpecRange=*/SourceRange(),
  13354. /*Exceptions=*/nullptr,
  13355. /*ExceptionRanges=*/nullptr,
  13356. /*NumExceptions=*/0,
  13357. /*NoexceptExpr=*/nullptr,
  13358. /*ExceptionSpecTokens=*/nullptr,
  13359. /*DeclsInPrototype=*/None, Loc,
  13360. Loc, D),
  13361. std::move(DS.getAttributes()), SourceLocation());
  13362. D.SetIdentifier(&II, Loc);
  13363. // Insert this function into the enclosing block scope.
  13364. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  13365. FD->setImplicit();
  13366. AddKnownFunctionAttributes(FD);
  13367. return FD;
  13368. }
  13369. /// If this function is a C++ replaceable global allocation function
  13370. /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
  13371. /// adds any function attributes that we know a priori based on the standard.
  13372. ///
  13373. /// We need to check for duplicate attributes both here and where user-written
  13374. /// attributes are applied to declarations.
  13375. void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
  13376. FunctionDecl *FD) {
  13377. if (FD->isInvalidDecl())
  13378. return;
  13379. if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
  13380. FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
  13381. return;
  13382. Optional<unsigned> AlignmentParam;
  13383. bool IsNothrow = false;
  13384. if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
  13385. return;
  13386. // C++2a [basic.stc.dynamic.allocation]p4:
  13387. // An allocation function that has a non-throwing exception specification
  13388. // indicates failure by returning a null pointer value. Any other allocation
  13389. // function never returns a null pointer value and indicates failure only by
  13390. // throwing an exception [...]
  13391. if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
  13392. FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
  13393. // C++2a [basic.stc.dynamic.allocation]p2:
  13394. // An allocation function attempts to allocate the requested amount of
  13395. // storage. [...] If the request succeeds, the value returned by a
  13396. // replaceable allocation function is a [...] pointer value p0 different
  13397. // from any previously returned value p1 [...]
  13398. //
  13399. // However, this particular information is being added in codegen,
  13400. // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
  13401. // C++2a [basic.stc.dynamic.allocation]p2:
  13402. // An allocation function attempts to allocate the requested amount of
  13403. // storage. If it is successful, it returns the address of the start of a
  13404. // block of storage whose length in bytes is at least as large as the
  13405. // requested size.
  13406. if (!FD->hasAttr<AllocSizeAttr>()) {
  13407. FD->addAttr(AllocSizeAttr::CreateImplicit(
  13408. Context, /*ElemSizeParam=*/ParamIdx(1, FD),
  13409. /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
  13410. }
  13411. // C++2a [basic.stc.dynamic.allocation]p3:
  13412. // For an allocation function [...], the pointer returned on a successful
  13413. // call shall represent the address of storage that is aligned as follows:
  13414. // (3.1) If the allocation function takes an argument of type
  13415. // std​::​align_­val_­t, the storage will have the alignment
  13416. // specified by the value of this argument.
  13417. if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
  13418. FD->addAttr(AllocAlignAttr::CreateImplicit(
  13419. Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
  13420. }
  13421. // FIXME:
  13422. // C++2a [basic.stc.dynamic.allocation]p3:
  13423. // For an allocation function [...], the pointer returned on a successful
  13424. // call shall represent the address of storage that is aligned as follows:
  13425. // (3.2) Otherwise, if the allocation function is named operator new[],
  13426. // the storage is aligned for any object that does not have
  13427. // new-extended alignment ([basic.align]) and is no larger than the
  13428. // requested size.
  13429. // (3.3) Otherwise, the storage is aligned for any object that does not
  13430. // have new-extended alignment and is of the requested size.
  13431. }
  13432. /// Adds any function attributes that we know a priori based on
  13433. /// the declaration of this function.
  13434. ///
  13435. /// These attributes can apply both to implicitly-declared builtins
  13436. /// (like __builtin___printf_chk) or to library-declared functions
  13437. /// like NSLog or printf.
  13438. ///
  13439. /// We need to check for duplicate attributes both here and where user-written
  13440. /// attributes are applied to declarations.
  13441. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  13442. if (FD->isInvalidDecl())
  13443. return;
  13444. // If this is a built-in function, map its builtin attributes to
  13445. // actual attributes.
  13446. if (unsigned BuiltinID = FD->getBuiltinID()) {
  13447. // Handle printf-formatting attributes.
  13448. unsigned FormatIdx;
  13449. bool HasVAListArg;
  13450. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  13451. if (!FD->hasAttr<FormatAttr>()) {
  13452. const char *fmt = "printf";
  13453. unsigned int NumParams = FD->getNumParams();
  13454. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  13455. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  13456. fmt = "NSString";
  13457. FD->addAttr(FormatAttr::CreateImplicit(Context,
  13458. &Context.Idents.get(fmt),
  13459. FormatIdx+1,
  13460. HasVAListArg ? 0 : FormatIdx+2,
  13461. FD->getLocation()));
  13462. }
  13463. }
  13464. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  13465. HasVAListArg)) {
  13466. if (!FD->hasAttr<FormatAttr>())
  13467. FD->addAttr(FormatAttr::CreateImplicit(Context,
  13468. &Context.Idents.get("scanf"),
  13469. FormatIdx+1,
  13470. HasVAListArg ? 0 : FormatIdx+2,
  13471. FD->getLocation()));
  13472. }
  13473. // Handle automatically recognized callbacks.
  13474. SmallVector<int, 4> Encoding;
  13475. if (!FD->hasAttr<CallbackAttr>() &&
  13476. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  13477. FD->addAttr(CallbackAttr::CreateImplicit(
  13478. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  13479. // Mark const if we don't care about errno and that is the only thing
  13480. // preventing the function from being const. This allows IRgen to use LLVM
  13481. // intrinsics for such functions.
  13482. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  13483. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  13484. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  13485. // We make "fma" on GNU or Windows const because we know it does not set
  13486. // errno in those environments even though it could set errno based on the
  13487. // C standard.
  13488. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  13489. if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
  13490. !FD->hasAttr<ConstAttr>()) {
  13491. switch (BuiltinID) {
  13492. case Builtin::BI__builtin_fma:
  13493. case Builtin::BI__builtin_fmaf:
  13494. case Builtin::BI__builtin_fmal:
  13495. case Builtin::BIfma:
  13496. case Builtin::BIfmaf:
  13497. case Builtin::BIfmal:
  13498. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  13499. break;
  13500. default:
  13501. break;
  13502. }
  13503. }
  13504. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  13505. !FD->hasAttr<ReturnsTwiceAttr>())
  13506. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  13507. FD->getLocation()));
  13508. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  13509. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  13510. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  13511. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  13512. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  13513. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  13514. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  13515. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  13516. // Add the appropriate attribute, depending on the CUDA compilation mode
  13517. // and which target the builtin belongs to. For example, during host
  13518. // compilation, aux builtins are __device__, while the rest are __host__.
  13519. if (getLangOpts().CUDAIsDevice !=
  13520. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  13521. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  13522. else
  13523. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  13524. }
  13525. // Add known guaranteed alignment for allocation functions.
  13526. switch (BuiltinID) {
  13527. case Builtin::BIaligned_alloc:
  13528. if (!FD->hasAttr<AllocAlignAttr>())
  13529. FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
  13530. FD->getLocation()));
  13531. break;
  13532. default:
  13533. break;
  13534. }
  13535. }
  13536. AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
  13537. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  13538. // throw, add an implicit nothrow attribute to any extern "C" function we come
  13539. // across.
  13540. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  13541. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  13542. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  13543. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  13544. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  13545. }
  13546. IdentifierInfo *Name = FD->getIdentifier();
  13547. if (!Name)
  13548. return;
  13549. if ((!getLangOpts().CPlusPlus &&
  13550. FD->getDeclContext()->isTranslationUnit()) ||
  13551. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  13552. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  13553. LinkageSpecDecl::lang_c)) {
  13554. // Okay: this could be a libc/libm/Objective-C function we know
  13555. // about.
  13556. } else
  13557. return;
  13558. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  13559. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  13560. // target-specific builtins, perhaps?
  13561. if (!FD->hasAttr<FormatAttr>())
  13562. FD->addAttr(FormatAttr::CreateImplicit(Context,
  13563. &Context.Idents.get("printf"), 2,
  13564. Name->isStr("vasprintf") ? 0 : 3,
  13565. FD->getLocation()));
  13566. }
  13567. if (Name->isStr("__CFStringMakeConstantString")) {
  13568. // We already have a __builtin___CFStringMakeConstantString,
  13569. // but builds that use -fno-constant-cfstrings don't go through that.
  13570. if (!FD->hasAttr<FormatArgAttr>())
  13571. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  13572. FD->getLocation()));
  13573. }
  13574. }
  13575. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  13576. TypeSourceInfo *TInfo) {
  13577. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  13578. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  13579. if (!TInfo) {
  13580. assert(D.isInvalidType() && "no declarator info for valid type");
  13581. TInfo = Context.getTrivialTypeSourceInfo(T);
  13582. }
  13583. // Scope manipulation handled by caller.
  13584. TypedefDecl *NewTD =
  13585. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  13586. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  13587. // Bail out immediately if we have an invalid declaration.
  13588. if (D.isInvalidType()) {
  13589. NewTD->setInvalidDecl();
  13590. return NewTD;
  13591. }
  13592. if (D.getDeclSpec().isModulePrivateSpecified()) {
  13593. if (CurContext->isFunctionOrMethod())
  13594. Diag(NewTD->getLocation(), diag::err_module_private_local)
  13595. << 2 << NewTD
  13596. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  13597. << FixItHint::CreateRemoval(
  13598. D.getDeclSpec().getModulePrivateSpecLoc());
  13599. else
  13600. NewTD->setModulePrivate();
  13601. }
  13602. // C++ [dcl.typedef]p8:
  13603. // If the typedef declaration defines an unnamed class (or
  13604. // enum), the first typedef-name declared by the declaration
  13605. // to be that class type (or enum type) is used to denote the
  13606. // class type (or enum type) for linkage purposes only.
  13607. // We need to check whether the type was declared in the declaration.
  13608. switch (D.getDeclSpec().getTypeSpecType()) {
  13609. case TST_enum:
  13610. case TST_struct:
  13611. case TST_interface:
  13612. case TST_union:
  13613. case TST_class: {
  13614. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  13615. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  13616. break;
  13617. }
  13618. default:
  13619. break;
  13620. }
  13621. return NewTD;
  13622. }
  13623. /// Check that this is a valid underlying type for an enum declaration.
  13624. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  13625. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  13626. QualType T = TI->getType();
  13627. if (T->isDependentType())
  13628. return false;
  13629. // This doesn't use 'isIntegralType' despite the error message mentioning
  13630. // integral type because isIntegralType would also allow enum types in C.
  13631. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  13632. if (BT->isInteger())
  13633. return false;
  13634. if (T->isBitIntType())
  13635. return false;
  13636. return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  13637. }
  13638. /// Check whether this is a valid redeclaration of a previous enumeration.
  13639. /// \return true if the redeclaration was invalid.
  13640. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  13641. QualType EnumUnderlyingTy, bool IsFixed,
  13642. const EnumDecl *Prev) {
  13643. if (IsScoped != Prev->isScoped()) {
  13644. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  13645. << Prev->isScoped();
  13646. Diag(Prev->getLocation(), diag::note_previous_declaration);
  13647. return true;
  13648. }
  13649. if (IsFixed && Prev->isFixed()) {
  13650. if (!EnumUnderlyingTy->isDependentType() &&
  13651. !Prev->getIntegerType()->isDependentType() &&
  13652. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  13653. Prev->getIntegerType())) {
  13654. // TODO: Highlight the underlying type of the redeclaration.
  13655. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  13656. << EnumUnderlyingTy << Prev->getIntegerType();
  13657. Diag(Prev->getLocation(), diag::note_previous_declaration)
  13658. << Prev->getIntegerTypeRange();
  13659. return true;
  13660. }
  13661. } else if (IsFixed != Prev->isFixed()) {
  13662. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  13663. << Prev->isFixed();
  13664. Diag(Prev->getLocation(), diag::note_previous_declaration);
  13665. return true;
  13666. }
  13667. return false;
  13668. }
  13669. /// Get diagnostic %select index for tag kind for
  13670. /// redeclaration diagnostic message.
  13671. /// WARNING: Indexes apply to particular diagnostics only!
  13672. ///
  13673. /// \returns diagnostic %select index.
  13674. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  13675. switch (Tag) {
  13676. case TTK_Struct: return 0;
  13677. case TTK_Interface: return 1;
  13678. case TTK_Class: return 2;
  13679. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  13680. }
  13681. }
  13682. /// Determine if tag kind is a class-key compatible with
  13683. /// class for redeclaration (class, struct, or __interface).
  13684. ///
  13685. /// \returns true iff the tag kind is compatible.
  13686. static bool isClassCompatTagKind(TagTypeKind Tag)
  13687. {
  13688. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  13689. }
  13690. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  13691. TagTypeKind TTK) {
  13692. if (isa<TypedefDecl>(PrevDecl))
  13693. return NTK_Typedef;
  13694. else if (isa<TypeAliasDecl>(PrevDecl))
  13695. return NTK_TypeAlias;
  13696. else if (isa<ClassTemplateDecl>(PrevDecl))
  13697. return NTK_Template;
  13698. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  13699. return NTK_TypeAliasTemplate;
  13700. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  13701. return NTK_TemplateTemplateArgument;
  13702. switch (TTK) {
  13703. case TTK_Struct:
  13704. case TTK_Interface:
  13705. case TTK_Class:
  13706. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  13707. case TTK_Union:
  13708. return NTK_NonUnion;
  13709. case TTK_Enum:
  13710. return NTK_NonEnum;
  13711. }
  13712. llvm_unreachable("invalid TTK");
  13713. }
  13714. /// Determine whether a tag with a given kind is acceptable
  13715. /// as a redeclaration of the given tag declaration.
  13716. ///
  13717. /// \returns true if the new tag kind is acceptable, false otherwise.
  13718. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  13719. TagTypeKind NewTag, bool isDefinition,
  13720. SourceLocation NewTagLoc,
  13721. const IdentifierInfo *Name) {
  13722. // C++ [dcl.type.elab]p3:
  13723. // The class-key or enum keyword present in the
  13724. // elaborated-type-specifier shall agree in kind with the
  13725. // declaration to which the name in the elaborated-type-specifier
  13726. // refers. This rule also applies to the form of
  13727. // elaborated-type-specifier that declares a class-name or
  13728. // friend class since it can be construed as referring to the
  13729. // definition of the class. Thus, in any
  13730. // elaborated-type-specifier, the enum keyword shall be used to
  13731. // refer to an enumeration (7.2), the union class-key shall be
  13732. // used to refer to a union (clause 9), and either the class or
  13733. // struct class-key shall be used to refer to a class (clause 9)
  13734. // declared using the class or struct class-key.
  13735. TagTypeKind OldTag = Previous->getTagKind();
  13736. if (OldTag != NewTag &&
  13737. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  13738. return false;
  13739. // Tags are compatible, but we might still want to warn on mismatched tags.
  13740. // Non-class tags can't be mismatched at this point.
  13741. if (!isClassCompatTagKind(NewTag))
  13742. return true;
  13743. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  13744. // by our warning analysis. We don't want to warn about mismatches with (eg)
  13745. // declarations in system headers that are designed to be specialized, but if
  13746. // a user asks us to warn, we should warn if their code contains mismatched
  13747. // declarations.
  13748. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  13749. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  13750. Loc);
  13751. };
  13752. if (IsIgnoredLoc(NewTagLoc))
  13753. return true;
  13754. auto IsIgnored = [&](const TagDecl *Tag) {
  13755. return IsIgnoredLoc(Tag->getLocation());
  13756. };
  13757. while (IsIgnored(Previous)) {
  13758. Previous = Previous->getPreviousDecl();
  13759. if (!Previous)
  13760. return true;
  13761. OldTag = Previous->getTagKind();
  13762. }
  13763. bool isTemplate = false;
  13764. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  13765. isTemplate = Record->getDescribedClassTemplate();
  13766. if (inTemplateInstantiation()) {
  13767. if (OldTag != NewTag) {
  13768. // In a template instantiation, do not offer fix-its for tag mismatches
  13769. // since they usually mess up the template instead of fixing the problem.
  13770. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  13771. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  13772. << getRedeclDiagFromTagKind(OldTag);
  13773. // FIXME: Note previous location?
  13774. }
  13775. return true;
  13776. }
  13777. if (isDefinition) {
  13778. // On definitions, check all previous tags and issue a fix-it for each
  13779. // one that doesn't match the current tag.
  13780. if (Previous->getDefinition()) {
  13781. // Don't suggest fix-its for redefinitions.
  13782. return true;
  13783. }
  13784. bool previousMismatch = false;
  13785. for (const TagDecl *I : Previous->redecls()) {
  13786. if (I->getTagKind() != NewTag) {
  13787. // Ignore previous declarations for which the warning was disabled.
  13788. if (IsIgnored(I))
  13789. continue;
  13790. if (!previousMismatch) {
  13791. previousMismatch = true;
  13792. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  13793. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  13794. << getRedeclDiagFromTagKind(I->getTagKind());
  13795. }
  13796. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  13797. << getRedeclDiagFromTagKind(NewTag)
  13798. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  13799. TypeWithKeyword::getTagTypeKindName(NewTag));
  13800. }
  13801. }
  13802. return true;
  13803. }
  13804. // Identify the prevailing tag kind: this is the kind of the definition (if
  13805. // there is a non-ignored definition), or otherwise the kind of the prior
  13806. // (non-ignored) declaration.
  13807. const TagDecl *PrevDef = Previous->getDefinition();
  13808. if (PrevDef && IsIgnored(PrevDef))
  13809. PrevDef = nullptr;
  13810. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  13811. if (Redecl->getTagKind() != NewTag) {
  13812. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  13813. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  13814. << getRedeclDiagFromTagKind(OldTag);
  13815. Diag(Redecl->getLocation(), diag::note_previous_use);
  13816. // If there is a previous definition, suggest a fix-it.
  13817. if (PrevDef) {
  13818. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  13819. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  13820. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  13821. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  13822. }
  13823. }
  13824. return true;
  13825. }
  13826. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  13827. /// from an outer enclosing namespace or file scope inside a friend declaration.
  13828. /// This should provide the commented out code in the following snippet:
  13829. /// namespace N {
  13830. /// struct X;
  13831. /// namespace M {
  13832. /// struct Y { friend struct /*N::*/ X; };
  13833. /// }
  13834. /// }
  13835. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  13836. SourceLocation NameLoc) {
  13837. // While the decl is in a namespace, do repeated lookup of that name and see
  13838. // if we get the same namespace back. If we do not, continue until
  13839. // translation unit scope, at which point we have a fully qualified NNS.
  13840. SmallVector<IdentifierInfo *, 4> Namespaces;
  13841. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  13842. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  13843. // This tag should be declared in a namespace, which can only be enclosed by
  13844. // other namespaces. Bail if there's an anonymous namespace in the chain.
  13845. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  13846. if (!Namespace || Namespace->isAnonymousNamespace())
  13847. return FixItHint();
  13848. IdentifierInfo *II = Namespace->getIdentifier();
  13849. Namespaces.push_back(II);
  13850. NamedDecl *Lookup = SemaRef.LookupSingleName(
  13851. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  13852. if (Lookup == Namespace)
  13853. break;
  13854. }
  13855. // Once we have all the namespaces, reverse them to go outermost first, and
  13856. // build an NNS.
  13857. SmallString<64> Insertion;
  13858. llvm::raw_svector_ostream OS(Insertion);
  13859. if (DC->isTranslationUnit())
  13860. OS << "::";
  13861. std::reverse(Namespaces.begin(), Namespaces.end());
  13862. for (auto *II : Namespaces)
  13863. OS << II->getName() << "::";
  13864. return FixItHint::CreateInsertion(NameLoc, Insertion);
  13865. }
  13866. /// Determine whether a tag originally declared in context \p OldDC can
  13867. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  13868. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  13869. /// using-declaration).
  13870. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  13871. DeclContext *NewDC) {
  13872. OldDC = OldDC->getRedeclContext();
  13873. NewDC = NewDC->getRedeclContext();
  13874. if (OldDC->Equals(NewDC))
  13875. return true;
  13876. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  13877. // encloses the other).
  13878. if (S.getLangOpts().MSVCCompat &&
  13879. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  13880. return true;
  13881. return false;
  13882. }
  13883. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  13884. /// former case, Name will be non-null. In the later case, Name will be null.
  13885. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  13886. /// reference/declaration/definition of a tag.
  13887. ///
  13888. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  13889. /// trailing-type-specifier) other than one in an alias-declaration.
  13890. ///
  13891. /// \param SkipBody If non-null, will be set to indicate if the caller should
  13892. /// skip the definition of this tag and treat it as if it were a declaration.
  13893. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  13894. SourceLocation KWLoc, CXXScopeSpec &SS,
  13895. IdentifierInfo *Name, SourceLocation NameLoc,
  13896. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  13897. SourceLocation ModulePrivateLoc,
  13898. MultiTemplateParamsArg TemplateParameterLists,
  13899. bool &OwnedDecl, bool &IsDependent,
  13900. SourceLocation ScopedEnumKWLoc,
  13901. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  13902. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  13903. SkipBodyInfo *SkipBody) {
  13904. // If this is not a definition, it must have a name.
  13905. IdentifierInfo *OrigName = Name;
  13906. assert((Name != nullptr || TUK == TUK_Definition) &&
  13907. "Nameless record must be a definition!");
  13908. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  13909. OwnedDecl = false;
  13910. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  13911. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  13912. // FIXME: Check member specializations more carefully.
  13913. bool isMemberSpecialization = false;
  13914. bool Invalid = false;
  13915. // We only need to do this matching if we have template parameters
  13916. // or a scope specifier, which also conveniently avoids this work
  13917. // for non-C++ cases.
  13918. if (TemplateParameterLists.size() > 0 ||
  13919. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  13920. if (TemplateParameterList *TemplateParams =
  13921. MatchTemplateParametersToScopeSpecifier(
  13922. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  13923. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  13924. if (Kind == TTK_Enum) {
  13925. Diag(KWLoc, diag::err_enum_template);
  13926. return nullptr;
  13927. }
  13928. if (TemplateParams->size() > 0) {
  13929. // This is a declaration or definition of a class template (which may
  13930. // be a member of another template).
  13931. if (Invalid)
  13932. return nullptr;
  13933. OwnedDecl = false;
  13934. DeclResult Result = CheckClassTemplate(
  13935. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  13936. AS, ModulePrivateLoc,
  13937. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  13938. TemplateParameterLists.data(), SkipBody);
  13939. return Result.get();
  13940. } else {
  13941. // The "template<>" header is extraneous.
  13942. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  13943. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  13944. isMemberSpecialization = true;
  13945. }
  13946. }
  13947. if (!TemplateParameterLists.empty() && isMemberSpecialization &&
  13948. CheckTemplateDeclScope(S, TemplateParameterLists.back()))
  13949. return nullptr;
  13950. }
  13951. // Figure out the underlying type if this a enum declaration. We need to do
  13952. // this early, because it's needed to detect if this is an incompatible
  13953. // redeclaration.
  13954. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  13955. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  13956. if (Kind == TTK_Enum) {
  13957. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  13958. // No underlying type explicitly specified, or we failed to parse the
  13959. // type, default to int.
  13960. EnumUnderlying = Context.IntTy.getTypePtr();
  13961. } else if (UnderlyingType.get()) {
  13962. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  13963. // integral type; any cv-qualification is ignored.
  13964. TypeSourceInfo *TI = nullptr;
  13965. GetTypeFromParser(UnderlyingType.get(), &TI);
  13966. EnumUnderlying = TI;
  13967. if (CheckEnumUnderlyingType(TI))
  13968. // Recover by falling back to int.
  13969. EnumUnderlying = Context.IntTy.getTypePtr();
  13970. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  13971. UPPC_FixedUnderlyingType))
  13972. EnumUnderlying = Context.IntTy.getTypePtr();
  13973. } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
  13974. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  13975. // of 'int'. However, if this is an unfixed forward declaration, don't set
  13976. // the underlying type unless the user enables -fms-compatibility. This
  13977. // makes unfixed forward declared enums incomplete and is more conforming.
  13978. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  13979. EnumUnderlying = Context.IntTy.getTypePtr();
  13980. }
  13981. }
  13982. DeclContext *SearchDC = CurContext;
  13983. DeclContext *DC = CurContext;
  13984. bool isStdBadAlloc = false;
  13985. bool isStdAlignValT = false;
  13986. RedeclarationKind Redecl = forRedeclarationInCurContext();
  13987. if (TUK == TUK_Friend || TUK == TUK_Reference)
  13988. Redecl = NotForRedeclaration;
  13989. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  13990. /// implemented asks for structural equivalence checking, the returned decl
  13991. /// here is passed back to the parser, allowing the tag body to be parsed.
  13992. auto createTagFromNewDecl = [&]() -> TagDecl * {
  13993. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  13994. // If there is an identifier, use the location of the identifier as the
  13995. // location of the decl, otherwise use the location of the struct/union
  13996. // keyword.
  13997. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13998. TagDecl *New = nullptr;
  13999. if (Kind == TTK_Enum) {
  14000. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  14001. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  14002. // If this is an undefined enum, bail.
  14003. if (TUK != TUK_Definition && !Invalid)
  14004. return nullptr;
  14005. if (EnumUnderlying) {
  14006. EnumDecl *ED = cast<EnumDecl>(New);
  14007. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  14008. ED->setIntegerTypeSourceInfo(TI);
  14009. else
  14010. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  14011. ED->setPromotionType(ED->getIntegerType());
  14012. }
  14013. } else { // struct/union
  14014. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  14015. nullptr);
  14016. }
  14017. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  14018. // Add alignment attributes if necessary; these attributes are checked
  14019. // when the ASTContext lays out the structure.
  14020. //
  14021. // It is important for implementing the correct semantics that this
  14022. // happen here (in ActOnTag). The #pragma pack stack is
  14023. // maintained as a result of parser callbacks which can occur at
  14024. // many points during the parsing of a struct declaration (because
  14025. // the #pragma tokens are effectively skipped over during the
  14026. // parsing of the struct).
  14027. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  14028. AddAlignmentAttributesForRecord(RD);
  14029. AddMsStructLayoutForRecord(RD);
  14030. }
  14031. }
  14032. New->setLexicalDeclContext(CurContext);
  14033. return New;
  14034. };
  14035. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  14036. if (Name && SS.isNotEmpty()) {
  14037. // We have a nested-name tag ('struct foo::bar').
  14038. // Check for invalid 'foo::'.
  14039. if (SS.isInvalid()) {
  14040. Name = nullptr;
  14041. goto CreateNewDecl;
  14042. }
  14043. // If this is a friend or a reference to a class in a dependent
  14044. // context, don't try to make a decl for it.
  14045. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  14046. DC = computeDeclContext(SS, false);
  14047. if (!DC) {
  14048. IsDependent = true;
  14049. return nullptr;
  14050. }
  14051. } else {
  14052. DC = computeDeclContext(SS, true);
  14053. if (!DC) {
  14054. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  14055. << SS.getRange();
  14056. return nullptr;
  14057. }
  14058. }
  14059. if (RequireCompleteDeclContext(SS, DC))
  14060. return nullptr;
  14061. SearchDC = DC;
  14062. // Look-up name inside 'foo::'.
  14063. LookupQualifiedName(Previous, DC);
  14064. if (Previous.isAmbiguous())
  14065. return nullptr;
  14066. if (Previous.empty()) {
  14067. // Name lookup did not find anything. However, if the
  14068. // nested-name-specifier refers to the current instantiation,
  14069. // and that current instantiation has any dependent base
  14070. // classes, we might find something at instantiation time: treat
  14071. // this as a dependent elaborated-type-specifier.
  14072. // But this only makes any sense for reference-like lookups.
  14073. if (Previous.wasNotFoundInCurrentInstantiation() &&
  14074. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  14075. IsDependent = true;
  14076. return nullptr;
  14077. }
  14078. // A tag 'foo::bar' must already exist.
  14079. Diag(NameLoc, diag::err_not_tag_in_scope)
  14080. << Kind << Name << DC << SS.getRange();
  14081. Name = nullptr;
  14082. Invalid = true;
  14083. goto CreateNewDecl;
  14084. }
  14085. } else if (Name) {
  14086. // C++14 [class.mem]p14:
  14087. // If T is the name of a class, then each of the following shall have a
  14088. // name different from T:
  14089. // -- every member of class T that is itself a type
  14090. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  14091. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  14092. return nullptr;
  14093. // If this is a named struct, check to see if there was a previous forward
  14094. // declaration or definition.
  14095. // FIXME: We're looking into outer scopes here, even when we
  14096. // shouldn't be. Doing so can result in ambiguities that we
  14097. // shouldn't be diagnosing.
  14098. LookupName(Previous, S);
  14099. // When declaring or defining a tag, ignore ambiguities introduced
  14100. // by types using'ed into this scope.
  14101. if (Previous.isAmbiguous() &&
  14102. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  14103. LookupResult::Filter F = Previous.makeFilter();
  14104. while (F.hasNext()) {
  14105. NamedDecl *ND = F.next();
  14106. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  14107. SearchDC->getRedeclContext()))
  14108. F.erase();
  14109. }
  14110. F.done();
  14111. }
  14112. // C++11 [namespace.memdef]p3:
  14113. // If the name in a friend declaration is neither qualified nor
  14114. // a template-id and the declaration is a function or an
  14115. // elaborated-type-specifier, the lookup to determine whether
  14116. // the entity has been previously declared shall not consider
  14117. // any scopes outside the innermost enclosing namespace.
  14118. //
  14119. // MSVC doesn't implement the above rule for types, so a friend tag
  14120. // declaration may be a redeclaration of a type declared in an enclosing
  14121. // scope. They do implement this rule for friend functions.
  14122. //
  14123. // Does it matter that this should be by scope instead of by
  14124. // semantic context?
  14125. if (!Previous.empty() && TUK == TUK_Friend) {
  14126. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  14127. LookupResult::Filter F = Previous.makeFilter();
  14128. bool FriendSawTagOutsideEnclosingNamespace = false;
  14129. while (F.hasNext()) {
  14130. NamedDecl *ND = F.next();
  14131. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  14132. if (DC->isFileContext() &&
  14133. !EnclosingNS->Encloses(ND->getDeclContext())) {
  14134. if (getLangOpts().MSVCCompat)
  14135. FriendSawTagOutsideEnclosingNamespace = true;
  14136. else
  14137. F.erase();
  14138. }
  14139. }
  14140. F.done();
  14141. // Diagnose this MSVC extension in the easy case where lookup would have
  14142. // unambiguously found something outside the enclosing namespace.
  14143. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  14144. NamedDecl *ND = Previous.getFoundDecl();
  14145. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  14146. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  14147. }
  14148. }
  14149. // Note: there used to be some attempt at recovery here.
  14150. if (Previous.isAmbiguous())
  14151. return nullptr;
  14152. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  14153. // FIXME: This makes sure that we ignore the contexts associated
  14154. // with C structs, unions, and enums when looking for a matching
  14155. // tag declaration or definition. See the similar lookup tweak
  14156. // in Sema::LookupName; is there a better way to deal with this?
  14157. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  14158. SearchDC = SearchDC->getParent();
  14159. }
  14160. }
  14161. if (Previous.isSingleResult() &&
  14162. Previous.getFoundDecl()->isTemplateParameter()) {
  14163. // Maybe we will complain about the shadowed template parameter.
  14164. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  14165. // Just pretend that we didn't see the previous declaration.
  14166. Previous.clear();
  14167. }
  14168. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  14169. DC->Equals(getStdNamespace())) {
  14170. if (Name->isStr("bad_alloc")) {
  14171. // This is a declaration of or a reference to "std::bad_alloc".
  14172. isStdBadAlloc = true;
  14173. // If std::bad_alloc has been implicitly declared (but made invisible to
  14174. // name lookup), fill in this implicit declaration as the previous
  14175. // declaration, so that the declarations get chained appropriately.
  14176. if (Previous.empty() && StdBadAlloc)
  14177. Previous.addDecl(getStdBadAlloc());
  14178. } else if (Name->isStr("align_val_t")) {
  14179. isStdAlignValT = true;
  14180. if (Previous.empty() && StdAlignValT)
  14181. Previous.addDecl(getStdAlignValT());
  14182. }
  14183. }
  14184. // If we didn't find a previous declaration, and this is a reference
  14185. // (or friend reference), move to the correct scope. In C++, we
  14186. // also need to do a redeclaration lookup there, just in case
  14187. // there's a shadow friend decl.
  14188. if (Name && Previous.empty() &&
  14189. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  14190. if (Invalid) goto CreateNewDecl;
  14191. assert(SS.isEmpty());
  14192. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  14193. // C++ [basic.scope.pdecl]p5:
  14194. // -- for an elaborated-type-specifier of the form
  14195. //
  14196. // class-key identifier
  14197. //
  14198. // if the elaborated-type-specifier is used in the
  14199. // decl-specifier-seq or parameter-declaration-clause of a
  14200. // function defined in namespace scope, the identifier is
  14201. // declared as a class-name in the namespace that contains
  14202. // the declaration; otherwise, except as a friend
  14203. // declaration, the identifier is declared in the smallest
  14204. // non-class, non-function-prototype scope that contains the
  14205. // declaration.
  14206. //
  14207. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  14208. // C structs and unions.
  14209. //
  14210. // It is an error in C++ to declare (rather than define) an enum
  14211. // type, including via an elaborated type specifier. We'll
  14212. // diagnose that later; for now, declare the enum in the same
  14213. // scope as we would have picked for any other tag type.
  14214. //
  14215. // GNU C also supports this behavior as part of its incomplete
  14216. // enum types extension, while GNU C++ does not.
  14217. //
  14218. // Find the context where we'll be declaring the tag.
  14219. // FIXME: We would like to maintain the current DeclContext as the
  14220. // lexical context,
  14221. SearchDC = getTagInjectionContext(SearchDC);
  14222. // Find the scope where we'll be declaring the tag.
  14223. S = getTagInjectionScope(S, getLangOpts());
  14224. } else {
  14225. assert(TUK == TUK_Friend);
  14226. // C++ [namespace.memdef]p3:
  14227. // If a friend declaration in a non-local class first declares a
  14228. // class or function, the friend class or function is a member of
  14229. // the innermost enclosing namespace.
  14230. SearchDC = SearchDC->getEnclosingNamespaceContext();
  14231. }
  14232. // In C++, we need to do a redeclaration lookup to properly
  14233. // diagnose some problems.
  14234. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  14235. // hidden declaration so that we don't get ambiguity errors when using a
  14236. // type declared by an elaborated-type-specifier. In C that is not correct
  14237. // and we should instead merge compatible types found by lookup.
  14238. if (getLangOpts().CPlusPlus) {
  14239. // FIXME: This can perform qualified lookups into function contexts,
  14240. // which are meaningless.
  14241. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  14242. LookupQualifiedName(Previous, SearchDC);
  14243. } else {
  14244. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  14245. LookupName(Previous, S);
  14246. }
  14247. }
  14248. // If we have a known previous declaration to use, then use it.
  14249. if (Previous.empty() && SkipBody && SkipBody->Previous)
  14250. Previous.addDecl(SkipBody->Previous);
  14251. if (!Previous.empty()) {
  14252. NamedDecl *PrevDecl = Previous.getFoundDecl();
  14253. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  14254. // It's okay to have a tag decl in the same scope as a typedef
  14255. // which hides a tag decl in the same scope. Finding this
  14256. // with a redeclaration lookup can only actually happen in C++.
  14257. //
  14258. // This is also okay for elaborated-type-specifiers, which is
  14259. // technically forbidden by the current standard but which is
  14260. // okay according to the likely resolution of an open issue;
  14261. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  14262. if (getLangOpts().CPlusPlus) {
  14263. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  14264. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  14265. TagDecl *Tag = TT->getDecl();
  14266. if (Tag->getDeclName() == Name &&
  14267. Tag->getDeclContext()->getRedeclContext()
  14268. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  14269. PrevDecl = Tag;
  14270. Previous.clear();
  14271. Previous.addDecl(Tag);
  14272. Previous.resolveKind();
  14273. }
  14274. }
  14275. }
  14276. }
  14277. // If this is a redeclaration of a using shadow declaration, it must
  14278. // declare a tag in the same context. In MSVC mode, we allow a
  14279. // redefinition if either context is within the other.
  14280. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  14281. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  14282. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  14283. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  14284. !(OldTag && isAcceptableTagRedeclContext(
  14285. *this, OldTag->getDeclContext(), SearchDC))) {
  14286. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  14287. Diag(Shadow->getTargetDecl()->getLocation(),
  14288. diag::note_using_decl_target);
  14289. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
  14290. << 0;
  14291. // Recover by ignoring the old declaration.
  14292. Previous.clear();
  14293. goto CreateNewDecl;
  14294. }
  14295. }
  14296. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  14297. // If this is a use of a previous tag, or if the tag is already declared
  14298. // in the same scope (so that the definition/declaration completes or
  14299. // rementions the tag), reuse the decl.
  14300. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  14301. isDeclInScope(DirectPrevDecl, SearchDC, S,
  14302. SS.isNotEmpty() || isMemberSpecialization)) {
  14303. // Make sure that this wasn't declared as an enum and now used as a
  14304. // struct or something similar.
  14305. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  14306. TUK == TUK_Definition, KWLoc,
  14307. Name)) {
  14308. bool SafeToContinue
  14309. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  14310. Kind != TTK_Enum);
  14311. if (SafeToContinue)
  14312. Diag(KWLoc, diag::err_use_with_wrong_tag)
  14313. << Name
  14314. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  14315. PrevTagDecl->getKindName());
  14316. else
  14317. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  14318. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  14319. if (SafeToContinue)
  14320. Kind = PrevTagDecl->getTagKind();
  14321. else {
  14322. // Recover by making this an anonymous redefinition.
  14323. Name = nullptr;
  14324. Previous.clear();
  14325. Invalid = true;
  14326. }
  14327. }
  14328. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  14329. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  14330. if (TUK == TUK_Reference || TUK == TUK_Friend)
  14331. return PrevTagDecl;
  14332. QualType EnumUnderlyingTy;
  14333. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  14334. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  14335. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  14336. EnumUnderlyingTy = QualType(T, 0);
  14337. // All conflicts with previous declarations are recovered by
  14338. // returning the previous declaration, unless this is a definition,
  14339. // in which case we want the caller to bail out.
  14340. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  14341. ScopedEnum, EnumUnderlyingTy,
  14342. IsFixed, PrevEnum))
  14343. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  14344. }
  14345. // C++11 [class.mem]p1:
  14346. // A member shall not be declared twice in the member-specification,
  14347. // except that a nested class or member class template can be declared
  14348. // and then later defined.
  14349. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  14350. S->isDeclScope(PrevDecl)) {
  14351. Diag(NameLoc, diag::ext_member_redeclared);
  14352. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  14353. }
  14354. if (!Invalid) {
  14355. // If this is a use, just return the declaration we found, unless
  14356. // we have attributes.
  14357. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  14358. if (!Attrs.empty()) {
  14359. // FIXME: Diagnose these attributes. For now, we create a new
  14360. // declaration to hold them.
  14361. } else if (TUK == TUK_Reference &&
  14362. (PrevTagDecl->getFriendObjectKind() ==
  14363. Decl::FOK_Undeclared ||
  14364. PrevDecl->getOwningModule() != getCurrentModule()) &&
  14365. SS.isEmpty()) {
  14366. // This declaration is a reference to an existing entity, but
  14367. // has different visibility from that entity: it either makes
  14368. // a friend visible or it makes a type visible in a new module.
  14369. // In either case, create a new declaration. We only do this if
  14370. // the declaration would have meant the same thing if no prior
  14371. // declaration were found, that is, if it was found in the same
  14372. // scope where we would have injected a declaration.
  14373. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  14374. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  14375. return PrevTagDecl;
  14376. // This is in the injected scope, create a new declaration in
  14377. // that scope.
  14378. S = getTagInjectionScope(S, getLangOpts());
  14379. } else {
  14380. return PrevTagDecl;
  14381. }
  14382. }
  14383. // Diagnose attempts to redefine a tag.
  14384. if (TUK == TUK_Definition) {
  14385. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  14386. // If we're defining a specialization and the previous definition
  14387. // is from an implicit instantiation, don't emit an error
  14388. // here; we'll catch this in the general case below.
  14389. bool IsExplicitSpecializationAfterInstantiation = false;
  14390. if (isMemberSpecialization) {
  14391. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  14392. IsExplicitSpecializationAfterInstantiation =
  14393. RD->getTemplateSpecializationKind() !=
  14394. TSK_ExplicitSpecialization;
  14395. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  14396. IsExplicitSpecializationAfterInstantiation =
  14397. ED->getTemplateSpecializationKind() !=
  14398. TSK_ExplicitSpecialization;
  14399. }
  14400. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  14401. // not keep more that one definition around (merge them). However,
  14402. // ensure the decl passes the structural compatibility check in
  14403. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  14404. NamedDecl *Hidden = nullptr;
  14405. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  14406. // There is a definition of this tag, but it is not visible. We
  14407. // explicitly make use of C++'s one definition rule here, and
  14408. // assume that this definition is identical to the hidden one
  14409. // we already have. Make the existing definition visible and
  14410. // use it in place of this one.
  14411. if (!getLangOpts().CPlusPlus) {
  14412. // Postpone making the old definition visible until after we
  14413. // complete parsing the new one and do the structural
  14414. // comparison.
  14415. SkipBody->CheckSameAsPrevious = true;
  14416. SkipBody->New = createTagFromNewDecl();
  14417. SkipBody->Previous = Def;
  14418. return Def;
  14419. } else {
  14420. SkipBody->ShouldSkip = true;
  14421. SkipBody->Previous = Def;
  14422. makeMergedDefinitionVisible(Hidden);
  14423. // Carry on and handle it like a normal definition. We'll
  14424. // skip starting the definitiion later.
  14425. }
  14426. } else if (!IsExplicitSpecializationAfterInstantiation) {
  14427. // A redeclaration in function prototype scope in C isn't
  14428. // visible elsewhere, so merely issue a warning.
  14429. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  14430. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  14431. else
  14432. Diag(NameLoc, diag::err_redefinition) << Name;
  14433. notePreviousDefinition(Def,
  14434. NameLoc.isValid() ? NameLoc : KWLoc);
  14435. // If this is a redefinition, recover by making this
  14436. // struct be anonymous, which will make any later
  14437. // references get the previous definition.
  14438. Name = nullptr;
  14439. Previous.clear();
  14440. Invalid = true;
  14441. }
  14442. } else {
  14443. // If the type is currently being defined, complain
  14444. // about a nested redefinition.
  14445. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  14446. if (TD->isBeingDefined()) {
  14447. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  14448. Diag(PrevTagDecl->getLocation(),
  14449. diag::note_previous_definition);
  14450. Name = nullptr;
  14451. Previous.clear();
  14452. Invalid = true;
  14453. }
  14454. }
  14455. // Okay, this is definition of a previously declared or referenced
  14456. // tag. We're going to create a new Decl for it.
  14457. }
  14458. // Okay, we're going to make a redeclaration. If this is some kind
  14459. // of reference, make sure we build the redeclaration in the same DC
  14460. // as the original, and ignore the current access specifier.
  14461. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  14462. SearchDC = PrevTagDecl->getDeclContext();
  14463. AS = AS_none;
  14464. }
  14465. }
  14466. // If we get here we have (another) forward declaration or we
  14467. // have a definition. Just create a new decl.
  14468. } else {
  14469. // If we get here, this is a definition of a new tag type in a nested
  14470. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  14471. // new decl/type. We set PrevDecl to NULL so that the entities
  14472. // have distinct types.
  14473. Previous.clear();
  14474. }
  14475. // If we get here, we're going to create a new Decl. If PrevDecl
  14476. // is non-NULL, it's a definition of the tag declared by
  14477. // PrevDecl. If it's NULL, we have a new definition.
  14478. // Otherwise, PrevDecl is not a tag, but was found with tag
  14479. // lookup. This is only actually possible in C++, where a few
  14480. // things like templates still live in the tag namespace.
  14481. } else {
  14482. // Use a better diagnostic if an elaborated-type-specifier
  14483. // found the wrong kind of type on the first
  14484. // (non-redeclaration) lookup.
  14485. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  14486. !Previous.isForRedeclaration()) {
  14487. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  14488. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  14489. << Kind;
  14490. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  14491. Invalid = true;
  14492. // Otherwise, only diagnose if the declaration is in scope.
  14493. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  14494. SS.isNotEmpty() || isMemberSpecialization)) {
  14495. // do nothing
  14496. // Diagnose implicit declarations introduced by elaborated types.
  14497. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  14498. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  14499. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  14500. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  14501. Invalid = true;
  14502. // Otherwise it's a declaration. Call out a particularly common
  14503. // case here.
  14504. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  14505. unsigned Kind = 0;
  14506. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  14507. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  14508. << Name << Kind << TND->getUnderlyingType();
  14509. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  14510. Invalid = true;
  14511. // Otherwise, diagnose.
  14512. } else {
  14513. // The tag name clashes with something else in the target scope,
  14514. // issue an error and recover by making this tag be anonymous.
  14515. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  14516. notePreviousDefinition(PrevDecl, NameLoc);
  14517. Name = nullptr;
  14518. Invalid = true;
  14519. }
  14520. // The existing declaration isn't relevant to us; we're in a
  14521. // new scope, so clear out the previous declaration.
  14522. Previous.clear();
  14523. }
  14524. }
  14525. CreateNewDecl:
  14526. TagDecl *PrevDecl = nullptr;
  14527. if (Previous.isSingleResult())
  14528. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  14529. // If there is an identifier, use the location of the identifier as the
  14530. // location of the decl, otherwise use the location of the struct/union
  14531. // keyword.
  14532. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  14533. // Otherwise, create a new declaration. If there is a previous
  14534. // declaration of the same entity, the two will be linked via
  14535. // PrevDecl.
  14536. TagDecl *New;
  14537. if (Kind == TTK_Enum) {
  14538. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  14539. // enum X { A, B, C } D; D should chain to X.
  14540. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  14541. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  14542. ScopedEnumUsesClassTag, IsFixed);
  14543. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  14544. StdAlignValT = cast<EnumDecl>(New);
  14545. // If this is an undefined enum, warn.
  14546. if (TUK != TUK_Definition && !Invalid) {
  14547. TagDecl *Def;
  14548. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  14549. // C++0x: 7.2p2: opaque-enum-declaration.
  14550. // Conflicts are diagnosed above. Do nothing.
  14551. }
  14552. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  14553. Diag(Loc, diag::ext_forward_ref_enum_def)
  14554. << New;
  14555. Diag(Def->getLocation(), diag::note_previous_definition);
  14556. } else {
  14557. unsigned DiagID = diag::ext_forward_ref_enum;
  14558. if (getLangOpts().MSVCCompat)
  14559. DiagID = diag::ext_ms_forward_ref_enum;
  14560. else if (getLangOpts().CPlusPlus)
  14561. DiagID = diag::err_forward_ref_enum;
  14562. Diag(Loc, DiagID);
  14563. }
  14564. }
  14565. if (EnumUnderlying) {
  14566. EnumDecl *ED = cast<EnumDecl>(New);
  14567. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  14568. ED->setIntegerTypeSourceInfo(TI);
  14569. else
  14570. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  14571. ED->setPromotionType(ED->getIntegerType());
  14572. assert(ED->isComplete() && "enum with type should be complete");
  14573. }
  14574. } else {
  14575. // struct/union/class
  14576. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  14577. // struct X { int A; } D; D should chain to X.
  14578. if (getLangOpts().CPlusPlus) {
  14579. // FIXME: Look for a way to use RecordDecl for simple structs.
  14580. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  14581. cast_or_null<CXXRecordDecl>(PrevDecl));
  14582. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  14583. StdBadAlloc = cast<CXXRecordDecl>(New);
  14584. } else
  14585. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  14586. cast_or_null<RecordDecl>(PrevDecl));
  14587. }
  14588. // C++11 [dcl.type]p3:
  14589. // A type-specifier-seq shall not define a class or enumeration [...].
  14590. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  14591. TUK == TUK_Definition) {
  14592. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  14593. << Context.getTagDeclType(New);
  14594. Invalid = true;
  14595. }
  14596. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  14597. DC->getDeclKind() == Decl::Enum) {
  14598. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  14599. << Context.getTagDeclType(New);
  14600. Invalid = true;
  14601. }
  14602. // Maybe add qualifier info.
  14603. if (SS.isNotEmpty()) {
  14604. if (SS.isSet()) {
  14605. // If this is either a declaration or a definition, check the
  14606. // nested-name-specifier against the current context.
  14607. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  14608. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  14609. isMemberSpecialization))
  14610. Invalid = true;
  14611. New->setQualifierInfo(SS.getWithLocInContext(Context));
  14612. if (TemplateParameterLists.size() > 0) {
  14613. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  14614. }
  14615. }
  14616. else
  14617. Invalid = true;
  14618. }
  14619. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  14620. // Add alignment attributes if necessary; these attributes are checked when
  14621. // the ASTContext lays out the structure.
  14622. //
  14623. // It is important for implementing the correct semantics that this
  14624. // happen here (in ActOnTag). The #pragma pack stack is
  14625. // maintained as a result of parser callbacks which can occur at
  14626. // many points during the parsing of a struct declaration (because
  14627. // the #pragma tokens are effectively skipped over during the
  14628. // parsing of the struct).
  14629. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  14630. AddAlignmentAttributesForRecord(RD);
  14631. AddMsStructLayoutForRecord(RD);
  14632. }
  14633. }
  14634. if (ModulePrivateLoc.isValid()) {
  14635. if (isMemberSpecialization)
  14636. Diag(New->getLocation(), diag::err_module_private_specialization)
  14637. << 2
  14638. << FixItHint::CreateRemoval(ModulePrivateLoc);
  14639. // __module_private__ does not apply to local classes. However, we only
  14640. // diagnose this as an error when the declaration specifiers are
  14641. // freestanding. Here, we just ignore the __module_private__.
  14642. else if (!SearchDC->isFunctionOrMethod())
  14643. New->setModulePrivate();
  14644. }
  14645. // If this is a specialization of a member class (of a class template),
  14646. // check the specialization.
  14647. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  14648. Invalid = true;
  14649. // If we're declaring or defining a tag in function prototype scope in C,
  14650. // note that this type can only be used within the function and add it to
  14651. // the list of decls to inject into the function definition scope.
  14652. if ((Name || Kind == TTK_Enum) &&
  14653. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  14654. if (getLangOpts().CPlusPlus) {
  14655. // C++ [dcl.fct]p6:
  14656. // Types shall not be defined in return or parameter types.
  14657. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  14658. Diag(Loc, diag::err_type_defined_in_param_type)
  14659. << Name;
  14660. Invalid = true;
  14661. }
  14662. } else if (!PrevDecl) {
  14663. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  14664. }
  14665. }
  14666. if (Invalid)
  14667. New->setInvalidDecl();
  14668. // Set the lexical context. If the tag has a C++ scope specifier, the
  14669. // lexical context will be different from the semantic context.
  14670. New->setLexicalDeclContext(CurContext);
  14671. // Mark this as a friend decl if applicable.
  14672. // In Microsoft mode, a friend declaration also acts as a forward
  14673. // declaration so we always pass true to setObjectOfFriendDecl to make
  14674. // the tag name visible.
  14675. if (TUK == TUK_Friend)
  14676. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  14677. // Set the access specifier.
  14678. if (!Invalid && SearchDC->isRecord())
  14679. SetMemberAccessSpecifier(New, PrevDecl, AS);
  14680. if (PrevDecl)
  14681. CheckRedeclarationInModule(New, PrevDecl);
  14682. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  14683. New->startDefinition();
  14684. ProcessDeclAttributeList(S, New, Attrs);
  14685. AddPragmaAttributes(S, New);
  14686. // If this has an identifier, add it to the scope stack.
  14687. if (TUK == TUK_Friend) {
  14688. // We might be replacing an existing declaration in the lookup tables;
  14689. // if so, borrow its access specifier.
  14690. if (PrevDecl)
  14691. New->setAccess(PrevDecl->getAccess());
  14692. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  14693. DC->makeDeclVisibleInContext(New);
  14694. if (Name) // can be null along some error paths
  14695. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  14696. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  14697. } else if (Name) {
  14698. S = getNonFieldDeclScope(S);
  14699. PushOnScopeChains(New, S, true);
  14700. } else {
  14701. CurContext->addDecl(New);
  14702. }
  14703. // If this is the C FILE type, notify the AST context.
  14704. if (IdentifierInfo *II = New->getIdentifier())
  14705. if (!New->isInvalidDecl() &&
  14706. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  14707. II->isStr("FILE"))
  14708. Context.setFILEDecl(New);
  14709. if (PrevDecl)
  14710. mergeDeclAttributes(New, PrevDecl);
  14711. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  14712. inferGslOwnerPointerAttribute(CXXRD);
  14713. // If there's a #pragma GCC visibility in scope, set the visibility of this
  14714. // record.
  14715. AddPushedVisibilityAttribute(New);
  14716. if (isMemberSpecialization && !New->isInvalidDecl())
  14717. CompleteMemberSpecialization(New, Previous);
  14718. OwnedDecl = true;
  14719. // In C++, don't return an invalid declaration. We can't recover well from
  14720. // the cases where we make the type anonymous.
  14721. if (Invalid && getLangOpts().CPlusPlus) {
  14722. if (New->isBeingDefined())
  14723. if (auto RD = dyn_cast<RecordDecl>(New))
  14724. RD->completeDefinition();
  14725. return nullptr;
  14726. } else if (SkipBody && SkipBody->ShouldSkip) {
  14727. return SkipBody->Previous;
  14728. } else {
  14729. return New;
  14730. }
  14731. }
  14732. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  14733. AdjustDeclIfTemplate(TagD);
  14734. TagDecl *Tag = cast<TagDecl>(TagD);
  14735. // Enter the tag context.
  14736. PushDeclContext(S, Tag);
  14737. ActOnDocumentableDecl(TagD);
  14738. // If there's a #pragma GCC visibility in scope, set the visibility of this
  14739. // record.
  14740. AddPushedVisibilityAttribute(Tag);
  14741. }
  14742. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  14743. SkipBodyInfo &SkipBody) {
  14744. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  14745. return false;
  14746. // Make the previous decl visible.
  14747. makeMergedDefinitionVisible(SkipBody.Previous);
  14748. return true;
  14749. }
  14750. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  14751. assert(isa<ObjCContainerDecl>(IDecl) &&
  14752. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  14753. DeclContext *OCD = cast<DeclContext>(IDecl);
  14754. assert(OCD->getLexicalParent() == CurContext &&
  14755. "The next DeclContext should be lexically contained in the current one.");
  14756. CurContext = OCD;
  14757. return IDecl;
  14758. }
  14759. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  14760. SourceLocation FinalLoc,
  14761. bool IsFinalSpelledSealed,
  14762. bool IsAbstract,
  14763. SourceLocation LBraceLoc) {
  14764. AdjustDeclIfTemplate(TagD);
  14765. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  14766. FieldCollector->StartClass();
  14767. if (!Record->getIdentifier())
  14768. return;
  14769. if (IsAbstract)
  14770. Record->markAbstract();
  14771. if (FinalLoc.isValid()) {
  14772. Record->addAttr(FinalAttr::Create(
  14773. Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
  14774. static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
  14775. }
  14776. // C++ [class]p2:
  14777. // [...] The class-name is also inserted into the scope of the
  14778. // class itself; this is known as the injected-class-name. For
  14779. // purposes of access checking, the injected-class-name is treated
  14780. // as if it were a public member name.
  14781. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  14782. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  14783. Record->getLocation(), Record->getIdentifier(),
  14784. /*PrevDecl=*/nullptr,
  14785. /*DelayTypeCreation=*/true);
  14786. Context.getTypeDeclType(InjectedClassName, Record);
  14787. InjectedClassName->setImplicit();
  14788. InjectedClassName->setAccess(AS_public);
  14789. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  14790. InjectedClassName->setDescribedClassTemplate(Template);
  14791. PushOnScopeChains(InjectedClassName, S);
  14792. assert(InjectedClassName->isInjectedClassName() &&
  14793. "Broken injected-class-name");
  14794. }
  14795. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  14796. SourceRange BraceRange) {
  14797. AdjustDeclIfTemplate(TagD);
  14798. TagDecl *Tag = cast<TagDecl>(TagD);
  14799. Tag->setBraceRange(BraceRange);
  14800. // Make sure we "complete" the definition even it is invalid.
  14801. if (Tag->isBeingDefined()) {
  14802. assert(Tag->isInvalidDecl() && "We should already have completed it");
  14803. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  14804. RD->completeDefinition();
  14805. }
  14806. if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  14807. FieldCollector->FinishClass();
  14808. if (RD->hasAttr<SYCLSpecialClassAttr>()) {
  14809. auto *Def = RD->getDefinition();
  14810. assert(Def && "The record is expected to have a completed definition");
  14811. unsigned NumInitMethods = 0;
  14812. for (auto *Method : Def->methods()) {
  14813. if (!Method->getIdentifier())
  14814. continue;
  14815. if (Method->getName() == "__init")
  14816. NumInitMethods++;
  14817. }
  14818. if (NumInitMethods > 1 || !Def->hasInitMethod())
  14819. Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
  14820. }
  14821. }
  14822. // Exit this scope of this tag's definition.
  14823. PopDeclContext();
  14824. if (getCurLexicalContext()->isObjCContainer() &&
  14825. Tag->getDeclContext()->isFileContext())
  14826. Tag->setTopLevelDeclInObjCContainer();
  14827. // Notify the consumer that we've defined a tag.
  14828. if (!Tag->isInvalidDecl())
  14829. Consumer.HandleTagDeclDefinition(Tag);
  14830. // Clangs implementation of #pragma align(packed) differs in bitfield layout
  14831. // from XLs and instead matches the XL #pragma pack(1) behavior.
  14832. if (Context.getTargetInfo().getTriple().isOSAIX() &&
  14833. AlignPackStack.hasValue()) {
  14834. AlignPackInfo APInfo = AlignPackStack.CurrentValue;
  14835. // Only diagnose #pragma align(packed).
  14836. if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
  14837. return;
  14838. const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
  14839. if (!RD)
  14840. return;
  14841. // Only warn if there is at least 1 bitfield member.
  14842. if (llvm::any_of(RD->fields(),
  14843. [](const FieldDecl *FD) { return FD->isBitField(); }))
  14844. Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
  14845. }
  14846. }
  14847. void Sema::ActOnObjCContainerFinishDefinition() {
  14848. // Exit this scope of this interface definition.
  14849. PopDeclContext();
  14850. }
  14851. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  14852. assert(DC == CurContext && "Mismatch of container contexts");
  14853. OriginalLexicalContext = DC;
  14854. ActOnObjCContainerFinishDefinition();
  14855. }
  14856. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  14857. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  14858. OriginalLexicalContext = nullptr;
  14859. }
  14860. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  14861. AdjustDeclIfTemplate(TagD);
  14862. TagDecl *Tag = cast<TagDecl>(TagD);
  14863. Tag->setInvalidDecl();
  14864. // Make sure we "complete" the definition even it is invalid.
  14865. if (Tag->isBeingDefined()) {
  14866. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  14867. RD->completeDefinition();
  14868. }
  14869. // We're undoing ActOnTagStartDefinition here, not
  14870. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  14871. // the FieldCollector.
  14872. PopDeclContext();
  14873. }
  14874. // Note that FieldName may be null for anonymous bitfields.
  14875. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  14876. IdentifierInfo *FieldName,
  14877. QualType FieldTy, bool IsMsStruct,
  14878. Expr *BitWidth, bool *ZeroWidth) {
  14879. assert(BitWidth);
  14880. if (BitWidth->containsErrors())
  14881. return ExprError();
  14882. // Default to true; that shouldn't confuse checks for emptiness
  14883. if (ZeroWidth)
  14884. *ZeroWidth = true;
  14885. // C99 6.7.2.1p4 - verify the field type.
  14886. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  14887. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  14888. // Handle incomplete and sizeless types with a specific error.
  14889. if (RequireCompleteSizedType(FieldLoc, FieldTy,
  14890. diag::err_field_incomplete_or_sizeless))
  14891. return ExprError();
  14892. if (FieldName)
  14893. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  14894. << FieldName << FieldTy << BitWidth->getSourceRange();
  14895. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  14896. << FieldTy << BitWidth->getSourceRange();
  14897. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  14898. UPPC_BitFieldWidth))
  14899. return ExprError();
  14900. // If the bit-width is type- or value-dependent, don't try to check
  14901. // it now.
  14902. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  14903. return BitWidth;
  14904. llvm::APSInt Value;
  14905. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
  14906. if (ICE.isInvalid())
  14907. return ICE;
  14908. BitWidth = ICE.get();
  14909. if (Value != 0 && ZeroWidth)
  14910. *ZeroWidth = false;
  14911. // Zero-width bitfield is ok for anonymous field.
  14912. if (Value == 0 && FieldName)
  14913. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  14914. if (Value.isSigned() && Value.isNegative()) {
  14915. if (FieldName)
  14916. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  14917. << FieldName << toString(Value, 10);
  14918. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  14919. << toString(Value, 10);
  14920. }
  14921. // The size of the bit-field must not exceed our maximum permitted object
  14922. // size.
  14923. if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
  14924. return Diag(FieldLoc, diag::err_bitfield_too_wide)
  14925. << !FieldName << FieldName << toString(Value, 10);
  14926. }
  14927. if (!FieldTy->isDependentType()) {
  14928. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  14929. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  14930. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  14931. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  14932. // ABI.
  14933. bool CStdConstraintViolation =
  14934. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  14935. bool MSBitfieldViolation =
  14936. Value.ugt(TypeStorageSize) &&
  14937. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  14938. if (CStdConstraintViolation || MSBitfieldViolation) {
  14939. unsigned DiagWidth =
  14940. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  14941. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  14942. << (bool)FieldName << FieldName << toString(Value, 10)
  14943. << !CStdConstraintViolation << DiagWidth;
  14944. }
  14945. // Warn on types where the user might conceivably expect to get all
  14946. // specified bits as value bits: that's all integral types other than
  14947. // 'bool'.
  14948. if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
  14949. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  14950. << FieldName << toString(Value, 10)
  14951. << (unsigned)TypeWidth;
  14952. }
  14953. }
  14954. return BitWidth;
  14955. }
  14956. /// ActOnField - Each field of a C struct/union is passed into this in order
  14957. /// to create a FieldDecl object for it.
  14958. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  14959. Declarator &D, Expr *BitfieldWidth) {
  14960. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  14961. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  14962. /*InitStyle=*/ICIS_NoInit, AS_public);
  14963. return Res;
  14964. }
  14965. /// HandleField - Analyze a field of a C struct or a C++ data member.
  14966. ///
  14967. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  14968. SourceLocation DeclStart,
  14969. Declarator &D, Expr *BitWidth,
  14970. InClassInitStyle InitStyle,
  14971. AccessSpecifier AS) {
  14972. if (D.isDecompositionDeclarator()) {
  14973. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  14974. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  14975. << Decomp.getSourceRange();
  14976. return nullptr;
  14977. }
  14978. IdentifierInfo *II = D.getIdentifier();
  14979. SourceLocation Loc = DeclStart;
  14980. if (II) Loc = D.getIdentifierLoc();
  14981. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  14982. QualType T = TInfo->getType();
  14983. if (getLangOpts().CPlusPlus) {
  14984. CheckExtraCXXDefaultArguments(D);
  14985. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  14986. UPPC_DataMemberType)) {
  14987. D.setInvalidType();
  14988. T = Context.IntTy;
  14989. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  14990. }
  14991. }
  14992. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  14993. if (D.getDeclSpec().isInlineSpecified())
  14994. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  14995. << getLangOpts().CPlusPlus17;
  14996. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  14997. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  14998. diag::err_invalid_thread)
  14999. << DeclSpec::getSpecifierName(TSCS);
  15000. // Check to see if this name was declared as a member previously
  15001. NamedDecl *PrevDecl = nullptr;
  15002. LookupResult Previous(*this, II, Loc, LookupMemberName,
  15003. ForVisibleRedeclaration);
  15004. LookupName(Previous, S);
  15005. switch (Previous.getResultKind()) {
  15006. case LookupResult::Found:
  15007. case LookupResult::FoundUnresolvedValue:
  15008. PrevDecl = Previous.getAsSingle<NamedDecl>();
  15009. break;
  15010. case LookupResult::FoundOverloaded:
  15011. PrevDecl = Previous.getRepresentativeDecl();
  15012. break;
  15013. case LookupResult::NotFound:
  15014. case LookupResult::NotFoundInCurrentInstantiation:
  15015. case LookupResult::Ambiguous:
  15016. break;
  15017. }
  15018. Previous.suppressDiagnostics();
  15019. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15020. // Maybe we will complain about the shadowed template parameter.
  15021. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  15022. // Just pretend that we didn't see the previous declaration.
  15023. PrevDecl = nullptr;
  15024. }
  15025. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  15026. PrevDecl = nullptr;
  15027. bool Mutable
  15028. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  15029. SourceLocation TSSL = D.getBeginLoc();
  15030. FieldDecl *NewFD
  15031. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  15032. TSSL, AS, PrevDecl, &D);
  15033. if (NewFD->isInvalidDecl())
  15034. Record->setInvalidDecl();
  15035. if (D.getDeclSpec().isModulePrivateSpecified())
  15036. NewFD->setModulePrivate();
  15037. if (NewFD->isInvalidDecl() && PrevDecl) {
  15038. // Don't introduce NewFD into scope; there's already something
  15039. // with the same name in the same scope.
  15040. } else if (II) {
  15041. PushOnScopeChains(NewFD, S);
  15042. } else
  15043. Record->addDecl(NewFD);
  15044. return NewFD;
  15045. }
  15046. /// Build a new FieldDecl and check its well-formedness.
  15047. ///
  15048. /// This routine builds a new FieldDecl given the fields name, type,
  15049. /// record, etc. \p PrevDecl should refer to any previous declaration
  15050. /// with the same name and in the same scope as the field to be
  15051. /// created.
  15052. ///
  15053. /// \returns a new FieldDecl.
  15054. ///
  15055. /// \todo The Declarator argument is a hack. It will be removed once
  15056. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  15057. TypeSourceInfo *TInfo,
  15058. RecordDecl *Record, SourceLocation Loc,
  15059. bool Mutable, Expr *BitWidth,
  15060. InClassInitStyle InitStyle,
  15061. SourceLocation TSSL,
  15062. AccessSpecifier AS, NamedDecl *PrevDecl,
  15063. Declarator *D) {
  15064. IdentifierInfo *II = Name.getAsIdentifierInfo();
  15065. bool InvalidDecl = false;
  15066. if (D) InvalidDecl = D->isInvalidType();
  15067. // If we receive a broken type, recover by assuming 'int' and
  15068. // marking this declaration as invalid.
  15069. if (T.isNull() || T->containsErrors()) {
  15070. InvalidDecl = true;
  15071. T = Context.IntTy;
  15072. }
  15073. QualType EltTy = Context.getBaseElementType(T);
  15074. if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
  15075. if (RequireCompleteSizedType(Loc, EltTy,
  15076. diag::err_field_incomplete_or_sizeless)) {
  15077. // Fields of incomplete type force their record to be invalid.
  15078. Record->setInvalidDecl();
  15079. InvalidDecl = true;
  15080. } else {
  15081. NamedDecl *Def;
  15082. EltTy->isIncompleteType(&Def);
  15083. if (Def && Def->isInvalidDecl()) {
  15084. Record->setInvalidDecl();
  15085. InvalidDecl = true;
  15086. }
  15087. }
  15088. }
  15089. // TR 18037 does not allow fields to be declared with address space
  15090. if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
  15091. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  15092. Diag(Loc, diag::err_field_with_address_space);
  15093. Record->setInvalidDecl();
  15094. InvalidDecl = true;
  15095. }
  15096. if (LangOpts.OpenCL) {
  15097. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  15098. // used as structure or union field: image, sampler, event or block types.
  15099. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  15100. T->isBlockPointerType()) {
  15101. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  15102. Record->setInvalidDecl();
  15103. InvalidDecl = true;
  15104. }
  15105. // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
  15106. // is enabled.
  15107. if (BitWidth && !getOpenCLOptions().isAvailableOption(
  15108. "__cl_clang_bitfields", LangOpts)) {
  15109. Diag(Loc, diag::err_opencl_bitfields);
  15110. InvalidDecl = true;
  15111. }
  15112. }
  15113. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  15114. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  15115. T.hasQualifiers()) {
  15116. InvalidDecl = true;
  15117. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  15118. }
  15119. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  15120. // than a variably modified type.
  15121. if (!InvalidDecl && T->isVariablyModifiedType()) {
  15122. if (!tryToFixVariablyModifiedVarType(
  15123. TInfo, T, Loc, diag::err_typecheck_field_variable_size))
  15124. InvalidDecl = true;
  15125. }
  15126. // Fields can not have abstract class types
  15127. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  15128. diag::err_abstract_type_in_decl,
  15129. AbstractFieldType))
  15130. InvalidDecl = true;
  15131. bool ZeroWidth = false;
  15132. if (InvalidDecl)
  15133. BitWidth = nullptr;
  15134. // If this is declared as a bit-field, check the bit-field.
  15135. if (BitWidth) {
  15136. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  15137. &ZeroWidth).get();
  15138. if (!BitWidth) {
  15139. InvalidDecl = true;
  15140. BitWidth = nullptr;
  15141. ZeroWidth = false;
  15142. }
  15143. }
  15144. // Check that 'mutable' is consistent with the type of the declaration.
  15145. if (!InvalidDecl && Mutable) {
  15146. unsigned DiagID = 0;
  15147. if (T->isReferenceType())
  15148. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  15149. : diag::err_mutable_reference;
  15150. else if (T.isConstQualified())
  15151. DiagID = diag::err_mutable_const;
  15152. if (DiagID) {
  15153. SourceLocation ErrLoc = Loc;
  15154. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  15155. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  15156. Diag(ErrLoc, DiagID);
  15157. if (DiagID != diag::ext_mutable_reference) {
  15158. Mutable = false;
  15159. InvalidDecl = true;
  15160. }
  15161. }
  15162. }
  15163. // C++11 [class.union]p8 (DR1460):
  15164. // At most one variant member of a union may have a
  15165. // brace-or-equal-initializer.
  15166. if (InitStyle != ICIS_NoInit)
  15167. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  15168. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  15169. BitWidth, Mutable, InitStyle);
  15170. if (InvalidDecl)
  15171. NewFD->setInvalidDecl();
  15172. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  15173. Diag(Loc, diag::err_duplicate_member) << II;
  15174. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  15175. NewFD->setInvalidDecl();
  15176. }
  15177. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  15178. if (Record->isUnion()) {
  15179. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  15180. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  15181. if (RDecl->getDefinition()) {
  15182. // C++ [class.union]p1: An object of a class with a non-trivial
  15183. // constructor, a non-trivial copy constructor, a non-trivial
  15184. // destructor, or a non-trivial copy assignment operator
  15185. // cannot be a member of a union, nor can an array of such
  15186. // objects.
  15187. if (CheckNontrivialField(NewFD))
  15188. NewFD->setInvalidDecl();
  15189. }
  15190. }
  15191. // C++ [class.union]p1: If a union contains a member of reference type,
  15192. // the program is ill-formed, except when compiling with MSVC extensions
  15193. // enabled.
  15194. if (EltTy->isReferenceType()) {
  15195. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  15196. diag::ext_union_member_of_reference_type :
  15197. diag::err_union_member_of_reference_type)
  15198. << NewFD->getDeclName() << EltTy;
  15199. if (!getLangOpts().MicrosoftExt)
  15200. NewFD->setInvalidDecl();
  15201. }
  15202. }
  15203. }
  15204. // FIXME: We need to pass in the attributes given an AST
  15205. // representation, not a parser representation.
  15206. if (D) {
  15207. // FIXME: The current scope is almost... but not entirely... correct here.
  15208. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  15209. if (NewFD->hasAttrs())
  15210. CheckAlignasUnderalignment(NewFD);
  15211. }
  15212. // In auto-retain/release, infer strong retension for fields of
  15213. // retainable type.
  15214. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  15215. NewFD->setInvalidDecl();
  15216. if (T.isObjCGCWeak())
  15217. Diag(Loc, diag::warn_attribute_weak_on_field);
  15218. // PPC MMA non-pointer types are not allowed as field types.
  15219. if (Context.getTargetInfo().getTriple().isPPC64() &&
  15220. CheckPPCMMAType(T, NewFD->getLocation()))
  15221. NewFD->setInvalidDecl();
  15222. NewFD->setAccess(AS);
  15223. return NewFD;
  15224. }
  15225. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  15226. assert(FD);
  15227. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  15228. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  15229. return false;
  15230. QualType EltTy = Context.getBaseElementType(FD->getType());
  15231. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  15232. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  15233. if (RDecl->getDefinition()) {
  15234. // We check for copy constructors before constructors
  15235. // because otherwise we'll never get complaints about
  15236. // copy constructors.
  15237. CXXSpecialMember member = CXXInvalid;
  15238. // We're required to check for any non-trivial constructors. Since the
  15239. // implicit default constructor is suppressed if there are any
  15240. // user-declared constructors, we just need to check that there is a
  15241. // trivial default constructor and a trivial copy constructor. (We don't
  15242. // worry about move constructors here, since this is a C++98 check.)
  15243. if (RDecl->hasNonTrivialCopyConstructor())
  15244. member = CXXCopyConstructor;
  15245. else if (!RDecl->hasTrivialDefaultConstructor())
  15246. member = CXXDefaultConstructor;
  15247. else if (RDecl->hasNonTrivialCopyAssignment())
  15248. member = CXXCopyAssignment;
  15249. else if (RDecl->hasNonTrivialDestructor())
  15250. member = CXXDestructor;
  15251. if (member != CXXInvalid) {
  15252. if (!getLangOpts().CPlusPlus11 &&
  15253. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  15254. // Objective-C++ ARC: it is an error to have a non-trivial field of
  15255. // a union. However, system headers in Objective-C programs
  15256. // occasionally have Objective-C lifetime objects within unions,
  15257. // and rather than cause the program to fail, we make those
  15258. // members unavailable.
  15259. SourceLocation Loc = FD->getLocation();
  15260. if (getSourceManager().isInSystemHeader(Loc)) {
  15261. if (!FD->hasAttr<UnavailableAttr>())
  15262. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  15263. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  15264. return false;
  15265. }
  15266. }
  15267. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  15268. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  15269. diag::err_illegal_union_or_anon_struct_member)
  15270. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  15271. DiagnoseNontrivial(RDecl, member);
  15272. return !getLangOpts().CPlusPlus11;
  15273. }
  15274. }
  15275. }
  15276. return false;
  15277. }
  15278. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  15279. /// AST enum value.
  15280. static ObjCIvarDecl::AccessControl
  15281. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  15282. switch (ivarVisibility) {
  15283. default: llvm_unreachable("Unknown visitibility kind");
  15284. case tok::objc_private: return ObjCIvarDecl::Private;
  15285. case tok::objc_public: return ObjCIvarDecl::Public;
  15286. case tok::objc_protected: return ObjCIvarDecl::Protected;
  15287. case tok::objc_package: return ObjCIvarDecl::Package;
  15288. }
  15289. }
  15290. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  15291. /// in order to create an IvarDecl object for it.
  15292. Decl *Sema::ActOnIvar(Scope *S,
  15293. SourceLocation DeclStart,
  15294. Declarator &D, Expr *BitfieldWidth,
  15295. tok::ObjCKeywordKind Visibility) {
  15296. IdentifierInfo *II = D.getIdentifier();
  15297. Expr *BitWidth = (Expr*)BitfieldWidth;
  15298. SourceLocation Loc = DeclStart;
  15299. if (II) Loc = D.getIdentifierLoc();
  15300. // FIXME: Unnamed fields can be handled in various different ways, for
  15301. // example, unnamed unions inject all members into the struct namespace!
  15302. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  15303. QualType T = TInfo->getType();
  15304. if (BitWidth) {
  15305. // 6.7.2.1p3, 6.7.2.1p4
  15306. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  15307. if (!BitWidth)
  15308. D.setInvalidType();
  15309. } else {
  15310. // Not a bitfield.
  15311. // validate II.
  15312. }
  15313. if (T->isReferenceType()) {
  15314. Diag(Loc, diag::err_ivar_reference_type);
  15315. D.setInvalidType();
  15316. }
  15317. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  15318. // than a variably modified type.
  15319. else if (T->isVariablyModifiedType()) {
  15320. if (!tryToFixVariablyModifiedVarType(
  15321. TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
  15322. D.setInvalidType();
  15323. }
  15324. // Get the visibility (access control) for this ivar.
  15325. ObjCIvarDecl::AccessControl ac =
  15326. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  15327. : ObjCIvarDecl::None;
  15328. // Must set ivar's DeclContext to its enclosing interface.
  15329. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  15330. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  15331. return nullptr;
  15332. ObjCContainerDecl *EnclosingContext;
  15333. if (ObjCImplementationDecl *IMPDecl =
  15334. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  15335. if (LangOpts.ObjCRuntime.isFragile()) {
  15336. // Case of ivar declared in an implementation. Context is that of its class.
  15337. EnclosingContext = IMPDecl->getClassInterface();
  15338. assert(EnclosingContext && "Implementation has no class interface!");
  15339. }
  15340. else
  15341. EnclosingContext = EnclosingDecl;
  15342. } else {
  15343. if (ObjCCategoryDecl *CDecl =
  15344. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  15345. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  15346. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  15347. return nullptr;
  15348. }
  15349. }
  15350. EnclosingContext = EnclosingDecl;
  15351. }
  15352. // Construct the decl.
  15353. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  15354. DeclStart, Loc, II, T,
  15355. TInfo, ac, (Expr *)BitfieldWidth);
  15356. if (II) {
  15357. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  15358. ForVisibleRedeclaration);
  15359. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  15360. && !isa<TagDecl>(PrevDecl)) {
  15361. Diag(Loc, diag::err_duplicate_member) << II;
  15362. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  15363. NewID->setInvalidDecl();
  15364. }
  15365. }
  15366. // Process attributes attached to the ivar.
  15367. ProcessDeclAttributes(S, NewID, D);
  15368. if (D.isInvalidType())
  15369. NewID->setInvalidDecl();
  15370. // In ARC, infer 'retaining' for ivars of retainable type.
  15371. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  15372. NewID->setInvalidDecl();
  15373. if (D.getDeclSpec().isModulePrivateSpecified())
  15374. NewID->setModulePrivate();
  15375. if (II) {
  15376. // FIXME: When interfaces are DeclContexts, we'll need to add
  15377. // these to the interface.
  15378. S->AddDecl(NewID);
  15379. IdResolver.AddDecl(NewID);
  15380. }
  15381. if (LangOpts.ObjCRuntime.isNonFragile() &&
  15382. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  15383. Diag(Loc, diag::warn_ivars_in_interface);
  15384. return NewID;
  15385. }
  15386. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  15387. /// class and class extensions. For every class \@interface and class
  15388. /// extension \@interface, if the last ivar is a bitfield of any type,
  15389. /// then add an implicit `char :0` ivar to the end of that interface.
  15390. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  15391. SmallVectorImpl<Decl *> &AllIvarDecls) {
  15392. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  15393. return;
  15394. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  15395. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  15396. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  15397. return;
  15398. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  15399. if (!ID) {
  15400. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  15401. if (!CD->IsClassExtension())
  15402. return;
  15403. }
  15404. // No need to add this to end of @implementation.
  15405. else
  15406. return;
  15407. }
  15408. // All conditions are met. Add a new bitfield to the tail end of ivars.
  15409. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  15410. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  15411. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  15412. DeclLoc, DeclLoc, nullptr,
  15413. Context.CharTy,
  15414. Context.getTrivialTypeSourceInfo(Context.CharTy,
  15415. DeclLoc),
  15416. ObjCIvarDecl::Private, BW,
  15417. true);
  15418. AllIvarDecls.push_back(Ivar);
  15419. }
  15420. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  15421. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  15422. SourceLocation RBrac,
  15423. const ParsedAttributesView &Attrs) {
  15424. assert(EnclosingDecl && "missing record or interface decl");
  15425. // If this is an Objective-C @implementation or category and we have
  15426. // new fields here we should reset the layout of the interface since
  15427. // it will now change.
  15428. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  15429. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  15430. switch (DC->getKind()) {
  15431. default: break;
  15432. case Decl::ObjCCategory:
  15433. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  15434. break;
  15435. case Decl::ObjCImplementation:
  15436. Context.
  15437. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  15438. break;
  15439. }
  15440. }
  15441. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  15442. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  15443. // Start counting up the number of named members; make sure to include
  15444. // members of anonymous structs and unions in the total.
  15445. unsigned NumNamedMembers = 0;
  15446. if (Record) {
  15447. for (const auto *I : Record->decls()) {
  15448. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  15449. if (IFD->getDeclName())
  15450. ++NumNamedMembers;
  15451. }
  15452. }
  15453. // Verify that all the fields are okay.
  15454. SmallVector<FieldDecl*, 32> RecFields;
  15455. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  15456. i != end; ++i) {
  15457. FieldDecl *FD = cast<FieldDecl>(*i);
  15458. // Get the type for the field.
  15459. const Type *FDTy = FD->getType().getTypePtr();
  15460. if (!FD->isAnonymousStructOrUnion()) {
  15461. // Remember all fields written by the user.
  15462. RecFields.push_back(FD);
  15463. }
  15464. // If the field is already invalid for some reason, don't emit more
  15465. // diagnostics about it.
  15466. if (FD->isInvalidDecl()) {
  15467. EnclosingDecl->setInvalidDecl();
  15468. continue;
  15469. }
  15470. // C99 6.7.2.1p2:
  15471. // A structure or union shall not contain a member with
  15472. // incomplete or function type (hence, a structure shall not
  15473. // contain an instance of itself, but may contain a pointer to
  15474. // an instance of itself), except that the last member of a
  15475. // structure with more than one named member may have incomplete
  15476. // array type; such a structure (and any union containing,
  15477. // possibly recursively, a member that is such a structure)
  15478. // shall not be a member of a structure or an element of an
  15479. // array.
  15480. bool IsLastField = (i + 1 == Fields.end());
  15481. if (FDTy->isFunctionType()) {
  15482. // Field declared as a function.
  15483. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  15484. << FD->getDeclName();
  15485. FD->setInvalidDecl();
  15486. EnclosingDecl->setInvalidDecl();
  15487. continue;
  15488. } else if (FDTy->isIncompleteArrayType() &&
  15489. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  15490. if (Record) {
  15491. // Flexible array member.
  15492. // Microsoft and g++ is more permissive regarding flexible array.
  15493. // It will accept flexible array in union and also
  15494. // as the sole element of a struct/class.
  15495. unsigned DiagID = 0;
  15496. if (!Record->isUnion() && !IsLastField) {
  15497. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  15498. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  15499. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  15500. FD->setInvalidDecl();
  15501. EnclosingDecl->setInvalidDecl();
  15502. continue;
  15503. } else if (Record->isUnion())
  15504. DiagID = getLangOpts().MicrosoftExt
  15505. ? diag::ext_flexible_array_union_ms
  15506. : getLangOpts().CPlusPlus
  15507. ? diag::ext_flexible_array_union_gnu
  15508. : diag::err_flexible_array_union;
  15509. else if (NumNamedMembers < 1)
  15510. DiagID = getLangOpts().MicrosoftExt
  15511. ? diag::ext_flexible_array_empty_aggregate_ms
  15512. : getLangOpts().CPlusPlus
  15513. ? diag::ext_flexible_array_empty_aggregate_gnu
  15514. : diag::err_flexible_array_empty_aggregate;
  15515. if (DiagID)
  15516. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  15517. << Record->getTagKind();
  15518. // While the layout of types that contain virtual bases is not specified
  15519. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  15520. // virtual bases after the derived members. This would make a flexible
  15521. // array member declared at the end of an object not adjacent to the end
  15522. // of the type.
  15523. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  15524. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  15525. << FD->getDeclName() << Record->getTagKind();
  15526. if (!getLangOpts().C99)
  15527. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  15528. << FD->getDeclName() << Record->getTagKind();
  15529. // If the element type has a non-trivial destructor, we would not
  15530. // implicitly destroy the elements, so disallow it for now.
  15531. //
  15532. // FIXME: GCC allows this. We should probably either implicitly delete
  15533. // the destructor of the containing class, or just allow this.
  15534. QualType BaseElem = Context.getBaseElementType(FD->getType());
  15535. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  15536. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  15537. << FD->getDeclName() << FD->getType();
  15538. FD->setInvalidDecl();
  15539. EnclosingDecl->setInvalidDecl();
  15540. continue;
  15541. }
  15542. // Okay, we have a legal flexible array member at the end of the struct.
  15543. Record->setHasFlexibleArrayMember(true);
  15544. } else {
  15545. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  15546. // unless they are followed by another ivar. That check is done
  15547. // elsewhere, after synthesized ivars are known.
  15548. }
  15549. } else if (!FDTy->isDependentType() &&
  15550. RequireCompleteSizedType(
  15551. FD->getLocation(), FD->getType(),
  15552. diag::err_field_incomplete_or_sizeless)) {
  15553. // Incomplete type
  15554. FD->setInvalidDecl();
  15555. EnclosingDecl->setInvalidDecl();
  15556. continue;
  15557. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  15558. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  15559. // A type which contains a flexible array member is considered to be a
  15560. // flexible array member.
  15561. Record->setHasFlexibleArrayMember(true);
  15562. if (!Record->isUnion()) {
  15563. // If this is a struct/class and this is not the last element, reject
  15564. // it. Note that GCC supports variable sized arrays in the middle of
  15565. // structures.
  15566. if (!IsLastField)
  15567. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  15568. << FD->getDeclName() << FD->getType();
  15569. else {
  15570. // We support flexible arrays at the end of structs in
  15571. // other structs as an extension.
  15572. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  15573. << FD->getDeclName();
  15574. }
  15575. }
  15576. }
  15577. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  15578. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  15579. diag::err_abstract_type_in_decl,
  15580. AbstractIvarType)) {
  15581. // Ivars can not have abstract class types
  15582. FD->setInvalidDecl();
  15583. }
  15584. if (Record && FDTTy->getDecl()->hasObjectMember())
  15585. Record->setHasObjectMember(true);
  15586. if (Record && FDTTy->getDecl()->hasVolatileMember())
  15587. Record->setHasVolatileMember(true);
  15588. } else if (FDTy->isObjCObjectType()) {
  15589. /// A field cannot be an Objective-c object
  15590. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  15591. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  15592. QualType T = Context.getObjCObjectPointerType(FD->getType());
  15593. FD->setType(T);
  15594. } else if (Record && Record->isUnion() &&
  15595. FD->getType().hasNonTrivialObjCLifetime() &&
  15596. getSourceManager().isInSystemHeader(FD->getLocation()) &&
  15597. !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
  15598. (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
  15599. !Context.hasDirectOwnershipQualifier(FD->getType()))) {
  15600. // For backward compatibility, fields of C unions declared in system
  15601. // headers that have non-trivial ObjC ownership qualifications are marked
  15602. // as unavailable unless the qualifier is explicit and __strong. This can
  15603. // break ABI compatibility between programs compiled with ARC and MRR, but
  15604. // is a better option than rejecting programs using those unions under
  15605. // ARC.
  15606. FD->addAttr(UnavailableAttr::CreateImplicit(
  15607. Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
  15608. FD->getLocation()));
  15609. } else if (getLangOpts().ObjC &&
  15610. getLangOpts().getGC() != LangOptions::NonGC && Record &&
  15611. !Record->hasObjectMember()) {
  15612. if (FD->getType()->isObjCObjectPointerType() ||
  15613. FD->getType().isObjCGCStrong())
  15614. Record->setHasObjectMember(true);
  15615. else if (Context.getAsArrayType(FD->getType())) {
  15616. QualType BaseType = Context.getBaseElementType(FD->getType());
  15617. if (BaseType->isRecordType() &&
  15618. BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
  15619. Record->setHasObjectMember(true);
  15620. else if (BaseType->isObjCObjectPointerType() ||
  15621. BaseType.isObjCGCStrong())
  15622. Record->setHasObjectMember(true);
  15623. }
  15624. }
  15625. if (Record && !getLangOpts().CPlusPlus &&
  15626. !shouldIgnoreForRecordTriviality(FD)) {
  15627. QualType FT = FD->getType();
  15628. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  15629. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  15630. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  15631. Record->isUnion())
  15632. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  15633. }
  15634. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  15635. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  15636. Record->setNonTrivialToPrimitiveCopy(true);
  15637. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  15638. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  15639. }
  15640. if (FT.isDestructedType()) {
  15641. Record->setNonTrivialToPrimitiveDestroy(true);
  15642. Record->setParamDestroyedInCallee(true);
  15643. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  15644. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  15645. }
  15646. if (const auto *RT = FT->getAs<RecordType>()) {
  15647. if (RT->getDecl()->getArgPassingRestrictions() ==
  15648. RecordDecl::APK_CanNeverPassInRegs)
  15649. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  15650. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  15651. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  15652. }
  15653. if (Record && FD->getType().isVolatileQualified())
  15654. Record->setHasVolatileMember(true);
  15655. // Keep track of the number of named members.
  15656. if (FD->getIdentifier())
  15657. ++NumNamedMembers;
  15658. }
  15659. // Okay, we successfully defined 'Record'.
  15660. if (Record) {
  15661. bool Completed = false;
  15662. if (CXXRecord) {
  15663. if (!CXXRecord->isInvalidDecl()) {
  15664. // Set access bits correctly on the directly-declared conversions.
  15665. for (CXXRecordDecl::conversion_iterator
  15666. I = CXXRecord->conversion_begin(),
  15667. E = CXXRecord->conversion_end(); I != E; ++I)
  15668. I.setAccess((*I)->getAccess());
  15669. }
  15670. // Add any implicitly-declared members to this class.
  15671. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  15672. if (!CXXRecord->isDependentType()) {
  15673. if (!CXXRecord->isInvalidDecl()) {
  15674. // If we have virtual base classes, we may end up finding multiple
  15675. // final overriders for a given virtual function. Check for this
  15676. // problem now.
  15677. if (CXXRecord->getNumVBases()) {
  15678. CXXFinalOverriderMap FinalOverriders;
  15679. CXXRecord->getFinalOverriders(FinalOverriders);
  15680. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  15681. MEnd = FinalOverriders.end();
  15682. M != MEnd; ++M) {
  15683. for (OverridingMethods::iterator SO = M->second.begin(),
  15684. SOEnd = M->second.end();
  15685. SO != SOEnd; ++SO) {
  15686. assert(SO->second.size() > 0 &&
  15687. "Virtual function without overriding functions?");
  15688. if (SO->second.size() == 1)
  15689. continue;
  15690. // C++ [class.virtual]p2:
  15691. // In a derived class, if a virtual member function of a base
  15692. // class subobject has more than one final overrider the
  15693. // program is ill-formed.
  15694. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  15695. << (const NamedDecl *)M->first << Record;
  15696. Diag(M->first->getLocation(),
  15697. diag::note_overridden_virtual_function);
  15698. for (OverridingMethods::overriding_iterator
  15699. OM = SO->second.begin(),
  15700. OMEnd = SO->second.end();
  15701. OM != OMEnd; ++OM)
  15702. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  15703. << (const NamedDecl *)M->first << OM->Method->getParent();
  15704. Record->setInvalidDecl();
  15705. }
  15706. }
  15707. CXXRecord->completeDefinition(&FinalOverriders);
  15708. Completed = true;
  15709. }
  15710. }
  15711. }
  15712. }
  15713. if (!Completed)
  15714. Record->completeDefinition();
  15715. // Handle attributes before checking the layout.
  15716. ProcessDeclAttributeList(S, Record, Attrs);
  15717. // We may have deferred checking for a deleted destructor. Check now.
  15718. if (CXXRecord) {
  15719. auto *Dtor = CXXRecord->getDestructor();
  15720. if (Dtor && Dtor->isImplicit() &&
  15721. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  15722. CXXRecord->setImplicitDestructorIsDeleted();
  15723. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  15724. }
  15725. }
  15726. if (Record->hasAttrs()) {
  15727. CheckAlignasUnderalignment(Record);
  15728. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  15729. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  15730. IA->getRange(), IA->getBestCase(),
  15731. IA->getInheritanceModel());
  15732. }
  15733. // Check if the structure/union declaration is a type that can have zero
  15734. // size in C. For C this is a language extension, for C++ it may cause
  15735. // compatibility problems.
  15736. bool CheckForZeroSize;
  15737. if (!getLangOpts().CPlusPlus) {
  15738. CheckForZeroSize = true;
  15739. } else {
  15740. // For C++ filter out types that cannot be referenced in C code.
  15741. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  15742. CheckForZeroSize =
  15743. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  15744. !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
  15745. CXXRecord->isCLike();
  15746. }
  15747. if (CheckForZeroSize) {
  15748. bool ZeroSize = true;
  15749. bool IsEmpty = true;
  15750. unsigned NonBitFields = 0;
  15751. for (RecordDecl::field_iterator I = Record->field_begin(),
  15752. E = Record->field_end();
  15753. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  15754. IsEmpty = false;
  15755. if (I->isUnnamedBitfield()) {
  15756. if (!I->isZeroLengthBitField(Context))
  15757. ZeroSize = false;
  15758. } else {
  15759. ++NonBitFields;
  15760. QualType FieldType = I->getType();
  15761. if (FieldType->isIncompleteType() ||
  15762. !Context.getTypeSizeInChars(FieldType).isZero())
  15763. ZeroSize = false;
  15764. }
  15765. }
  15766. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  15767. // allowed in C++, but warn if its declaration is inside
  15768. // extern "C" block.
  15769. if (ZeroSize) {
  15770. Diag(RecLoc, getLangOpts().CPlusPlus ?
  15771. diag::warn_zero_size_struct_union_in_extern_c :
  15772. diag::warn_zero_size_struct_union_compat)
  15773. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  15774. }
  15775. // Structs without named members are extension in C (C99 6.7.2.1p7),
  15776. // but are accepted by GCC.
  15777. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  15778. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  15779. diag::ext_no_named_members_in_struct_union)
  15780. << Record->isUnion();
  15781. }
  15782. }
  15783. } else {
  15784. ObjCIvarDecl **ClsFields =
  15785. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  15786. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  15787. ID->setEndOfDefinitionLoc(RBrac);
  15788. // Add ivar's to class's DeclContext.
  15789. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  15790. ClsFields[i]->setLexicalDeclContext(ID);
  15791. ID->addDecl(ClsFields[i]);
  15792. }
  15793. // Must enforce the rule that ivars in the base classes may not be
  15794. // duplicates.
  15795. if (ID->getSuperClass())
  15796. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  15797. } else if (ObjCImplementationDecl *IMPDecl =
  15798. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  15799. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  15800. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  15801. // Ivar declared in @implementation never belongs to the implementation.
  15802. // Only it is in implementation's lexical context.
  15803. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  15804. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  15805. IMPDecl->setIvarLBraceLoc(LBrac);
  15806. IMPDecl->setIvarRBraceLoc(RBrac);
  15807. } else if (ObjCCategoryDecl *CDecl =
  15808. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  15809. // case of ivars in class extension; all other cases have been
  15810. // reported as errors elsewhere.
  15811. // FIXME. Class extension does not have a LocEnd field.
  15812. // CDecl->setLocEnd(RBrac);
  15813. // Add ivar's to class extension's DeclContext.
  15814. // Diagnose redeclaration of private ivars.
  15815. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  15816. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  15817. if (IDecl) {
  15818. if (const ObjCIvarDecl *ClsIvar =
  15819. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  15820. Diag(ClsFields[i]->getLocation(),
  15821. diag::err_duplicate_ivar_declaration);
  15822. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  15823. continue;
  15824. }
  15825. for (const auto *Ext : IDecl->known_extensions()) {
  15826. if (const ObjCIvarDecl *ClsExtIvar
  15827. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  15828. Diag(ClsFields[i]->getLocation(),
  15829. diag::err_duplicate_ivar_declaration);
  15830. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  15831. continue;
  15832. }
  15833. }
  15834. }
  15835. ClsFields[i]->setLexicalDeclContext(CDecl);
  15836. CDecl->addDecl(ClsFields[i]);
  15837. }
  15838. CDecl->setIvarLBraceLoc(LBrac);
  15839. CDecl->setIvarRBraceLoc(RBrac);
  15840. }
  15841. }
  15842. }
  15843. /// Determine whether the given integral value is representable within
  15844. /// the given type T.
  15845. static bool isRepresentableIntegerValue(ASTContext &Context,
  15846. llvm::APSInt &Value,
  15847. QualType T) {
  15848. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  15849. "Integral type required!");
  15850. unsigned BitWidth = Context.getIntWidth(T);
  15851. if (Value.isUnsigned() || Value.isNonNegative()) {
  15852. if (T->isSignedIntegerOrEnumerationType())
  15853. --BitWidth;
  15854. return Value.getActiveBits() <= BitWidth;
  15855. }
  15856. return Value.getMinSignedBits() <= BitWidth;
  15857. }
  15858. // Given an integral type, return the next larger integral type
  15859. // (or a NULL type of no such type exists).
  15860. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  15861. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  15862. // enum checking below.
  15863. assert((T->isIntegralType(Context) ||
  15864. T->isEnumeralType()) && "Integral type required!");
  15865. const unsigned NumTypes = 4;
  15866. QualType SignedIntegralTypes[NumTypes] = {
  15867. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  15868. };
  15869. QualType UnsignedIntegralTypes[NumTypes] = {
  15870. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  15871. Context.UnsignedLongLongTy
  15872. };
  15873. unsigned BitWidth = Context.getTypeSize(T);
  15874. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  15875. : UnsignedIntegralTypes;
  15876. for (unsigned I = 0; I != NumTypes; ++I)
  15877. if (Context.getTypeSize(Types[I]) > BitWidth)
  15878. return Types[I];
  15879. return QualType();
  15880. }
  15881. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  15882. EnumConstantDecl *LastEnumConst,
  15883. SourceLocation IdLoc,
  15884. IdentifierInfo *Id,
  15885. Expr *Val) {
  15886. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  15887. llvm::APSInt EnumVal(IntWidth);
  15888. QualType EltTy;
  15889. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  15890. Val = nullptr;
  15891. if (Val)
  15892. Val = DefaultLvalueConversion(Val).get();
  15893. if (Val) {
  15894. if (Enum->isDependentType() || Val->isTypeDependent() ||
  15895. Val->containsErrors())
  15896. EltTy = Context.DependentTy;
  15897. else {
  15898. // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
  15899. // underlying type, but do allow it in all other contexts.
  15900. if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
  15901. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  15902. // constant-expression in the enumerator-definition shall be a converted
  15903. // constant expression of the underlying type.
  15904. EltTy = Enum->getIntegerType();
  15905. ExprResult Converted =
  15906. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  15907. CCEK_Enumerator);
  15908. if (Converted.isInvalid())
  15909. Val = nullptr;
  15910. else
  15911. Val = Converted.get();
  15912. } else if (!Val->isValueDependent() &&
  15913. !(Val =
  15914. VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
  15915. .get())) {
  15916. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  15917. } else {
  15918. if (Enum->isComplete()) {
  15919. EltTy = Enum->getIntegerType();
  15920. // In Obj-C and Microsoft mode, require the enumeration value to be
  15921. // representable in the underlying type of the enumeration. In C++11,
  15922. // we perform a non-narrowing conversion as part of converted constant
  15923. // expression checking.
  15924. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  15925. if (Context.getTargetInfo()
  15926. .getTriple()
  15927. .isWindowsMSVCEnvironment()) {
  15928. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  15929. } else {
  15930. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  15931. }
  15932. }
  15933. // Cast to the underlying type.
  15934. Val = ImpCastExprToType(Val, EltTy,
  15935. EltTy->isBooleanType() ? CK_IntegralToBoolean
  15936. : CK_IntegralCast)
  15937. .get();
  15938. } else if (getLangOpts().CPlusPlus) {
  15939. // C++11 [dcl.enum]p5:
  15940. // If the underlying type is not fixed, the type of each enumerator
  15941. // is the type of its initializing value:
  15942. // - If an initializer is specified for an enumerator, the
  15943. // initializing value has the same type as the expression.
  15944. EltTy = Val->getType();
  15945. } else {
  15946. // C99 6.7.2.2p2:
  15947. // The expression that defines the value of an enumeration constant
  15948. // shall be an integer constant expression that has a value
  15949. // representable as an int.
  15950. // Complain if the value is not representable in an int.
  15951. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  15952. Diag(IdLoc, diag::ext_enum_value_not_int)
  15953. << toString(EnumVal, 10) << Val->getSourceRange()
  15954. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  15955. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  15956. // Force the type of the expression to 'int'.
  15957. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  15958. }
  15959. EltTy = Val->getType();
  15960. }
  15961. }
  15962. }
  15963. }
  15964. if (!Val) {
  15965. if (Enum->isDependentType())
  15966. EltTy = Context.DependentTy;
  15967. else if (!LastEnumConst) {
  15968. // C++0x [dcl.enum]p5:
  15969. // If the underlying type is not fixed, the type of each enumerator
  15970. // is the type of its initializing value:
  15971. // - If no initializer is specified for the first enumerator, the
  15972. // initializing value has an unspecified integral type.
  15973. //
  15974. // GCC uses 'int' for its unspecified integral type, as does
  15975. // C99 6.7.2.2p3.
  15976. if (Enum->isFixed()) {
  15977. EltTy = Enum->getIntegerType();
  15978. }
  15979. else {
  15980. EltTy = Context.IntTy;
  15981. }
  15982. } else {
  15983. // Assign the last value + 1.
  15984. EnumVal = LastEnumConst->getInitVal();
  15985. ++EnumVal;
  15986. EltTy = LastEnumConst->getType();
  15987. // Check for overflow on increment.
  15988. if (EnumVal < LastEnumConst->getInitVal()) {
  15989. // C++0x [dcl.enum]p5:
  15990. // If the underlying type is not fixed, the type of each enumerator
  15991. // is the type of its initializing value:
  15992. //
  15993. // - Otherwise the type of the initializing value is the same as
  15994. // the type of the initializing value of the preceding enumerator
  15995. // unless the incremented value is not representable in that type,
  15996. // in which case the type is an unspecified integral type
  15997. // sufficient to contain the incremented value. If no such type
  15998. // exists, the program is ill-formed.
  15999. QualType T = getNextLargerIntegralType(Context, EltTy);
  16000. if (T.isNull() || Enum->isFixed()) {
  16001. // There is no integral type larger enough to represent this
  16002. // value. Complain, then allow the value to wrap around.
  16003. EnumVal = LastEnumConst->getInitVal();
  16004. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  16005. ++EnumVal;
  16006. if (Enum->isFixed())
  16007. // When the underlying type is fixed, this is ill-formed.
  16008. Diag(IdLoc, diag::err_enumerator_wrapped)
  16009. << toString(EnumVal, 10)
  16010. << EltTy;
  16011. else
  16012. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  16013. << toString(EnumVal, 10);
  16014. } else {
  16015. EltTy = T;
  16016. }
  16017. // Retrieve the last enumerator's value, extent that type to the
  16018. // type that is supposed to be large enough to represent the incremented
  16019. // value, then increment.
  16020. EnumVal = LastEnumConst->getInitVal();
  16021. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  16022. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  16023. ++EnumVal;
  16024. // If we're not in C++, diagnose the overflow of enumerator values,
  16025. // which in C99 means that the enumerator value is not representable in
  16026. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  16027. // permits enumerator values that are representable in some larger
  16028. // integral type.
  16029. if (!getLangOpts().CPlusPlus && !T.isNull())
  16030. Diag(IdLoc, diag::warn_enum_value_overflow);
  16031. } else if (!getLangOpts().CPlusPlus &&
  16032. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  16033. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  16034. Diag(IdLoc, diag::ext_enum_value_not_int)
  16035. << toString(EnumVal, 10) << 1;
  16036. }
  16037. }
  16038. }
  16039. if (!EltTy->isDependentType()) {
  16040. // Make the enumerator value match the signedness and size of the
  16041. // enumerator's type.
  16042. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  16043. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  16044. }
  16045. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  16046. Val, EnumVal);
  16047. }
  16048. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  16049. SourceLocation IILoc) {
  16050. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  16051. !getLangOpts().CPlusPlus)
  16052. return SkipBodyInfo();
  16053. // We have an anonymous enum definition. Look up the first enumerator to
  16054. // determine if we should merge the definition with an existing one and
  16055. // skip the body.
  16056. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  16057. forRedeclarationInCurContext());
  16058. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  16059. if (!PrevECD)
  16060. return SkipBodyInfo();
  16061. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  16062. NamedDecl *Hidden;
  16063. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  16064. SkipBodyInfo Skip;
  16065. Skip.Previous = Hidden;
  16066. return Skip;
  16067. }
  16068. return SkipBodyInfo();
  16069. }
  16070. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  16071. SourceLocation IdLoc, IdentifierInfo *Id,
  16072. const ParsedAttributesView &Attrs,
  16073. SourceLocation EqualLoc, Expr *Val) {
  16074. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  16075. EnumConstantDecl *LastEnumConst =
  16076. cast_or_null<EnumConstantDecl>(lastEnumConst);
  16077. // The scope passed in may not be a decl scope. Zip up the scope tree until
  16078. // we find one that is.
  16079. S = getNonFieldDeclScope(S);
  16080. // Verify that there isn't already something declared with this name in this
  16081. // scope.
  16082. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  16083. LookupName(R, S);
  16084. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  16085. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  16086. // Maybe we will complain about the shadowed template parameter.
  16087. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  16088. // Just pretend that we didn't see the previous declaration.
  16089. PrevDecl = nullptr;
  16090. }
  16091. // C++ [class.mem]p15:
  16092. // If T is the name of a class, then each of the following shall have a name
  16093. // different from T:
  16094. // - every enumerator of every member of class T that is an unscoped
  16095. // enumerated type
  16096. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  16097. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  16098. DeclarationNameInfo(Id, IdLoc));
  16099. EnumConstantDecl *New =
  16100. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  16101. if (!New)
  16102. return nullptr;
  16103. if (PrevDecl) {
  16104. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  16105. // Check for other kinds of shadowing not already handled.
  16106. CheckShadow(New, PrevDecl, R);
  16107. }
  16108. // When in C++, we may get a TagDecl with the same name; in this case the
  16109. // enum constant will 'hide' the tag.
  16110. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  16111. "Received TagDecl when not in C++!");
  16112. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  16113. if (isa<EnumConstantDecl>(PrevDecl))
  16114. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  16115. else
  16116. Diag(IdLoc, diag::err_redefinition) << Id;
  16117. notePreviousDefinition(PrevDecl, IdLoc);
  16118. return nullptr;
  16119. }
  16120. }
  16121. // Process attributes.
  16122. ProcessDeclAttributeList(S, New, Attrs);
  16123. AddPragmaAttributes(S, New);
  16124. // Register this decl in the current scope stack.
  16125. New->setAccess(TheEnumDecl->getAccess());
  16126. PushOnScopeChains(New, S);
  16127. ActOnDocumentableDecl(New);
  16128. return New;
  16129. }
  16130. // Returns true when the enum initial expression does not trigger the
  16131. // duplicate enum warning. A few common cases are exempted as follows:
  16132. // Element2 = Element1
  16133. // Element2 = Element1 + 1
  16134. // Element2 = Element1 - 1
  16135. // Where Element2 and Element1 are from the same enum.
  16136. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  16137. Expr *InitExpr = ECD->getInitExpr();
  16138. if (!InitExpr)
  16139. return true;
  16140. InitExpr = InitExpr->IgnoreImpCasts();
  16141. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  16142. if (!BO->isAdditiveOp())
  16143. return true;
  16144. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  16145. if (!IL)
  16146. return true;
  16147. if (IL->getValue() != 1)
  16148. return true;
  16149. InitExpr = BO->getLHS();
  16150. }
  16151. // This checks if the elements are from the same enum.
  16152. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  16153. if (!DRE)
  16154. return true;
  16155. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  16156. if (!EnumConstant)
  16157. return true;
  16158. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  16159. Enum)
  16160. return true;
  16161. return false;
  16162. }
  16163. // Emits a warning when an element is implicitly set a value that
  16164. // a previous element has already been set to.
  16165. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  16166. EnumDecl *Enum, QualType EnumType) {
  16167. // Avoid anonymous enums
  16168. if (!Enum->getIdentifier())
  16169. return;
  16170. // Only check for small enums.
  16171. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  16172. return;
  16173. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  16174. return;
  16175. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  16176. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  16177. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  16178. // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
  16179. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  16180. // Use int64_t as a key to avoid needing special handling for map keys.
  16181. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  16182. llvm::APSInt Val = D->getInitVal();
  16183. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  16184. };
  16185. DuplicatesVector DupVector;
  16186. ValueToVectorMap EnumMap;
  16187. // Populate the EnumMap with all values represented by enum constants without
  16188. // an initializer.
  16189. for (auto *Element : Elements) {
  16190. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  16191. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  16192. // this constant. Skip this enum since it may be ill-formed.
  16193. if (!ECD) {
  16194. return;
  16195. }
  16196. // Constants with initalizers are handled in the next loop.
  16197. if (ECD->getInitExpr())
  16198. continue;
  16199. // Duplicate values are handled in the next loop.
  16200. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  16201. }
  16202. if (EnumMap.size() == 0)
  16203. return;
  16204. // Create vectors for any values that has duplicates.
  16205. for (auto *Element : Elements) {
  16206. // The last loop returned if any constant was null.
  16207. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  16208. if (!ValidDuplicateEnum(ECD, Enum))
  16209. continue;
  16210. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  16211. if (Iter == EnumMap.end())
  16212. continue;
  16213. DeclOrVector& Entry = Iter->second;
  16214. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  16215. // Ensure constants are different.
  16216. if (D == ECD)
  16217. continue;
  16218. // Create new vector and push values onto it.
  16219. auto Vec = std::make_unique<ECDVector>();
  16220. Vec->push_back(D);
  16221. Vec->push_back(ECD);
  16222. // Update entry to point to the duplicates vector.
  16223. Entry = Vec.get();
  16224. // Store the vector somewhere we can consult later for quick emission of
  16225. // diagnostics.
  16226. DupVector.emplace_back(std::move(Vec));
  16227. continue;
  16228. }
  16229. ECDVector *Vec = Entry.get<ECDVector*>();
  16230. // Make sure constants are not added more than once.
  16231. if (*Vec->begin() == ECD)
  16232. continue;
  16233. Vec->push_back(ECD);
  16234. }
  16235. // Emit diagnostics.
  16236. for (const auto &Vec : DupVector) {
  16237. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  16238. // Emit warning for one enum constant.
  16239. auto *FirstECD = Vec->front();
  16240. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  16241. << FirstECD << toString(FirstECD->getInitVal(), 10)
  16242. << FirstECD->getSourceRange();
  16243. // Emit one note for each of the remaining enum constants with
  16244. // the same value.
  16245. for (auto *ECD : llvm::drop_begin(*Vec))
  16246. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  16247. << ECD << toString(ECD->getInitVal(), 10)
  16248. << ECD->getSourceRange();
  16249. }
  16250. }
  16251. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  16252. bool AllowMask) const {
  16253. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  16254. assert(ED->isCompleteDefinition() && "expected enum definition");
  16255. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  16256. llvm::APInt &FlagBits = R.first->second;
  16257. if (R.second) {
  16258. for (auto *E : ED->enumerators()) {
  16259. const auto &EVal = E->getInitVal();
  16260. // Only single-bit enumerators introduce new flag values.
  16261. if (EVal.isPowerOf2())
  16262. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  16263. }
  16264. }
  16265. // A value is in a flag enum if either its bits are a subset of the enum's
  16266. // flag bits (the first condition) or we are allowing masks and the same is
  16267. // true of its complement (the second condition). When masks are allowed, we
  16268. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  16269. //
  16270. // While it's true that any value could be used as a mask, the assumption is
  16271. // that a mask will have all of the insignificant bits set. Anything else is
  16272. // likely a logic error.
  16273. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  16274. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  16275. }
  16276. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  16277. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  16278. const ParsedAttributesView &Attrs) {
  16279. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  16280. QualType EnumType = Context.getTypeDeclType(Enum);
  16281. ProcessDeclAttributeList(S, Enum, Attrs);
  16282. if (Enum->isDependentType()) {
  16283. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  16284. EnumConstantDecl *ECD =
  16285. cast_or_null<EnumConstantDecl>(Elements[i]);
  16286. if (!ECD) continue;
  16287. ECD->setType(EnumType);
  16288. }
  16289. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  16290. return;
  16291. }
  16292. // TODO: If the result value doesn't fit in an int, it must be a long or long
  16293. // long value. ISO C does not support this, but GCC does as an extension,
  16294. // emit a warning.
  16295. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  16296. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  16297. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  16298. // Verify that all the values are okay, compute the size of the values, and
  16299. // reverse the list.
  16300. unsigned NumNegativeBits = 0;
  16301. unsigned NumPositiveBits = 0;
  16302. // Keep track of whether all elements have type int.
  16303. bool AllElementsInt = true;
  16304. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  16305. EnumConstantDecl *ECD =
  16306. cast_or_null<EnumConstantDecl>(Elements[i]);
  16307. if (!ECD) continue; // Already issued a diagnostic.
  16308. const llvm::APSInt &InitVal = ECD->getInitVal();
  16309. // Keep track of the size of positive and negative values.
  16310. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  16311. NumPositiveBits = std::max(NumPositiveBits,
  16312. (unsigned)InitVal.getActiveBits());
  16313. else
  16314. NumNegativeBits = std::max(NumNegativeBits,
  16315. (unsigned)InitVal.getMinSignedBits());
  16316. // Keep track of whether every enum element has type int (very common).
  16317. if (AllElementsInt)
  16318. AllElementsInt = ECD->getType() == Context.IntTy;
  16319. }
  16320. // Figure out the type that should be used for this enum.
  16321. QualType BestType;
  16322. unsigned BestWidth;
  16323. // C++0x N3000 [conv.prom]p3:
  16324. // An rvalue of an unscoped enumeration type whose underlying
  16325. // type is not fixed can be converted to an rvalue of the first
  16326. // of the following types that can represent all the values of
  16327. // the enumeration: int, unsigned int, long int, unsigned long
  16328. // int, long long int, or unsigned long long int.
  16329. // C99 6.4.4.3p2:
  16330. // An identifier declared as an enumeration constant has type int.
  16331. // The C99 rule is modified by a gcc extension
  16332. QualType BestPromotionType;
  16333. bool Packed = Enum->hasAttr<PackedAttr>();
  16334. // -fshort-enums is the equivalent to specifying the packed attribute on all
  16335. // enum definitions.
  16336. if (LangOpts.ShortEnums)
  16337. Packed = true;
  16338. // If the enum already has a type because it is fixed or dictated by the
  16339. // target, promote that type instead of analyzing the enumerators.
  16340. if (Enum->isComplete()) {
  16341. BestType = Enum->getIntegerType();
  16342. if (BestType->isPromotableIntegerType())
  16343. BestPromotionType = Context.getPromotedIntegerType(BestType);
  16344. else
  16345. BestPromotionType = BestType;
  16346. BestWidth = Context.getIntWidth(BestType);
  16347. }
  16348. else if (NumNegativeBits) {
  16349. // If there is a negative value, figure out the smallest integer type (of
  16350. // int/long/longlong) that fits.
  16351. // If it's packed, check also if it fits a char or a short.
  16352. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  16353. BestType = Context.SignedCharTy;
  16354. BestWidth = CharWidth;
  16355. } else if (Packed && NumNegativeBits <= ShortWidth &&
  16356. NumPositiveBits < ShortWidth) {
  16357. BestType = Context.ShortTy;
  16358. BestWidth = ShortWidth;
  16359. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  16360. BestType = Context.IntTy;
  16361. BestWidth = IntWidth;
  16362. } else {
  16363. BestWidth = Context.getTargetInfo().getLongWidth();
  16364. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  16365. BestType = Context.LongTy;
  16366. } else {
  16367. BestWidth = Context.getTargetInfo().getLongLongWidth();
  16368. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  16369. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  16370. BestType = Context.LongLongTy;
  16371. }
  16372. }
  16373. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  16374. } else {
  16375. // If there is no negative value, figure out the smallest type that fits
  16376. // all of the enumerator values.
  16377. // If it's packed, check also if it fits a char or a short.
  16378. if (Packed && NumPositiveBits <= CharWidth) {
  16379. BestType = Context.UnsignedCharTy;
  16380. BestPromotionType = Context.IntTy;
  16381. BestWidth = CharWidth;
  16382. } else if (Packed && NumPositiveBits <= ShortWidth) {
  16383. BestType = Context.UnsignedShortTy;
  16384. BestPromotionType = Context.IntTy;
  16385. BestWidth = ShortWidth;
  16386. } else if (NumPositiveBits <= IntWidth) {
  16387. BestType = Context.UnsignedIntTy;
  16388. BestWidth = IntWidth;
  16389. BestPromotionType
  16390. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  16391. ? Context.UnsignedIntTy : Context.IntTy;
  16392. } else if (NumPositiveBits <=
  16393. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  16394. BestType = Context.UnsignedLongTy;
  16395. BestPromotionType
  16396. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  16397. ? Context.UnsignedLongTy : Context.LongTy;
  16398. } else {
  16399. BestWidth = Context.getTargetInfo().getLongLongWidth();
  16400. assert(NumPositiveBits <= BestWidth &&
  16401. "How could an initializer get larger than ULL?");
  16402. BestType = Context.UnsignedLongLongTy;
  16403. BestPromotionType
  16404. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  16405. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  16406. }
  16407. }
  16408. // Loop over all of the enumerator constants, changing their types to match
  16409. // the type of the enum if needed.
  16410. for (auto *D : Elements) {
  16411. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  16412. if (!ECD) continue; // Already issued a diagnostic.
  16413. // Standard C says the enumerators have int type, but we allow, as an
  16414. // extension, the enumerators to be larger than int size. If each
  16415. // enumerator value fits in an int, type it as an int, otherwise type it the
  16416. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  16417. // that X has type 'int', not 'unsigned'.
  16418. // Determine whether the value fits into an int.
  16419. llvm::APSInt InitVal = ECD->getInitVal();
  16420. // If it fits into an integer type, force it. Otherwise force it to match
  16421. // the enum decl type.
  16422. QualType NewTy;
  16423. unsigned NewWidth;
  16424. bool NewSign;
  16425. if (!getLangOpts().CPlusPlus &&
  16426. !Enum->isFixed() &&
  16427. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  16428. NewTy = Context.IntTy;
  16429. NewWidth = IntWidth;
  16430. NewSign = true;
  16431. } else if (ECD->getType() == BestType) {
  16432. // Already the right type!
  16433. if (getLangOpts().CPlusPlus)
  16434. // C++ [dcl.enum]p4: Following the closing brace of an
  16435. // enum-specifier, each enumerator has the type of its
  16436. // enumeration.
  16437. ECD->setType(EnumType);
  16438. continue;
  16439. } else {
  16440. NewTy = BestType;
  16441. NewWidth = BestWidth;
  16442. NewSign = BestType->isSignedIntegerOrEnumerationType();
  16443. }
  16444. // Adjust the APSInt value.
  16445. InitVal = InitVal.extOrTrunc(NewWidth);
  16446. InitVal.setIsSigned(NewSign);
  16447. ECD->setInitVal(InitVal);
  16448. // Adjust the Expr initializer and type.
  16449. if (ECD->getInitExpr() &&
  16450. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  16451. ECD->setInitExpr(ImplicitCastExpr::Create(
  16452. Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
  16453. /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
  16454. if (getLangOpts().CPlusPlus)
  16455. // C++ [dcl.enum]p4: Following the closing brace of an
  16456. // enum-specifier, each enumerator has the type of its
  16457. // enumeration.
  16458. ECD->setType(EnumType);
  16459. else
  16460. ECD->setType(NewTy);
  16461. }
  16462. Enum->completeDefinition(BestType, BestPromotionType,
  16463. NumPositiveBits, NumNegativeBits);
  16464. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  16465. if (Enum->isClosedFlag()) {
  16466. for (Decl *D : Elements) {
  16467. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  16468. if (!ECD) continue; // Already issued a diagnostic.
  16469. llvm::APSInt InitVal = ECD->getInitVal();
  16470. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  16471. !IsValueInFlagEnum(Enum, InitVal, true))
  16472. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  16473. << ECD << Enum;
  16474. }
  16475. }
  16476. // Now that the enum type is defined, ensure it's not been underaligned.
  16477. if (Enum->hasAttrs())
  16478. CheckAlignasUnderalignment(Enum);
  16479. }
  16480. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  16481. SourceLocation StartLoc,
  16482. SourceLocation EndLoc) {
  16483. StringLiteral *AsmString = cast<StringLiteral>(expr);
  16484. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  16485. AsmString, StartLoc,
  16486. EndLoc);
  16487. CurContext->addDecl(New);
  16488. return New;
  16489. }
  16490. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  16491. IdentifierInfo* AliasName,
  16492. SourceLocation PragmaLoc,
  16493. SourceLocation NameLoc,
  16494. SourceLocation AliasNameLoc) {
  16495. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  16496. LookupOrdinaryName);
  16497. AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
  16498. AttributeCommonInfo::AS_Pragma);
  16499. AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
  16500. Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
  16501. // If a declaration that:
  16502. // 1) declares a function or a variable
  16503. // 2) has external linkage
  16504. // already exists, add a label attribute to it.
  16505. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  16506. if (isDeclExternC(PrevDecl))
  16507. PrevDecl->addAttr(Attr);
  16508. else
  16509. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  16510. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  16511. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  16512. } else
  16513. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  16514. }
  16515. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  16516. SourceLocation PragmaLoc,
  16517. SourceLocation NameLoc) {
  16518. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  16519. if (PrevDecl) {
  16520. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
  16521. } else {
  16522. (void)WeakUndeclaredIdentifiers.insert(
  16523. std::pair<IdentifierInfo*,WeakInfo>
  16524. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  16525. }
  16526. }
  16527. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  16528. IdentifierInfo* AliasName,
  16529. SourceLocation PragmaLoc,
  16530. SourceLocation NameLoc,
  16531. SourceLocation AliasNameLoc) {
  16532. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  16533. LookupOrdinaryName);
  16534. WeakInfo W = WeakInfo(Name, NameLoc);
  16535. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  16536. if (!PrevDecl->hasAttr<AliasAttr>())
  16537. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  16538. DeclApplyPragmaWeak(TUScope, ND, W);
  16539. } else {
  16540. (void)WeakUndeclaredIdentifiers.insert(
  16541. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  16542. }
  16543. }
  16544. Decl *Sema::getObjCDeclContext() const {
  16545. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  16546. }
  16547. Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
  16548. bool Final) {
  16549. assert(FD && "Expected non-null FunctionDecl");
  16550. // SYCL functions can be template, so we check if they have appropriate
  16551. // attribute prior to checking if it is a template.
  16552. if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
  16553. return FunctionEmissionStatus::Emitted;
  16554. // Templates are emitted when they're instantiated.
  16555. if (FD->isDependentContext())
  16556. return FunctionEmissionStatus::TemplateDiscarded;
  16557. // Check whether this function is an externally visible definition.
  16558. auto IsEmittedForExternalSymbol = [this, FD]() {
  16559. // We have to check the GVA linkage of the function's *definition* -- if we
  16560. // only have a declaration, we don't know whether or not the function will
  16561. // be emitted, because (say) the definition could include "inline".
  16562. FunctionDecl *Def = FD->getDefinition();
  16563. return Def && !isDiscardableGVALinkage(
  16564. getASTContext().GetGVALinkageForFunction(Def));
  16565. };
  16566. if (LangOpts.OpenMPIsDevice) {
  16567. // In OpenMP device mode we will not emit host only functions, or functions
  16568. // we don't need due to their linkage.
  16569. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  16570. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  16571. // DevTy may be changed later by
  16572. // #pragma omp declare target to(*) device_type(*).
  16573. // Therefore DevTy having no value does not imply host. The emission status
  16574. // will be checked again at the end of compilation unit with Final = true.
  16575. if (DevTy.hasValue())
  16576. if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  16577. return FunctionEmissionStatus::OMPDiscarded;
  16578. // If we have an explicit value for the device type, or we are in a target
  16579. // declare context, we need to emit all extern and used symbols.
  16580. if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
  16581. if (IsEmittedForExternalSymbol())
  16582. return FunctionEmissionStatus::Emitted;
  16583. // Device mode only emits what it must, if it wasn't tagged yet and needed,
  16584. // we'll omit it.
  16585. if (Final)
  16586. return FunctionEmissionStatus::OMPDiscarded;
  16587. } else if (LangOpts.OpenMP > 45) {
  16588. // In OpenMP host compilation prior to 5.0 everything was an emitted host
  16589. // function. In 5.0, no_host was introduced which might cause a function to
  16590. // be ommitted.
  16591. Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  16592. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  16593. if (DevTy.hasValue())
  16594. if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  16595. return FunctionEmissionStatus::OMPDiscarded;
  16596. }
  16597. if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
  16598. return FunctionEmissionStatus::Emitted;
  16599. if (LangOpts.CUDA) {
  16600. // When compiling for device, host functions are never emitted. Similarly,
  16601. // when compiling for host, device and global functions are never emitted.
  16602. // (Technically, we do emit a host-side stub for global functions, but this
  16603. // doesn't count for our purposes here.)
  16604. Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
  16605. if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
  16606. return FunctionEmissionStatus::CUDADiscarded;
  16607. if (!LangOpts.CUDAIsDevice &&
  16608. (T == Sema::CFT_Device || T == Sema::CFT_Global))
  16609. return FunctionEmissionStatus::CUDADiscarded;
  16610. if (IsEmittedForExternalSymbol())
  16611. return FunctionEmissionStatus::Emitted;
  16612. }
  16613. // Otherwise, the function is known-emitted if it's in our set of
  16614. // known-emitted functions.
  16615. return FunctionEmissionStatus::Unknown;
  16616. }
  16617. bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
  16618. // Host-side references to a __global__ function refer to the stub, so the
  16619. // function itself is never emitted and therefore should not be marked.
  16620. // If we have host fn calls kernel fn calls host+device, the HD function
  16621. // does not get instantiated on the host. We model this by omitting at the
  16622. // call to the kernel from the callgraph. This ensures that, when compiling
  16623. // for host, only HD functions actually called from the host get marked as
  16624. // known-emitted.
  16625. return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  16626. IdentifyCUDATarget(Callee) == CFT_Global;
  16627. }