SemaDecl.cpp 781 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954
  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/Randstruct.h"
  27. #include "clang/AST/StmtCXX.h"
  28. #include "clang/Basic/Builtins.h"
  29. #include "clang/Basic/HLSLRuntime.h"
  30. #include "clang/Basic/PartialDiagnostic.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  34. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  35. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  36. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  37. #include "clang/Sema/CXXFieldCollector.h"
  38. #include "clang/Sema/DeclSpec.h"
  39. #include "clang/Sema/DelayedDiagnostic.h"
  40. #include "clang/Sema/Initialization.h"
  41. #include "clang/Sema/Lookup.h"
  42. #include "clang/Sema/ParsedTemplate.h"
  43. #include "clang/Sema/Scope.h"
  44. #include "clang/Sema/ScopeInfo.h"
  45. #include "clang/Sema/SemaInternal.h"
  46. #include "clang/Sema/Template.h"
  47. #include "llvm/ADT/SmallString.h"
  48. #include "llvm/ADT/Triple.h"
  49. #include <algorithm>
  50. #include <cstring>
  51. #include <functional>
  52. #include <optional>
  53. #include <unordered_map>
  54. using namespace clang;
  55. using namespace sema;
  56. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  57. if (OwnedType) {
  58. Decl *Group[2] = { OwnedType, Ptr };
  59. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  60. }
  61. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  62. }
  63. namespace {
  64. class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
  65. public:
  66. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  67. bool AllowTemplates = false,
  68. bool AllowNonTemplates = true)
  69. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  70. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  71. WantExpressionKeywords = false;
  72. WantCXXNamedCasts = false;
  73. WantRemainingKeywords = false;
  74. }
  75. bool ValidateCandidate(const TypoCorrection &candidate) override {
  76. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  77. if (!AllowInvalidDecl && ND->isInvalidDecl())
  78. return false;
  79. if (getAsTypeTemplateDecl(ND))
  80. return AllowTemplates;
  81. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  82. if (!IsType)
  83. return false;
  84. if (AllowNonTemplates)
  85. return true;
  86. // An injected-class-name of a class template (specialization) is valid
  87. // as a template or as a non-template.
  88. if (AllowTemplates) {
  89. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  90. if (!RD || !RD->isInjectedClassName())
  91. return false;
  92. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  93. return RD->getDescribedClassTemplate() ||
  94. isa<ClassTemplateSpecializationDecl>(RD);
  95. }
  96. return false;
  97. }
  98. return !WantClassName && candidate.isKeyword();
  99. }
  100. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  101. return std::make_unique<TypeNameValidatorCCC>(*this);
  102. }
  103. private:
  104. bool AllowInvalidDecl;
  105. bool WantClassName;
  106. bool AllowTemplates;
  107. bool AllowNonTemplates;
  108. };
  109. } // end anonymous namespace
  110. /// Determine whether the token kind starts a simple-type-specifier.
  111. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  112. switch (Kind) {
  113. // FIXME: Take into account the current language when deciding whether a
  114. // token kind is a valid type specifier
  115. case tok::kw_short:
  116. case tok::kw_long:
  117. case tok::kw___int64:
  118. case tok::kw___int128:
  119. case tok::kw_signed:
  120. case tok::kw_unsigned:
  121. case tok::kw_void:
  122. case tok::kw_char:
  123. case tok::kw_int:
  124. case tok::kw_half:
  125. case tok::kw_float:
  126. case tok::kw_double:
  127. case tok::kw___bf16:
  128. case tok::kw__Float16:
  129. case tok::kw___float128:
  130. case tok::kw___ibm128:
  131. case tok::kw_wchar_t:
  132. case tok::kw_bool:
  133. #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
  134. #include "clang/Basic/TransformTypeTraits.def"
  135. case tok::kw___auto_type:
  136. return true;
  137. case tok::annot_typename:
  138. case tok::kw_char16_t:
  139. case tok::kw_char32_t:
  140. case tok::kw_typeof:
  141. case tok::annot_decltype:
  142. case tok::kw_decltype:
  143. return getLangOpts().CPlusPlus;
  144. case tok::kw_char8_t:
  145. return getLangOpts().Char8;
  146. default:
  147. break;
  148. }
  149. return false;
  150. }
  151. namespace {
  152. enum class UnqualifiedTypeNameLookupResult {
  153. NotFound,
  154. FoundNonType,
  155. FoundType
  156. };
  157. } // end anonymous namespace
  158. /// Tries to perform unqualified lookup of the type decls in bases for
  159. /// dependent class.
  160. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  161. /// type decl, \a FoundType if only type decls are found.
  162. static UnqualifiedTypeNameLookupResult
  163. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  164. SourceLocation NameLoc,
  165. const CXXRecordDecl *RD) {
  166. if (!RD->hasDefinition())
  167. return UnqualifiedTypeNameLookupResult::NotFound;
  168. // Look for type decls in base classes.
  169. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  170. UnqualifiedTypeNameLookupResult::NotFound;
  171. for (const auto &Base : RD->bases()) {
  172. const CXXRecordDecl *BaseRD = nullptr;
  173. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  174. BaseRD = BaseTT->getAsCXXRecordDecl();
  175. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  176. // Look for type decls in dependent base classes that have known primary
  177. // templates.
  178. if (!TST || !TST->isDependentType())
  179. continue;
  180. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  181. if (!TD)
  182. continue;
  183. if (auto *BasePrimaryTemplate =
  184. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  185. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  186. BaseRD = BasePrimaryTemplate;
  187. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  188. if (const ClassTemplatePartialSpecializationDecl *PS =
  189. CTD->findPartialSpecialization(Base.getType()))
  190. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  191. BaseRD = PS;
  192. }
  193. }
  194. }
  195. if (BaseRD) {
  196. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  197. if (!isa<TypeDecl>(ND))
  198. return UnqualifiedTypeNameLookupResult::FoundNonType;
  199. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  200. }
  201. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  202. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  203. case UnqualifiedTypeNameLookupResult::FoundNonType:
  204. return UnqualifiedTypeNameLookupResult::FoundNonType;
  205. case UnqualifiedTypeNameLookupResult::FoundType:
  206. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  207. break;
  208. case UnqualifiedTypeNameLookupResult::NotFound:
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. return FoundTypeDecl;
  215. }
  216. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  217. const IdentifierInfo &II,
  218. SourceLocation NameLoc) {
  219. // Lookup in the parent class template context, if any.
  220. const CXXRecordDecl *RD = nullptr;
  221. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  222. UnqualifiedTypeNameLookupResult::NotFound;
  223. for (DeclContext *DC = S.CurContext;
  224. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  225. DC = DC->getParent()) {
  226. // Look for type decls in dependent base classes that have known primary
  227. // templates.
  228. RD = dyn_cast<CXXRecordDecl>(DC);
  229. if (RD && RD->getDescribedClassTemplate())
  230. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  231. }
  232. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  233. return nullptr;
  234. // We found some types in dependent base classes. Recover as if the user
  235. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  236. // lookup during template instantiation.
  237. S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
  238. ASTContext &Context = S.Context;
  239. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  240. cast<Type>(Context.getRecordType(RD)));
  241. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  242. CXXScopeSpec SS;
  243. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  244. TypeLocBuilder Builder;
  245. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  246. DepTL.setNameLoc(NameLoc);
  247. DepTL.setElaboratedKeywordLoc(SourceLocation());
  248. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  249. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  250. }
  251. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  252. static ParsedType buildNamedType(Sema &S, const CXXScopeSpec *SS, QualType T,
  253. SourceLocation NameLoc,
  254. bool WantNontrivialTypeSourceInfo = true) {
  255. switch (T->getTypeClass()) {
  256. case Type::DeducedTemplateSpecialization:
  257. case Type::Enum:
  258. case Type::InjectedClassName:
  259. case Type::Record:
  260. case Type::Typedef:
  261. case Type::UnresolvedUsing:
  262. case Type::Using:
  263. break;
  264. // These can never be qualified so an ElaboratedType node
  265. // would carry no additional meaning.
  266. case Type::ObjCInterface:
  267. case Type::ObjCTypeParam:
  268. case Type::TemplateTypeParm:
  269. return ParsedType::make(T);
  270. default:
  271. llvm_unreachable("Unexpected Type Class");
  272. }
  273. if (!SS || SS->isEmpty())
  274. return ParsedType::make(
  275. S.Context.getElaboratedType(ETK_None, nullptr, T, nullptr));
  276. QualType ElTy = S.getElaboratedType(ETK_None, *SS, T);
  277. if (!WantNontrivialTypeSourceInfo)
  278. return ParsedType::make(ElTy);
  279. TypeLocBuilder Builder;
  280. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  281. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(ElTy);
  282. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  283. ElabTL.setQualifierLoc(SS->getWithLocInContext(S.Context));
  284. return S.CreateParsedType(ElTy, Builder.getTypeSourceInfo(S.Context, ElTy));
  285. }
  286. /// If the identifier refers to a type name within this scope,
  287. /// return the declaration of that type.
  288. ///
  289. /// This routine performs ordinary name lookup of the identifier II
  290. /// within the given scope, with optional C++ scope specifier SS, to
  291. /// determine whether the name refers to a type. If so, returns an
  292. /// opaque pointer (actually a QualType) corresponding to that
  293. /// type. Otherwise, returns NULL.
  294. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  295. Scope *S, CXXScopeSpec *SS, bool isClassName,
  296. bool HasTrailingDot, ParsedType ObjectTypePtr,
  297. bool IsCtorOrDtorName,
  298. bool WantNontrivialTypeSourceInfo,
  299. bool IsClassTemplateDeductionContext,
  300. ImplicitTypenameContext AllowImplicitTypename,
  301. IdentifierInfo **CorrectedII) {
  302. // FIXME: Consider allowing this outside C++1z mode as an extension.
  303. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  304. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  305. !isClassName && !HasTrailingDot;
  306. // Determine where we will perform name lookup.
  307. DeclContext *LookupCtx = nullptr;
  308. if (ObjectTypePtr) {
  309. QualType ObjectType = ObjectTypePtr.get();
  310. if (ObjectType->isRecordType())
  311. LookupCtx = computeDeclContext(ObjectType);
  312. } else if (SS && SS->isNotEmpty()) {
  313. LookupCtx = computeDeclContext(*SS, false);
  314. if (!LookupCtx) {
  315. if (isDependentScopeSpecifier(*SS)) {
  316. // C++ [temp.res]p3:
  317. // A qualified-id that refers to a type and in which the
  318. // nested-name-specifier depends on a template-parameter (14.6.2)
  319. // shall be prefixed by the keyword typename to indicate that the
  320. // qualified-id denotes a type, forming an
  321. // elaborated-type-specifier (7.1.5.3).
  322. //
  323. // We therefore do not perform any name lookup if the result would
  324. // refer to a member of an unknown specialization.
  325. // In C++2a, in several contexts a 'typename' is not required. Also
  326. // allow this as an extension.
  327. if (AllowImplicitTypename == ImplicitTypenameContext::No &&
  328. !isClassName && !IsCtorOrDtorName)
  329. return nullptr;
  330. bool IsImplicitTypename = !isClassName && !IsCtorOrDtorName;
  331. if (IsImplicitTypename) {
  332. SourceLocation QualifiedLoc = SS->getRange().getBegin();
  333. if (getLangOpts().CPlusPlus20)
  334. Diag(QualifiedLoc, diag::warn_cxx17_compat_implicit_typename);
  335. else
  336. Diag(QualifiedLoc, diag::ext_implicit_typename)
  337. << SS->getScopeRep() << II.getName()
  338. << FixItHint::CreateInsertion(QualifiedLoc, "typename ");
  339. }
  340. // We know from the grammar that this name refers to a type,
  341. // so build a dependent node to describe the type.
  342. if (WantNontrivialTypeSourceInfo)
  343. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc,
  344. (ImplicitTypenameContext)IsImplicitTypename)
  345. .get();
  346. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  347. QualType T =
  348. CheckTypenameType(IsImplicitTypename ? ETK_Typename : ETK_None,
  349. SourceLocation(), QualifierLoc, II, NameLoc);
  350. return ParsedType::make(T);
  351. }
  352. return nullptr;
  353. }
  354. if (!LookupCtx->isDependentContext() &&
  355. RequireCompleteDeclContext(*SS, LookupCtx))
  356. return nullptr;
  357. }
  358. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  359. // lookup for class-names.
  360. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  361. LookupOrdinaryName;
  362. LookupResult Result(*this, &II, NameLoc, Kind);
  363. if (LookupCtx) {
  364. // Perform "qualified" name lookup into the declaration context we
  365. // computed, which is either the type of the base of a member access
  366. // expression or the declaration context associated with a prior
  367. // nested-name-specifier.
  368. LookupQualifiedName(Result, LookupCtx);
  369. if (ObjectTypePtr && Result.empty()) {
  370. // C++ [basic.lookup.classref]p3:
  371. // If the unqualified-id is ~type-name, the type-name is looked up
  372. // in the context of the entire postfix-expression. If the type T of
  373. // the object expression is of a class type C, the type-name is also
  374. // looked up in the scope of class C. At least one of the lookups shall
  375. // find a name that refers to (possibly cv-qualified) T.
  376. LookupName(Result, S);
  377. }
  378. } else {
  379. // Perform unqualified name lookup.
  380. LookupName(Result, S);
  381. // For unqualified lookup in a class template in MSVC mode, look into
  382. // dependent base classes where the primary class template is known.
  383. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  384. if (ParsedType TypeInBase =
  385. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  386. return TypeInBase;
  387. }
  388. }
  389. NamedDecl *IIDecl = nullptr;
  390. UsingShadowDecl *FoundUsingShadow = nullptr;
  391. switch (Result.getResultKind()) {
  392. case LookupResult::NotFound:
  393. case LookupResult::NotFoundInCurrentInstantiation:
  394. if (CorrectedII) {
  395. TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
  396. AllowDeducedTemplate);
  397. TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
  398. S, SS, CCC, CTK_ErrorRecovery);
  399. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  400. TemplateTy Template;
  401. bool MemberOfUnknownSpecialization;
  402. UnqualifiedId TemplateName;
  403. TemplateName.setIdentifier(NewII, NameLoc);
  404. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  405. CXXScopeSpec NewSS, *NewSSPtr = SS;
  406. if (SS && NNS) {
  407. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  408. NewSSPtr = &NewSS;
  409. }
  410. if (Correction && (NNS || NewII != &II) &&
  411. // Ignore a correction to a template type as the to-be-corrected
  412. // identifier is not a template (typo correction for template names
  413. // is handled elsewhere).
  414. !(getLangOpts().CPlusPlus && NewSSPtr &&
  415. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  416. Template, MemberOfUnknownSpecialization))) {
  417. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  418. isClassName, HasTrailingDot, ObjectTypePtr,
  419. IsCtorOrDtorName,
  420. WantNontrivialTypeSourceInfo,
  421. IsClassTemplateDeductionContext);
  422. if (Ty) {
  423. diagnoseTypo(Correction,
  424. PDiag(diag::err_unknown_type_or_class_name_suggest)
  425. << Result.getLookupName() << isClassName);
  426. if (SS && NNS)
  427. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  428. *CorrectedII = NewII;
  429. return Ty;
  430. }
  431. }
  432. }
  433. // If typo correction failed or was not performed, fall through
  434. [[fallthrough]];
  435. case LookupResult::FoundOverloaded:
  436. case LookupResult::FoundUnresolvedValue:
  437. Result.suppressDiagnostics();
  438. return nullptr;
  439. case LookupResult::Ambiguous:
  440. // Recover from type-hiding ambiguities by hiding the type. We'll
  441. // do the lookup again when looking for an object, and we can
  442. // diagnose the error then. If we don't do this, then the error
  443. // about hiding the type will be immediately followed by an error
  444. // that only makes sense if the identifier was treated like a type.
  445. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  446. Result.suppressDiagnostics();
  447. return nullptr;
  448. }
  449. // Look to see if we have a type anywhere in the list of results.
  450. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  451. Res != ResEnd; ++Res) {
  452. NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
  453. if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
  454. RealRes) ||
  455. (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
  456. if (!IIDecl ||
  457. // Make the selection of the recovery decl deterministic.
  458. RealRes->getLocation() < IIDecl->getLocation()) {
  459. IIDecl = RealRes;
  460. FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
  461. }
  462. }
  463. }
  464. if (!IIDecl) {
  465. // None of the entities we found is a type, so there is no way
  466. // to even assume that the result is a type. In this case, don't
  467. // complain about the ambiguity. The parser will either try to
  468. // perform this lookup again (e.g., as an object name), which
  469. // will produce the ambiguity, or will complain that it expected
  470. // a type name.
  471. Result.suppressDiagnostics();
  472. return nullptr;
  473. }
  474. // We found a type within the ambiguous lookup; diagnose the
  475. // ambiguity and then return that type. This might be the right
  476. // answer, or it might not be, but it suppresses any attempt to
  477. // perform the name lookup again.
  478. break;
  479. case LookupResult::Found:
  480. IIDecl = Result.getFoundDecl();
  481. FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
  482. break;
  483. }
  484. assert(IIDecl && "Didn't find decl");
  485. QualType T;
  486. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  487. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  488. // instead names the constructors of the class, except when naming a class.
  489. // This is ill-formed when we're not actually forming a ctor or dtor name.
  490. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  491. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  492. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  493. FoundRD->isInjectedClassName() &&
  494. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  495. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  496. << &II << /*Type*/1;
  497. DiagnoseUseOfDecl(IIDecl, NameLoc);
  498. T = Context.getTypeDeclType(TD);
  499. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  500. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  501. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  502. if (!HasTrailingDot)
  503. T = Context.getObjCInterfaceType(IDecl);
  504. FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
  505. } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
  506. (void)DiagnoseUseOfDecl(UD, NameLoc);
  507. // Recover with 'int'
  508. return ParsedType::make(Context.IntTy);
  509. } else if (AllowDeducedTemplate) {
  510. if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
  511. assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
  512. TemplateName Template =
  513. FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
  514. T = Context.getDeducedTemplateSpecializationType(Template, QualType(),
  515. false);
  516. // Don't wrap in a further UsingType.
  517. FoundUsingShadow = nullptr;
  518. }
  519. }
  520. if (T.isNull()) {
  521. // If it's not plausibly a type, suppress diagnostics.
  522. Result.suppressDiagnostics();
  523. return nullptr;
  524. }
  525. if (FoundUsingShadow)
  526. T = Context.getUsingType(FoundUsingShadow, T);
  527. return buildNamedType(*this, SS, T, NameLoc, WantNontrivialTypeSourceInfo);
  528. }
  529. // Builds a fake NNS for the given decl context.
  530. static NestedNameSpecifier *
  531. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  532. for (;; DC = DC->getLookupParent()) {
  533. DC = DC->getPrimaryContext();
  534. auto *ND = dyn_cast<NamespaceDecl>(DC);
  535. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  536. return NestedNameSpecifier::Create(Context, nullptr, ND);
  537. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  538. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  539. RD->getTypeForDecl());
  540. else if (isa<TranslationUnitDecl>(DC))
  541. return NestedNameSpecifier::GlobalSpecifier(Context);
  542. }
  543. llvm_unreachable("something isn't in TU scope?");
  544. }
  545. /// Find the parent class with dependent bases of the innermost enclosing method
  546. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  547. /// up allowing unqualified dependent type names at class-level, which MSVC
  548. /// correctly rejects.
  549. static const CXXRecordDecl *
  550. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  551. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  552. DC = DC->getPrimaryContext();
  553. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  554. if (MD->getParent()->hasAnyDependentBases())
  555. return MD->getParent();
  556. }
  557. return nullptr;
  558. }
  559. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  560. SourceLocation NameLoc,
  561. bool IsTemplateTypeArg) {
  562. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  563. NestedNameSpecifier *NNS = nullptr;
  564. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  565. // If we weren't able to parse a default template argument, delay lookup
  566. // until instantiation time by making a non-dependent DependentTypeName. We
  567. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  568. // lookup is retried.
  569. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  570. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  571. // name specifiers.
  572. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  573. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  574. } else if (const CXXRecordDecl *RD =
  575. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  576. // Build a DependentNameType that will perform lookup into RD at
  577. // instantiation time.
  578. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  579. RD->getTypeForDecl());
  580. // Diagnose that this identifier was undeclared, and retry the lookup during
  581. // template instantiation.
  582. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  583. << RD;
  584. } else {
  585. // This is not a situation that we should recover from.
  586. return ParsedType();
  587. }
  588. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  589. // Build type location information. We synthesized the qualifier, so we have
  590. // to build a fake NestedNameSpecifierLoc.
  591. NestedNameSpecifierLocBuilder NNSLocBuilder;
  592. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  593. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  594. TypeLocBuilder Builder;
  595. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  596. DepTL.setNameLoc(NameLoc);
  597. DepTL.setElaboratedKeywordLoc(SourceLocation());
  598. DepTL.setQualifierLoc(QualifierLoc);
  599. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  600. }
  601. /// isTagName() - This method is called *for error recovery purposes only*
  602. /// to determine if the specified name is a valid tag name ("struct foo"). If
  603. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  604. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  605. /// cases in C where the user forgot to specify the tag.
  606. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  607. // Do a tag name lookup in this scope.
  608. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  609. LookupName(R, S, false);
  610. R.suppressDiagnostics();
  611. if (R.getResultKind() == LookupResult::Found)
  612. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  613. switch (TD->getTagKind()) {
  614. case TTK_Struct: return DeclSpec::TST_struct;
  615. case TTK_Interface: return DeclSpec::TST_interface;
  616. case TTK_Union: return DeclSpec::TST_union;
  617. case TTK_Class: return DeclSpec::TST_class;
  618. case TTK_Enum: return DeclSpec::TST_enum;
  619. }
  620. }
  621. return DeclSpec::TST_unspecified;
  622. }
  623. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  624. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  625. /// then downgrade the missing typename error to a warning.
  626. /// This is needed for MSVC compatibility; Example:
  627. /// @code
  628. /// template<class T> class A {
  629. /// public:
  630. /// typedef int TYPE;
  631. /// };
  632. /// template<class T> class B : public A<T> {
  633. /// public:
  634. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  635. /// };
  636. /// @endcode
  637. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  638. if (CurContext->isRecord()) {
  639. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  640. return true;
  641. const Type *Ty = SS->getScopeRep()->getAsType();
  642. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  643. for (const auto &Base : RD->bases())
  644. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  645. return true;
  646. return S->isFunctionPrototypeScope();
  647. }
  648. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  649. }
  650. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  651. SourceLocation IILoc,
  652. Scope *S,
  653. CXXScopeSpec *SS,
  654. ParsedType &SuggestedType,
  655. bool IsTemplateName) {
  656. // Don't report typename errors for editor placeholders.
  657. if (II->isEditorPlaceholder())
  658. return;
  659. // We don't have anything to suggest (yet).
  660. SuggestedType = nullptr;
  661. // There may have been a typo in the name of the type. Look up typo
  662. // results, in case we have something that we can suggest.
  663. TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
  664. /*AllowTemplates=*/IsTemplateName,
  665. /*AllowNonTemplates=*/!IsTemplateName);
  666. if (TypoCorrection Corrected =
  667. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  668. CCC, CTK_ErrorRecovery)) {
  669. // FIXME: Support error recovery for the template-name case.
  670. bool CanRecover = !IsTemplateName;
  671. if (Corrected.isKeyword()) {
  672. // We corrected to a keyword.
  673. diagnoseTypo(Corrected,
  674. PDiag(IsTemplateName ? diag::err_no_template_suggest
  675. : diag::err_unknown_typename_suggest)
  676. << II);
  677. II = Corrected.getCorrectionAsIdentifierInfo();
  678. } else {
  679. // We found a similarly-named type or interface; suggest that.
  680. if (!SS || !SS->isSet()) {
  681. diagnoseTypo(Corrected,
  682. PDiag(IsTemplateName ? diag::err_no_template_suggest
  683. : diag::err_unknown_typename_suggest)
  684. << II, CanRecover);
  685. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  686. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  687. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  688. II->getName().equals(CorrectedStr);
  689. diagnoseTypo(Corrected,
  690. PDiag(IsTemplateName
  691. ? diag::err_no_member_template_suggest
  692. : diag::err_unknown_nested_typename_suggest)
  693. << II << DC << DroppedSpecifier << SS->getRange(),
  694. CanRecover);
  695. } else {
  696. llvm_unreachable("could not have corrected a typo here");
  697. }
  698. if (!CanRecover)
  699. return;
  700. CXXScopeSpec tmpSS;
  701. if (Corrected.getCorrectionSpecifier())
  702. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  703. SourceRange(IILoc));
  704. // FIXME: Support class template argument deduction here.
  705. SuggestedType =
  706. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  707. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  708. /*IsCtorOrDtorName=*/false,
  709. /*WantNontrivialTypeSourceInfo=*/true);
  710. }
  711. return;
  712. }
  713. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  714. // See if II is a class template that the user forgot to pass arguments to.
  715. UnqualifiedId Name;
  716. Name.setIdentifier(II, IILoc);
  717. CXXScopeSpec EmptySS;
  718. TemplateTy TemplateResult;
  719. bool MemberOfUnknownSpecialization;
  720. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  721. Name, nullptr, true, TemplateResult,
  722. MemberOfUnknownSpecialization) == TNK_Type_template) {
  723. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  724. return;
  725. }
  726. }
  727. // FIXME: Should we move the logic that tries to recover from a missing tag
  728. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  729. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  730. Diag(IILoc, IsTemplateName ? diag::err_no_template
  731. : diag::err_unknown_typename)
  732. << II;
  733. else if (DeclContext *DC = computeDeclContext(*SS, false))
  734. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  735. : diag::err_typename_nested_not_found)
  736. << II << DC << SS->getRange();
  737. else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
  738. SuggestedType =
  739. ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
  740. } else if (isDependentScopeSpecifier(*SS)) {
  741. unsigned DiagID = diag::err_typename_missing;
  742. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  743. DiagID = diag::ext_typename_missing;
  744. Diag(SS->getRange().getBegin(), DiagID)
  745. << SS->getScopeRep() << II->getName()
  746. << SourceRange(SS->getRange().getBegin(), IILoc)
  747. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  748. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  749. *SS, *II, IILoc).get();
  750. } else {
  751. assert(SS && SS->isInvalid() &&
  752. "Invalid scope specifier has already been diagnosed");
  753. }
  754. }
  755. /// Determine whether the given result set contains either a type name
  756. /// or
  757. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  758. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  759. NextToken.is(tok::less);
  760. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  761. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  762. return true;
  763. if (CheckTemplate && isa<TemplateDecl>(*I))
  764. return true;
  765. }
  766. return false;
  767. }
  768. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  769. Scope *S, CXXScopeSpec &SS,
  770. IdentifierInfo *&Name,
  771. SourceLocation NameLoc) {
  772. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  773. SemaRef.LookupParsedName(R, S, &SS);
  774. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  775. StringRef FixItTagName;
  776. switch (Tag->getTagKind()) {
  777. case TTK_Class:
  778. FixItTagName = "class ";
  779. break;
  780. case TTK_Enum:
  781. FixItTagName = "enum ";
  782. break;
  783. case TTK_Struct:
  784. FixItTagName = "struct ";
  785. break;
  786. case TTK_Interface:
  787. FixItTagName = "__interface ";
  788. break;
  789. case TTK_Union:
  790. FixItTagName = "union ";
  791. break;
  792. }
  793. StringRef TagName = FixItTagName.drop_back();
  794. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  795. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  796. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  797. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  798. I != IEnd; ++I)
  799. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  800. << Name << TagName;
  801. // Replace lookup results with just the tag decl.
  802. Result.clear(Sema::LookupTagName);
  803. SemaRef.LookupParsedName(Result, S, &SS);
  804. return true;
  805. }
  806. return false;
  807. }
  808. Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
  809. IdentifierInfo *&Name,
  810. SourceLocation NameLoc,
  811. const Token &NextToken,
  812. CorrectionCandidateCallback *CCC) {
  813. DeclarationNameInfo NameInfo(Name, NameLoc);
  814. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  815. assert(NextToken.isNot(tok::coloncolon) &&
  816. "parse nested name specifiers before calling ClassifyName");
  817. if (getLangOpts().CPlusPlus && SS.isSet() &&
  818. isCurrentClassName(*Name, S, &SS)) {
  819. // Per [class.qual]p2, this names the constructors of SS, not the
  820. // injected-class-name. We don't have a classification for that.
  821. // There's not much point caching this result, since the parser
  822. // will reject it later.
  823. return NameClassification::Unknown();
  824. }
  825. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  826. LookupParsedName(Result, S, &SS, !CurMethod);
  827. if (SS.isInvalid())
  828. return NameClassification::Error();
  829. // For unqualified lookup in a class template in MSVC mode, look into
  830. // dependent base classes where the primary class template is known.
  831. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  832. if (ParsedType TypeInBase =
  833. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  834. return TypeInBase;
  835. }
  836. // Perform lookup for Objective-C instance variables (including automatically
  837. // synthesized instance variables), if we're in an Objective-C method.
  838. // FIXME: This lookup really, really needs to be folded in to the normal
  839. // unqualified lookup mechanism.
  840. if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  841. DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
  842. if (Ivar.isInvalid())
  843. return NameClassification::Error();
  844. if (Ivar.isUsable())
  845. return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
  846. // We defer builtin creation until after ivar lookup inside ObjC methods.
  847. if (Result.empty())
  848. LookupBuiltin(Result);
  849. }
  850. bool SecondTry = false;
  851. bool IsFilteredTemplateName = false;
  852. Corrected:
  853. switch (Result.getResultKind()) {
  854. case LookupResult::NotFound:
  855. // If an unqualified-id is followed by a '(', then we have a function
  856. // call.
  857. if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
  858. // In C++, this is an ADL-only call.
  859. // FIXME: Reference?
  860. if (getLangOpts().CPlusPlus)
  861. return NameClassification::UndeclaredNonType();
  862. // C90 6.3.2.2:
  863. // If the expression that precedes the parenthesized argument list in a
  864. // function call consists solely of an identifier, and if no
  865. // declaration is visible for this identifier, the identifier is
  866. // implicitly declared exactly as if, in the innermost block containing
  867. // the function call, the declaration
  868. //
  869. // extern int identifier ();
  870. //
  871. // appeared.
  872. //
  873. // We also allow this in C99 as an extension. However, this is not
  874. // allowed in all language modes as functions without prototypes may not
  875. // be supported.
  876. if (getLangOpts().implicitFunctionsAllowed()) {
  877. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
  878. return NameClassification::NonType(D);
  879. }
  880. }
  881. if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
  882. // In C++20 onwards, this could be an ADL-only call to a function
  883. // template, and we're required to assume that this is a template name.
  884. //
  885. // FIXME: Find a way to still do typo correction in this case.
  886. TemplateName Template =
  887. Context.getAssumedTemplateName(NameInfo.getName());
  888. return NameClassification::UndeclaredTemplate(Template);
  889. }
  890. // In C, we first see whether there is a tag type by the same name, in
  891. // which case it's likely that the user just forgot to write "enum",
  892. // "struct", or "union".
  893. if (!getLangOpts().CPlusPlus && !SecondTry &&
  894. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  895. break;
  896. }
  897. // Perform typo correction to determine if there is another name that is
  898. // close to this name.
  899. if (!SecondTry && CCC) {
  900. SecondTry = true;
  901. if (TypoCorrection Corrected =
  902. CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
  903. &SS, *CCC, CTK_ErrorRecovery)) {
  904. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  905. unsigned QualifiedDiag = diag::err_no_member_suggest;
  906. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  907. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  908. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  909. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  910. UnqualifiedDiag = diag::err_no_template_suggest;
  911. QualifiedDiag = diag::err_no_member_template_suggest;
  912. } else if (UnderlyingFirstDecl &&
  913. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  914. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  915. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  916. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  917. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  918. }
  919. if (SS.isEmpty()) {
  920. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  921. } else {// FIXME: is this even reachable? Test it.
  922. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  923. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  924. Name->getName().equals(CorrectedStr);
  925. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  926. << Name << computeDeclContext(SS, false)
  927. << DroppedSpecifier << SS.getRange());
  928. }
  929. // Update the name, so that the caller has the new name.
  930. Name = Corrected.getCorrectionAsIdentifierInfo();
  931. // Typo correction corrected to a keyword.
  932. if (Corrected.isKeyword())
  933. return Name;
  934. // Also update the LookupResult...
  935. // FIXME: This should probably go away at some point
  936. Result.clear();
  937. Result.setLookupName(Corrected.getCorrection());
  938. if (FirstDecl)
  939. Result.addDecl(FirstDecl);
  940. // If we found an Objective-C instance variable, let
  941. // LookupInObjCMethod build the appropriate expression to
  942. // reference the ivar.
  943. // FIXME: This is a gross hack.
  944. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  945. DeclResult R =
  946. LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
  947. if (R.isInvalid())
  948. return NameClassification::Error();
  949. if (R.isUsable())
  950. return NameClassification::NonType(Ivar);
  951. }
  952. goto Corrected;
  953. }
  954. }
  955. // We failed to correct; just fall through and let the parser deal with it.
  956. Result.suppressDiagnostics();
  957. return NameClassification::Unknown();
  958. case LookupResult::NotFoundInCurrentInstantiation: {
  959. // We performed name lookup into the current instantiation, and there were
  960. // dependent bases, so we treat this result the same way as any other
  961. // dependent nested-name-specifier.
  962. // C++ [temp.res]p2:
  963. // A name used in a template declaration or definition and that is
  964. // dependent on a template-parameter is assumed not to name a type
  965. // unless the applicable name lookup finds a type name or the name is
  966. // qualified by the keyword typename.
  967. //
  968. // FIXME: If the next token is '<', we might want to ask the parser to
  969. // perform some heroics to see if we actually have a
  970. // template-argument-list, which would indicate a missing 'template'
  971. // keyword here.
  972. return NameClassification::DependentNonType();
  973. }
  974. case LookupResult::Found:
  975. case LookupResult::FoundOverloaded:
  976. case LookupResult::FoundUnresolvedValue:
  977. break;
  978. case LookupResult::Ambiguous:
  979. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  980. hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
  981. /*AllowDependent=*/false)) {
  982. // C++ [temp.local]p3:
  983. // A lookup that finds an injected-class-name (10.2) can result in an
  984. // ambiguity in certain cases (for example, if it is found in more than
  985. // one base class). If all of the injected-class-names that are found
  986. // refer to specializations of the same class template, and if the name
  987. // is followed by a template-argument-list, the reference refers to the
  988. // class template itself and not a specialization thereof, and is not
  989. // ambiguous.
  990. //
  991. // This filtering can make an ambiguous result into an unambiguous one,
  992. // so try again after filtering out template names.
  993. FilterAcceptableTemplateNames(Result);
  994. if (!Result.isAmbiguous()) {
  995. IsFilteredTemplateName = true;
  996. break;
  997. }
  998. }
  999. // Diagnose the ambiguity and return an error.
  1000. return NameClassification::Error();
  1001. }
  1002. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  1003. (IsFilteredTemplateName ||
  1004. hasAnyAcceptableTemplateNames(
  1005. Result, /*AllowFunctionTemplates=*/true,
  1006. /*AllowDependent=*/false,
  1007. /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
  1008. getLangOpts().CPlusPlus20))) {
  1009. // C++ [temp.names]p3:
  1010. // After name lookup (3.4) finds that a name is a template-name or that
  1011. // an operator-function-id or a literal- operator-id refers to a set of
  1012. // overloaded functions any member of which is a function template if
  1013. // this is followed by a <, the < is always taken as the delimiter of a
  1014. // template-argument-list and never as the less-than operator.
  1015. // C++2a [temp.names]p2:
  1016. // A name is also considered to refer to a template if it is an
  1017. // unqualified-id followed by a < and name lookup finds either one
  1018. // or more functions or finds nothing.
  1019. if (!IsFilteredTemplateName)
  1020. FilterAcceptableTemplateNames(Result);
  1021. bool IsFunctionTemplate;
  1022. bool IsVarTemplate;
  1023. TemplateName Template;
  1024. if (Result.end() - Result.begin() > 1) {
  1025. IsFunctionTemplate = true;
  1026. Template = Context.getOverloadedTemplateName(Result.begin(),
  1027. Result.end());
  1028. } else if (!Result.empty()) {
  1029. auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
  1030. *Result.begin(), /*AllowFunctionTemplates=*/true,
  1031. /*AllowDependent=*/false));
  1032. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  1033. IsVarTemplate = isa<VarTemplateDecl>(TD);
  1034. UsingShadowDecl *FoundUsingShadow =
  1035. dyn_cast<UsingShadowDecl>(*Result.begin());
  1036. assert(!FoundUsingShadow ||
  1037. TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()));
  1038. Template =
  1039. FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
  1040. if (SS.isNotEmpty())
  1041. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  1042. /*TemplateKeyword=*/false,
  1043. Template);
  1044. } else {
  1045. // All results were non-template functions. This is a function template
  1046. // name.
  1047. IsFunctionTemplate = true;
  1048. Template = Context.getAssumedTemplateName(NameInfo.getName());
  1049. }
  1050. if (IsFunctionTemplate) {
  1051. // Function templates always go through overload resolution, at which
  1052. // point we'll perform the various checks (e.g., accessibility) we need
  1053. // to based on which function we selected.
  1054. Result.suppressDiagnostics();
  1055. return NameClassification::FunctionTemplate(Template);
  1056. }
  1057. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  1058. : NameClassification::TypeTemplate(Template);
  1059. }
  1060. auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
  1061. QualType T = Context.getTypeDeclType(Type);
  1062. if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
  1063. T = Context.getUsingType(USD, T);
  1064. return buildNamedType(*this, &SS, T, NameLoc);
  1065. };
  1066. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  1067. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  1068. DiagnoseUseOfDecl(Type, NameLoc);
  1069. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  1070. return BuildTypeFor(Type, *Result.begin());
  1071. }
  1072. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  1073. if (!Class) {
  1074. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  1075. if (ObjCCompatibleAliasDecl *Alias =
  1076. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  1077. Class = Alias->getClassInterface();
  1078. }
  1079. if (Class) {
  1080. DiagnoseUseOfDecl(Class, NameLoc);
  1081. if (NextToken.is(tok::period)) {
  1082. // Interface. <something> is parsed as a property reference expression.
  1083. // Just return "unknown" as a fall-through for now.
  1084. Result.suppressDiagnostics();
  1085. return NameClassification::Unknown();
  1086. }
  1087. QualType T = Context.getObjCInterfaceType(Class);
  1088. return ParsedType::make(T);
  1089. }
  1090. if (isa<ConceptDecl>(FirstDecl))
  1091. return NameClassification::Concept(
  1092. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1093. if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
  1094. (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
  1095. return NameClassification::Error();
  1096. }
  1097. // We can have a type template here if we're classifying a template argument.
  1098. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1099. !isa<VarTemplateDecl>(FirstDecl))
  1100. return NameClassification::TypeTemplate(
  1101. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1102. // Check for a tag type hidden by a non-type decl in a few cases where it
  1103. // seems likely a type is wanted instead of the non-type that was found.
  1104. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1105. if ((NextToken.is(tok::identifier) ||
  1106. (NextIsOp &&
  1107. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1108. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1109. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1110. DiagnoseUseOfDecl(Type, NameLoc);
  1111. return BuildTypeFor(Type, *Result.begin());
  1112. }
  1113. // If we already know which single declaration is referenced, just annotate
  1114. // that declaration directly. Defer resolving even non-overloaded class
  1115. // member accesses, as we need to defer certain access checks until we know
  1116. // the context.
  1117. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1118. if (Result.isSingleResult() && !ADL &&
  1119. (!FirstDecl->isCXXClassMember() || isa<EnumConstantDecl>(FirstDecl)))
  1120. return NameClassification::NonType(Result.getRepresentativeDecl());
  1121. // Otherwise, this is an overload set that we will need to resolve later.
  1122. Result.suppressDiagnostics();
  1123. return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
  1124. Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
  1125. Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
  1126. Result.begin(), Result.end()));
  1127. }
  1128. ExprResult
  1129. Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
  1130. SourceLocation NameLoc) {
  1131. assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
  1132. CXXScopeSpec SS;
  1133. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  1134. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  1135. }
  1136. ExprResult
  1137. Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
  1138. IdentifierInfo *Name,
  1139. SourceLocation NameLoc,
  1140. bool IsAddressOfOperand) {
  1141. DeclarationNameInfo NameInfo(Name, NameLoc);
  1142. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  1143. NameInfo, IsAddressOfOperand,
  1144. /*TemplateArgs=*/nullptr);
  1145. }
  1146. ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
  1147. NamedDecl *Found,
  1148. SourceLocation NameLoc,
  1149. const Token &NextToken) {
  1150. if (getCurMethodDecl() && SS.isEmpty())
  1151. if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
  1152. return BuildIvarRefExpr(S, NameLoc, Ivar);
  1153. // Reconstruct the lookup result.
  1154. LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
  1155. Result.addDecl(Found);
  1156. Result.resolveKind();
  1157. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1158. return BuildDeclarationNameExpr(SS, Result, ADL, /*AcceptInvalidDecl=*/true);
  1159. }
  1160. ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
  1161. // For an implicit class member access, transform the result into a member
  1162. // access expression if necessary.
  1163. auto *ULE = cast<UnresolvedLookupExpr>(E);
  1164. if ((*ULE->decls_begin())->isCXXClassMember()) {
  1165. CXXScopeSpec SS;
  1166. SS.Adopt(ULE->getQualifierLoc());
  1167. // Reconstruct the lookup result.
  1168. LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
  1169. LookupOrdinaryName);
  1170. Result.setNamingClass(ULE->getNamingClass());
  1171. for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
  1172. Result.addDecl(*I, I.getAccess());
  1173. Result.resolveKind();
  1174. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1175. nullptr, S);
  1176. }
  1177. // Otherwise, this is already in the form we needed, and no further checks
  1178. // are necessary.
  1179. return ULE;
  1180. }
  1181. Sema::TemplateNameKindForDiagnostics
  1182. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1183. auto *TD = Name.getAsTemplateDecl();
  1184. if (!TD)
  1185. return TemplateNameKindForDiagnostics::DependentTemplate;
  1186. if (isa<ClassTemplateDecl>(TD))
  1187. return TemplateNameKindForDiagnostics::ClassTemplate;
  1188. if (isa<FunctionTemplateDecl>(TD))
  1189. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1190. if (isa<VarTemplateDecl>(TD))
  1191. return TemplateNameKindForDiagnostics::VarTemplate;
  1192. if (isa<TypeAliasTemplateDecl>(TD))
  1193. return TemplateNameKindForDiagnostics::AliasTemplate;
  1194. if (isa<TemplateTemplateParmDecl>(TD))
  1195. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1196. if (isa<ConceptDecl>(TD))
  1197. return TemplateNameKindForDiagnostics::Concept;
  1198. return TemplateNameKindForDiagnostics::DependentTemplate;
  1199. }
  1200. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1201. assert(DC->getLexicalParent() == CurContext &&
  1202. "The next DeclContext should be lexically contained in the current one.");
  1203. CurContext = DC;
  1204. S->setEntity(DC);
  1205. }
  1206. void Sema::PopDeclContext() {
  1207. assert(CurContext && "DeclContext imbalance!");
  1208. CurContext = CurContext->getLexicalParent();
  1209. assert(CurContext && "Popped translation unit!");
  1210. }
  1211. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1212. Decl *D) {
  1213. // Unlike PushDeclContext, the context to which we return is not necessarily
  1214. // the containing DC of TD, because the new context will be some pre-existing
  1215. // TagDecl definition instead of a fresh one.
  1216. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1217. CurContext = cast<TagDecl>(D)->getDefinition();
  1218. assert(CurContext && "skipping definition of undefined tag");
  1219. // Start lookups from the parent of the current context; we don't want to look
  1220. // into the pre-existing complete definition.
  1221. S->setEntity(CurContext->getLookupParent());
  1222. return Result;
  1223. }
  1224. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1225. CurContext = static_cast<decltype(CurContext)>(Context);
  1226. }
  1227. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1228. /// of a declarator's nested name specifier.
  1229. ///
  1230. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1231. // C++0x [basic.lookup.unqual]p13:
  1232. // A name used in the definition of a static data member of class
  1233. // X (after the qualified-id of the static member) is looked up as
  1234. // if the name was used in a member function of X.
  1235. // C++0x [basic.lookup.unqual]p14:
  1236. // If a variable member of a namespace is defined outside of the
  1237. // scope of its namespace then any name used in the definition of
  1238. // the variable member (after the declarator-id) is looked up as
  1239. // if the definition of the variable member occurred in its
  1240. // namespace.
  1241. // Both of these imply that we should push a scope whose context
  1242. // is the semantic context of the declaration. We can't use
  1243. // PushDeclContext here because that context is not necessarily
  1244. // lexically contained in the current context. Fortunately,
  1245. // the containing scope should have the appropriate information.
  1246. assert(!S->getEntity() && "scope already has entity");
  1247. #ifndef NDEBUG
  1248. Scope *Ancestor = S->getParent();
  1249. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1250. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1251. #endif
  1252. CurContext = DC;
  1253. S->setEntity(DC);
  1254. if (S->getParent()->isTemplateParamScope()) {
  1255. // Also set the corresponding entities for all immediately-enclosing
  1256. // template parameter scopes.
  1257. EnterTemplatedContext(S->getParent(), DC);
  1258. }
  1259. }
  1260. void Sema::ExitDeclaratorContext(Scope *S) {
  1261. assert(S->getEntity() == CurContext && "Context imbalance!");
  1262. // Switch back to the lexical context. The safety of this is
  1263. // enforced by an assert in EnterDeclaratorContext.
  1264. Scope *Ancestor = S->getParent();
  1265. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1266. CurContext = Ancestor->getEntity();
  1267. // We don't need to do anything with the scope, which is going to
  1268. // disappear.
  1269. }
  1270. void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
  1271. assert(S->isTemplateParamScope() &&
  1272. "expected to be initializing a template parameter scope");
  1273. // C++20 [temp.local]p7:
  1274. // In the definition of a member of a class template that appears outside
  1275. // of the class template definition, the name of a member of the class
  1276. // template hides the name of a template-parameter of any enclosing class
  1277. // templates (but not a template-parameter of the member if the member is a
  1278. // class or function template).
  1279. // C++20 [temp.local]p9:
  1280. // In the definition of a class template or in the definition of a member
  1281. // of such a template that appears outside of the template definition, for
  1282. // each non-dependent base class (13.8.2.1), if the name of the base class
  1283. // or the name of a member of the base class is the same as the name of a
  1284. // template-parameter, the base class name or member name hides the
  1285. // template-parameter name (6.4.10).
  1286. //
  1287. // This means that a template parameter scope should be searched immediately
  1288. // after searching the DeclContext for which it is a template parameter
  1289. // scope. For example, for
  1290. // template<typename T> template<typename U> template<typename V>
  1291. // void N::A<T>::B<U>::f(...)
  1292. // we search V then B<U> (and base classes) then U then A<T> (and base
  1293. // classes) then T then N then ::.
  1294. unsigned ScopeDepth = getTemplateDepth(S);
  1295. for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
  1296. DeclContext *SearchDCAfterScope = DC;
  1297. for (; DC; DC = DC->getLookupParent()) {
  1298. if (const TemplateParameterList *TPL =
  1299. cast<Decl>(DC)->getDescribedTemplateParams()) {
  1300. unsigned DCDepth = TPL->getDepth() + 1;
  1301. if (DCDepth > ScopeDepth)
  1302. continue;
  1303. if (ScopeDepth == DCDepth)
  1304. SearchDCAfterScope = DC = DC->getLookupParent();
  1305. break;
  1306. }
  1307. }
  1308. S->setLookupEntity(SearchDCAfterScope);
  1309. }
  1310. }
  1311. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1312. // We assume that the caller has already called
  1313. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1314. FunctionDecl *FD = D->getAsFunction();
  1315. if (!FD)
  1316. return;
  1317. // Same implementation as PushDeclContext, but enters the context
  1318. // from the lexical parent, rather than the top-level class.
  1319. assert(CurContext == FD->getLexicalParent() &&
  1320. "The next DeclContext should be lexically contained in the current one.");
  1321. CurContext = FD;
  1322. S->setEntity(CurContext);
  1323. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1324. ParmVarDecl *Param = FD->getParamDecl(P);
  1325. // If the parameter has an identifier, then add it to the scope
  1326. if (Param->getIdentifier()) {
  1327. S->AddDecl(Param);
  1328. IdResolver.AddDecl(Param);
  1329. }
  1330. }
  1331. }
  1332. void Sema::ActOnExitFunctionContext() {
  1333. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1334. // rather than the top-level class.
  1335. assert(CurContext && "DeclContext imbalance!");
  1336. CurContext = CurContext->getLexicalParent();
  1337. assert(CurContext && "Popped translation unit!");
  1338. }
  1339. /// Determine whether overloading is allowed for a new function
  1340. /// declaration considering prior declarations of the same name.
  1341. ///
  1342. /// This routine determines whether overloading is possible, not
  1343. /// whether a new declaration actually overloads a previous one.
  1344. /// It will return true in C++ (where overloads are alway permitted)
  1345. /// or, as a C extension, when either the new declaration or a
  1346. /// previous one is declared with the 'overloadable' attribute.
  1347. static bool AllowOverloadingOfFunction(const LookupResult &Previous,
  1348. ASTContext &Context,
  1349. const FunctionDecl *New) {
  1350. if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
  1351. return true;
  1352. // Multiversion function declarations are not overloads in the
  1353. // usual sense of that term, but lookup will report that an
  1354. // overload set was found if more than one multiversion function
  1355. // declaration is present for the same name. It is therefore
  1356. // inadequate to assume that some prior declaration(s) had
  1357. // the overloadable attribute; checking is required. Since one
  1358. // declaration is permitted to omit the attribute, it is necessary
  1359. // to check at least two; hence the 'any_of' check below. Note that
  1360. // the overloadable attribute is implicitly added to declarations
  1361. // that were required to have it but did not.
  1362. if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
  1363. return llvm::any_of(Previous, [](const NamedDecl *ND) {
  1364. return ND->hasAttr<OverloadableAttr>();
  1365. });
  1366. } else if (Previous.getResultKind() == LookupResult::Found)
  1367. return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
  1368. return false;
  1369. }
  1370. /// Add this decl to the scope shadowed decl chains.
  1371. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1372. // Move up the scope chain until we find the nearest enclosing
  1373. // non-transparent context. The declaration will be introduced into this
  1374. // scope.
  1375. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1376. S = S->getParent();
  1377. // Add scoped declarations into their context, so that they can be
  1378. // found later. Declarations without a context won't be inserted
  1379. // into any context.
  1380. if (AddToContext)
  1381. CurContext->addDecl(D);
  1382. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1383. // are function-local declarations.
  1384. if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
  1385. return;
  1386. // Template instantiations should also not be pushed into scope.
  1387. if (isa<FunctionDecl>(D) &&
  1388. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1389. return;
  1390. // If this replaces anything in the current scope,
  1391. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1392. IEnd = IdResolver.end();
  1393. for (; I != IEnd; ++I) {
  1394. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1395. S->RemoveDecl(*I);
  1396. IdResolver.RemoveDecl(*I);
  1397. // Should only need to replace one decl.
  1398. break;
  1399. }
  1400. }
  1401. S->AddDecl(D);
  1402. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1403. // Implicitly-generated labels may end up getting generated in an order that
  1404. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1405. // the label at the appropriate place in the identifier chain.
  1406. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1407. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1408. if (IDC == CurContext) {
  1409. if (!S->isDeclScope(*I))
  1410. continue;
  1411. } else if (IDC->Encloses(CurContext))
  1412. break;
  1413. }
  1414. IdResolver.InsertDeclAfter(I, D);
  1415. } else {
  1416. IdResolver.AddDecl(D);
  1417. }
  1418. warnOnReservedIdentifier(D);
  1419. }
  1420. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1421. bool AllowInlineNamespace) {
  1422. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1423. }
  1424. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1425. DeclContext *TargetDC = DC->getPrimaryContext();
  1426. do {
  1427. if (DeclContext *ScopeDC = S->getEntity())
  1428. if (ScopeDC->getPrimaryContext() == TargetDC)
  1429. return S;
  1430. } while ((S = S->getParent()));
  1431. return nullptr;
  1432. }
  1433. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1434. DeclContext*,
  1435. ASTContext&);
  1436. /// Filters out lookup results that don't fall within the given scope
  1437. /// as determined by isDeclInScope.
  1438. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1439. bool ConsiderLinkage,
  1440. bool AllowInlineNamespace) {
  1441. LookupResult::Filter F = R.makeFilter();
  1442. while (F.hasNext()) {
  1443. NamedDecl *D = F.next();
  1444. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1445. continue;
  1446. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1447. continue;
  1448. F.erase();
  1449. }
  1450. F.done();
  1451. }
  1452. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1453. /// have compatible owning modules.
  1454. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1455. // [module.interface]p7:
  1456. // A declaration is attached to a module as follows:
  1457. // - If the declaration is a non-dependent friend declaration that nominates a
  1458. // function with a declarator-id that is a qualified-id or template-id or that
  1459. // nominates a class other than with an elaborated-type-specifier with neither
  1460. // a nested-name-specifier nor a simple-template-id, it is attached to the
  1461. // module to which the friend is attached ([basic.link]).
  1462. if (New->getFriendObjectKind() &&
  1463. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1464. New->setLocalOwningModule(Old->getOwningModule());
  1465. makeMergedDefinitionVisible(New);
  1466. return false;
  1467. }
  1468. Module *NewM = New->getOwningModule();
  1469. Module *OldM = Old->getOwningModule();
  1470. if (NewM && NewM->isPrivateModule())
  1471. NewM = NewM->Parent;
  1472. if (OldM && OldM->isPrivateModule())
  1473. OldM = OldM->Parent;
  1474. if (NewM == OldM)
  1475. return false;
  1476. // Partitions are part of the module, but a partition could import another
  1477. // module, so verify that the PMIs agree.
  1478. if (NewM && OldM &&
  1479. (NewM->isModulePartition() || OldM->isModulePartition()) &&
  1480. NewM->getPrimaryModuleInterfaceName() ==
  1481. OldM->getPrimaryModuleInterfaceName())
  1482. return false;
  1483. bool NewIsModuleInterface = NewM && NewM->isModulePurview();
  1484. bool OldIsModuleInterface = OldM && OldM->isModulePurview();
  1485. if (NewIsModuleInterface || OldIsModuleInterface) {
  1486. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1487. // if a declaration of D [...] appears in the purview of a module, all
  1488. // other such declarations shall appear in the purview of the same module
  1489. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1490. << New
  1491. << NewIsModuleInterface
  1492. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1493. << OldIsModuleInterface
  1494. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1495. Diag(Old->getLocation(), diag::note_previous_declaration);
  1496. New->setInvalidDecl();
  1497. return true;
  1498. }
  1499. return false;
  1500. }
  1501. // [module.interface]p6:
  1502. // A redeclaration of an entity X is implicitly exported if X was introduced by
  1503. // an exported declaration; otherwise it shall not be exported.
  1504. bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) {
  1505. // [module.interface]p1:
  1506. // An export-declaration shall inhabit a namespace scope.
  1507. //
  1508. // So it is meaningless to talk about redeclaration which is not at namespace
  1509. // scope.
  1510. if (!New->getLexicalDeclContext()
  1511. ->getNonTransparentContext()
  1512. ->isFileContext() ||
  1513. !Old->getLexicalDeclContext()
  1514. ->getNonTransparentContext()
  1515. ->isFileContext())
  1516. return false;
  1517. bool IsNewExported = New->isInExportDeclContext();
  1518. bool IsOldExported = Old->isInExportDeclContext();
  1519. // It should be irrevelant if both of them are not exported.
  1520. if (!IsNewExported && !IsOldExported)
  1521. return false;
  1522. if (IsOldExported)
  1523. return false;
  1524. assert(IsNewExported);
  1525. auto Lk = Old->getFormalLinkage();
  1526. int S = 0;
  1527. if (Lk == Linkage::InternalLinkage)
  1528. S = 1;
  1529. else if (Lk == Linkage::ModuleLinkage)
  1530. S = 2;
  1531. Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S;
  1532. Diag(Old->getLocation(), diag::note_previous_declaration);
  1533. return true;
  1534. }
  1535. // A wrapper function for checking the semantic restrictions of
  1536. // a redeclaration within a module.
  1537. bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) {
  1538. if (CheckRedeclarationModuleOwnership(New, Old))
  1539. return true;
  1540. if (CheckRedeclarationExported(New, Old))
  1541. return true;
  1542. return false;
  1543. }
  1544. // Check the redefinition in C++20 Modules.
  1545. //
  1546. // [basic.def.odr]p14:
  1547. // For any definable item D with definitions in multiple translation units,
  1548. // - if D is a non-inline non-templated function or variable, or
  1549. // - if the definitions in different translation units do not satisfy the
  1550. // following requirements,
  1551. // the program is ill-formed; a diagnostic is required only if the definable
  1552. // item is attached to a named module and a prior definition is reachable at
  1553. // the point where a later definition occurs.
  1554. // - Each such definition shall not be attached to a named module
  1555. // ([module.unit]).
  1556. // - Each such definition shall consist of the same sequence of tokens, ...
  1557. // ...
  1558. //
  1559. // Return true if the redefinition is not allowed. Return false otherwise.
  1560. bool Sema::IsRedefinitionInModule(const NamedDecl *New,
  1561. const NamedDecl *Old) const {
  1562. assert(getASTContext().isSameEntity(New, Old) &&
  1563. "New and Old are not the same definition, we should diagnostic it "
  1564. "immediately instead of checking it.");
  1565. assert(const_cast<Sema *>(this)->isReachable(New) &&
  1566. const_cast<Sema *>(this)->isReachable(Old) &&
  1567. "We shouldn't see unreachable definitions here.");
  1568. Module *NewM = New->getOwningModule();
  1569. Module *OldM = Old->getOwningModule();
  1570. // We only checks for named modules here. The header like modules is skipped.
  1571. // FIXME: This is not right if we import the header like modules in the module
  1572. // purview.
  1573. //
  1574. // For example, assuming "header.h" provides definition for `D`.
  1575. // ```C++
  1576. // //--- M.cppm
  1577. // export module M;
  1578. // import "header.h"; // or #include "header.h" but import it by clang modules
  1579. // actually.
  1580. //
  1581. // //--- Use.cpp
  1582. // import M;
  1583. // import "header.h"; // or uses clang modules.
  1584. // ```
  1585. //
  1586. // In this case, `D` has multiple definitions in multiple TU (M.cppm and
  1587. // Use.cpp) and `D` is attached to a named module `M`. The compiler should
  1588. // reject it. But the current implementation couldn't detect the case since we
  1589. // don't record the information about the importee modules.
  1590. //
  1591. // But this might not be painful in practice. Since the design of C++20 Named
  1592. // Modules suggests us to use headers in global module fragment instead of
  1593. // module purview.
  1594. if (NewM && NewM->isHeaderLikeModule())
  1595. NewM = nullptr;
  1596. if (OldM && OldM->isHeaderLikeModule())
  1597. OldM = nullptr;
  1598. if (!NewM && !OldM)
  1599. return true;
  1600. // [basic.def.odr]p14.3
  1601. // Each such definition shall not be attached to a named module
  1602. // ([module.unit]).
  1603. if ((NewM && NewM->isModulePurview()) || (OldM && OldM->isModulePurview()))
  1604. return true;
  1605. // Then New and Old lives in the same TU if their share one same module unit.
  1606. if (NewM)
  1607. NewM = NewM->getTopLevelModule();
  1608. if (OldM)
  1609. OldM = OldM->getTopLevelModule();
  1610. return OldM == NewM;
  1611. }
  1612. static bool isUsingDecl(NamedDecl *D) {
  1613. return isa<UsingShadowDecl>(D) ||
  1614. isa<UnresolvedUsingTypenameDecl>(D) ||
  1615. isa<UnresolvedUsingValueDecl>(D);
  1616. }
  1617. /// Removes using shadow declarations from the lookup results.
  1618. static void RemoveUsingDecls(LookupResult &R) {
  1619. LookupResult::Filter F = R.makeFilter();
  1620. while (F.hasNext())
  1621. if (isUsingDecl(F.next()))
  1622. F.erase();
  1623. F.done();
  1624. }
  1625. /// Check for this common pattern:
  1626. /// @code
  1627. /// class S {
  1628. /// S(const S&); // DO NOT IMPLEMENT
  1629. /// void operator=(const S&); // DO NOT IMPLEMENT
  1630. /// };
  1631. /// @endcode
  1632. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1633. // FIXME: Should check for private access too but access is set after we get
  1634. // the decl here.
  1635. if (D->doesThisDeclarationHaveABody())
  1636. return false;
  1637. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1638. return CD->isCopyConstructor();
  1639. return D->isCopyAssignmentOperator();
  1640. }
  1641. // We need this to handle
  1642. //
  1643. // typedef struct {
  1644. // void *foo() { return 0; }
  1645. // } A;
  1646. //
  1647. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1648. // for example. If 'A', foo will have external linkage. If we have '*A',
  1649. // foo will have no linkage. Since we can't know until we get to the end
  1650. // of the typedef, this function finds out if D might have non-external linkage.
  1651. // Callers should verify at the end of the TU if it D has external linkage or
  1652. // not.
  1653. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1654. const DeclContext *DC = D->getDeclContext();
  1655. while (!DC->isTranslationUnit()) {
  1656. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1657. if (!RD->hasNameForLinkage())
  1658. return true;
  1659. }
  1660. DC = DC->getParent();
  1661. }
  1662. return !D->isExternallyVisible();
  1663. }
  1664. // FIXME: This needs to be refactored; some other isInMainFile users want
  1665. // these semantics.
  1666. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1667. if (S.TUKind != TU_Complete || S.getLangOpts().IsHeaderFile)
  1668. return false;
  1669. return S.SourceMgr.isInMainFile(Loc);
  1670. }
  1671. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1672. assert(D);
  1673. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1674. return false;
  1675. // Ignore all entities declared within templates, and out-of-line definitions
  1676. // of members of class templates.
  1677. if (D->getDeclContext()->isDependentContext() ||
  1678. D->getLexicalDeclContext()->isDependentContext())
  1679. return false;
  1680. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1681. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1682. return false;
  1683. // A non-out-of-line declaration of a member specialization was implicitly
  1684. // instantiated; it's the out-of-line declaration that we're interested in.
  1685. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1686. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1687. return false;
  1688. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1689. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1690. return false;
  1691. } else {
  1692. // 'static inline' functions are defined in headers; don't warn.
  1693. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1694. return false;
  1695. }
  1696. if (FD->doesThisDeclarationHaveABody() &&
  1697. Context.DeclMustBeEmitted(FD))
  1698. return false;
  1699. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1700. // Constants and utility variables are defined in headers with internal
  1701. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1702. // like "inline".)
  1703. if (!isMainFileLoc(*this, VD->getLocation()))
  1704. return false;
  1705. if (Context.DeclMustBeEmitted(VD))
  1706. return false;
  1707. if (VD->isStaticDataMember() &&
  1708. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1709. return false;
  1710. if (VD->isStaticDataMember() &&
  1711. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1712. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1713. return false;
  1714. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1715. return false;
  1716. } else {
  1717. return false;
  1718. }
  1719. // Only warn for unused decls internal to the translation unit.
  1720. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1721. // for inline functions defined in the main source file, for instance.
  1722. return mightHaveNonExternalLinkage(D);
  1723. }
  1724. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1725. if (!D)
  1726. return;
  1727. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1728. const FunctionDecl *First = FD->getFirstDecl();
  1729. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1730. return; // First should already be in the vector.
  1731. }
  1732. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1733. const VarDecl *First = VD->getFirstDecl();
  1734. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1735. return; // First should already be in the vector.
  1736. }
  1737. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1738. UnusedFileScopedDecls.push_back(D);
  1739. }
  1740. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1741. if (D->isInvalidDecl())
  1742. return false;
  1743. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1744. // For a decomposition declaration, warn if none of the bindings are
  1745. // referenced, instead of if the variable itself is referenced (which
  1746. // it is, by the bindings' expressions).
  1747. for (auto *BD : DD->bindings())
  1748. if (BD->isReferenced())
  1749. return false;
  1750. } else if (!D->getDeclName()) {
  1751. return false;
  1752. } else if (D->isReferenced() || D->isUsed()) {
  1753. return false;
  1754. }
  1755. if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
  1756. return false;
  1757. if (isa<LabelDecl>(D))
  1758. return true;
  1759. // Except for labels, we only care about unused decls that are local to
  1760. // functions.
  1761. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1762. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1763. // For dependent types, the diagnostic is deferred.
  1764. WithinFunction =
  1765. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1766. if (!WithinFunction)
  1767. return false;
  1768. if (isa<TypedefNameDecl>(D))
  1769. return true;
  1770. // White-list anything that isn't a local variable.
  1771. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1772. return false;
  1773. // Types of valid local variables should be complete, so this should succeed.
  1774. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1775. const Expr *Init = VD->getInit();
  1776. if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init))
  1777. Init = Cleanups->getSubExpr();
  1778. const auto *Ty = VD->getType().getTypePtr();
  1779. // Only look at the outermost level of typedef.
  1780. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1781. // Allow anything marked with __attribute__((unused)).
  1782. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1783. return false;
  1784. }
  1785. // Warn for reference variables whose initializtion performs lifetime
  1786. // extension.
  1787. if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) {
  1788. if (MTE->getExtendingDecl()) {
  1789. Ty = VD->getType().getNonReferenceType().getTypePtr();
  1790. Init = MTE->getSubExpr()->IgnoreImplicitAsWritten();
  1791. }
  1792. }
  1793. // If we failed to complete the type for some reason, or if the type is
  1794. // dependent, don't diagnose the variable.
  1795. if (Ty->isIncompleteType() || Ty->isDependentType())
  1796. return false;
  1797. // Look at the element type to ensure that the warning behaviour is
  1798. // consistent for both scalars and arrays.
  1799. Ty = Ty->getBaseElementTypeUnsafe();
  1800. if (const TagType *TT = Ty->getAs<TagType>()) {
  1801. const TagDecl *Tag = TT->getDecl();
  1802. if (Tag->hasAttr<UnusedAttr>())
  1803. return false;
  1804. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1805. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1806. return false;
  1807. if (Init) {
  1808. const CXXConstructExpr *Construct =
  1809. dyn_cast<CXXConstructExpr>(Init);
  1810. if (Construct && !Construct->isElidable()) {
  1811. CXXConstructorDecl *CD = Construct->getConstructor();
  1812. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1813. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1814. return false;
  1815. }
  1816. // Suppress the warning if we don't know how this is constructed, and
  1817. // it could possibly be non-trivial constructor.
  1818. if (Init->isTypeDependent()) {
  1819. for (const CXXConstructorDecl *Ctor : RD->ctors())
  1820. if (!Ctor->isTrivial())
  1821. return false;
  1822. }
  1823. // Suppress the warning if the constructor is unresolved because
  1824. // its arguments are dependent.
  1825. if (isa<CXXUnresolvedConstructExpr>(Init))
  1826. return false;
  1827. }
  1828. }
  1829. }
  1830. // TODO: __attribute__((unused)) templates?
  1831. }
  1832. return true;
  1833. }
  1834. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1835. FixItHint &Hint) {
  1836. if (isa<LabelDecl>(D)) {
  1837. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1838. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1839. true);
  1840. if (AfterColon.isInvalid())
  1841. return;
  1842. Hint = FixItHint::CreateRemoval(
  1843. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1844. }
  1845. }
  1846. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1847. DiagnoseUnusedNestedTypedefs(
  1848. D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
  1849. }
  1850. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D,
  1851. DiagReceiverTy DiagReceiver) {
  1852. if (D->getTypeForDecl()->isDependentType())
  1853. return;
  1854. for (auto *TmpD : D->decls()) {
  1855. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1856. DiagnoseUnusedDecl(T, DiagReceiver);
  1857. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1858. DiagnoseUnusedNestedTypedefs(R, DiagReceiver);
  1859. }
  1860. }
  1861. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1862. DiagnoseUnusedDecl(
  1863. D, [this](SourceLocation Loc, PartialDiagnostic PD) { Diag(Loc, PD); });
  1864. }
  1865. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1866. /// unless they are marked attr(unused).
  1867. void Sema::DiagnoseUnusedDecl(const NamedDecl *D, DiagReceiverTy DiagReceiver) {
  1868. if (!ShouldDiagnoseUnusedDecl(D))
  1869. return;
  1870. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1871. // typedefs can be referenced later on, so the diagnostics are emitted
  1872. // at end-of-translation-unit.
  1873. UnusedLocalTypedefNameCandidates.insert(TD);
  1874. return;
  1875. }
  1876. FixItHint Hint;
  1877. GenerateFixForUnusedDecl(D, Context, Hint);
  1878. unsigned DiagID;
  1879. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1880. DiagID = diag::warn_unused_exception_param;
  1881. else if (isa<LabelDecl>(D))
  1882. DiagID = diag::warn_unused_label;
  1883. else
  1884. DiagID = diag::warn_unused_variable;
  1885. DiagReceiver(D->getLocation(), PDiag(DiagID) << D << Hint);
  1886. }
  1887. void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD,
  1888. DiagReceiverTy DiagReceiver) {
  1889. // If it's not referenced, it can't be set. If it has the Cleanup attribute,
  1890. // it's not really unused.
  1891. if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
  1892. VD->hasAttr<CleanupAttr>())
  1893. return;
  1894. const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
  1895. if (Ty->isReferenceType() || Ty->isDependentType())
  1896. return;
  1897. if (const TagType *TT = Ty->getAs<TagType>()) {
  1898. const TagDecl *Tag = TT->getDecl();
  1899. if (Tag->hasAttr<UnusedAttr>())
  1900. return;
  1901. // In C++, don't warn for record types that don't have WarnUnusedAttr, to
  1902. // mimic gcc's behavior.
  1903. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1904. if (!RD->hasAttr<WarnUnusedAttr>())
  1905. return;
  1906. }
  1907. }
  1908. // Don't warn about __block Objective-C pointer variables, as they might
  1909. // be assigned in the block but not used elsewhere for the purpose of lifetime
  1910. // extension.
  1911. if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
  1912. return;
  1913. // Don't warn about Objective-C pointer variables with precise lifetime
  1914. // semantics; they can be used to ensure ARC releases the object at a known
  1915. // time, which may mean assignment but no other references.
  1916. if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
  1917. return;
  1918. auto iter = RefsMinusAssignments.find(VD);
  1919. if (iter == RefsMinusAssignments.end())
  1920. return;
  1921. assert(iter->getSecond() >= 0 &&
  1922. "Found a negative number of references to a VarDecl");
  1923. if (iter->getSecond() != 0)
  1924. return;
  1925. unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
  1926. : diag::warn_unused_but_set_variable;
  1927. DiagReceiver(VD->getLocation(), PDiag(DiagID) << VD);
  1928. }
  1929. static void CheckPoppedLabel(LabelDecl *L, Sema &S,
  1930. Sema::DiagReceiverTy DiagReceiver) {
  1931. // Verify that we have no forward references left. If so, there was a goto
  1932. // or address of a label taken, but no definition of it. Label fwd
  1933. // definitions are indicated with a null substmt which is also not a resolved
  1934. // MS inline assembly label name.
  1935. bool Diagnose = false;
  1936. if (L->isMSAsmLabel())
  1937. Diagnose = !L->isResolvedMSAsmLabel();
  1938. else
  1939. Diagnose = L->getStmt() == nullptr;
  1940. if (Diagnose)
  1941. DiagReceiver(L->getLocation(), S.PDiag(diag::err_undeclared_label_use)
  1942. << L);
  1943. }
  1944. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1945. S->applyNRVO();
  1946. if (S->decl_empty()) return;
  1947. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1948. "Scope shouldn't contain decls!");
  1949. /// We visit the decls in non-deterministic order, but we want diagnostics
  1950. /// emitted in deterministic order. Collect any diagnostic that may be emitted
  1951. /// and sort the diagnostics before emitting them, after we visited all decls.
  1952. struct LocAndDiag {
  1953. SourceLocation Loc;
  1954. std::optional<SourceLocation> PreviousDeclLoc;
  1955. PartialDiagnostic PD;
  1956. };
  1957. SmallVector<LocAndDiag, 16> DeclDiags;
  1958. auto addDiag = [&DeclDiags](SourceLocation Loc, PartialDiagnostic PD) {
  1959. DeclDiags.push_back(LocAndDiag{Loc, std::nullopt, std::move(PD)});
  1960. };
  1961. auto addDiagWithPrev = [&DeclDiags](SourceLocation Loc,
  1962. SourceLocation PreviousDeclLoc,
  1963. PartialDiagnostic PD) {
  1964. DeclDiags.push_back(LocAndDiag{Loc, PreviousDeclLoc, std::move(PD)});
  1965. };
  1966. for (auto *TmpD : S->decls()) {
  1967. assert(TmpD && "This decl didn't get pushed??");
  1968. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1969. NamedDecl *D = cast<NamedDecl>(TmpD);
  1970. // Diagnose unused variables in this scope.
  1971. if (!S->hasUnrecoverableErrorOccurred()) {
  1972. DiagnoseUnusedDecl(D, addDiag);
  1973. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1974. DiagnoseUnusedNestedTypedefs(RD, addDiag);
  1975. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1976. DiagnoseUnusedButSetDecl(VD, addDiag);
  1977. RefsMinusAssignments.erase(VD);
  1978. }
  1979. }
  1980. if (!D->getDeclName()) continue;
  1981. // If this was a forward reference to a label, verify it was defined.
  1982. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1983. CheckPoppedLabel(LD, *this, addDiag);
  1984. // Remove this name from our lexical scope, and warn on it if we haven't
  1985. // already.
  1986. IdResolver.RemoveDecl(D);
  1987. auto ShadowI = ShadowingDecls.find(D);
  1988. if (ShadowI != ShadowingDecls.end()) {
  1989. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1990. addDiagWithPrev(D->getLocation(), FD->getLocation(),
  1991. PDiag(diag::warn_ctor_parm_shadows_field)
  1992. << D << FD << FD->getParent());
  1993. }
  1994. ShadowingDecls.erase(ShadowI);
  1995. }
  1996. }
  1997. llvm::sort(DeclDiags,
  1998. [](const LocAndDiag &LHS, const LocAndDiag &RHS) -> bool {
  1999. // The particular order for diagnostics is not important, as long
  2000. // as the order is deterministic. Using the raw location is going
  2001. // to generally be in source order unless there are macro
  2002. // expansions involved.
  2003. return LHS.Loc.getRawEncoding() < RHS.Loc.getRawEncoding();
  2004. });
  2005. for (const LocAndDiag &D : DeclDiags) {
  2006. Diag(D.Loc, D.PD);
  2007. if (D.PreviousDeclLoc)
  2008. Diag(*D.PreviousDeclLoc, diag::note_previous_declaration);
  2009. }
  2010. }
  2011. /// Look for an Objective-C class in the translation unit.
  2012. ///
  2013. /// \param Id The name of the Objective-C class we're looking for. If
  2014. /// typo-correction fixes this name, the Id will be updated
  2015. /// to the fixed name.
  2016. ///
  2017. /// \param IdLoc The location of the name in the translation unit.
  2018. ///
  2019. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  2020. /// if there is no class with the given name.
  2021. ///
  2022. /// \returns The declaration of the named Objective-C class, or NULL if the
  2023. /// class could not be found.
  2024. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  2025. SourceLocation IdLoc,
  2026. bool DoTypoCorrection) {
  2027. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  2028. // creation from this context.
  2029. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  2030. if (!IDecl && DoTypoCorrection) {
  2031. // Perform typo correction at the given location, but only if we
  2032. // find an Objective-C class name.
  2033. DeclFilterCCC<ObjCInterfaceDecl> CCC{};
  2034. if (TypoCorrection C =
  2035. CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
  2036. TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
  2037. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  2038. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  2039. Id = IDecl->getIdentifier();
  2040. }
  2041. }
  2042. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  2043. // This routine must always return a class definition, if any.
  2044. if (Def && Def->getDefinition())
  2045. Def = Def->getDefinition();
  2046. return Def;
  2047. }
  2048. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  2049. /// from S, where a non-field would be declared. This routine copes
  2050. /// with the difference between C and C++ scoping rules in structs and
  2051. /// unions. For example, the following code is well-formed in C but
  2052. /// ill-formed in C++:
  2053. /// @code
  2054. /// struct S6 {
  2055. /// enum { BAR } e;
  2056. /// };
  2057. ///
  2058. /// void test_S6() {
  2059. /// struct S6 a;
  2060. /// a.e = BAR;
  2061. /// }
  2062. /// @endcode
  2063. /// For the declaration of BAR, this routine will return a different
  2064. /// scope. The scope S will be the scope of the unnamed enumeration
  2065. /// within S6. In C++, this routine will return the scope associated
  2066. /// with S6, because the enumeration's scope is a transparent
  2067. /// context but structures can contain non-field names. In C, this
  2068. /// routine will return the translation unit scope, since the
  2069. /// enumeration's scope is a transparent context and structures cannot
  2070. /// contain non-field names.
  2071. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  2072. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  2073. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  2074. (S->isClassScope() && !getLangOpts().CPlusPlus))
  2075. S = S->getParent();
  2076. return S;
  2077. }
  2078. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  2079. ASTContext::GetBuiltinTypeError Error) {
  2080. switch (Error) {
  2081. case ASTContext::GE_None:
  2082. return "";
  2083. case ASTContext::GE_Missing_type:
  2084. return BuiltinInfo.getHeaderName(ID);
  2085. case ASTContext::GE_Missing_stdio:
  2086. return "stdio.h";
  2087. case ASTContext::GE_Missing_setjmp:
  2088. return "setjmp.h";
  2089. case ASTContext::GE_Missing_ucontext:
  2090. return "ucontext.h";
  2091. }
  2092. llvm_unreachable("unhandled error kind");
  2093. }
  2094. FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
  2095. unsigned ID, SourceLocation Loc) {
  2096. DeclContext *Parent = Context.getTranslationUnitDecl();
  2097. if (getLangOpts().CPlusPlus) {
  2098. LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
  2099. Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
  2100. CLinkageDecl->setImplicit();
  2101. Parent->addDecl(CLinkageDecl);
  2102. Parent = CLinkageDecl;
  2103. }
  2104. FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
  2105. /*TInfo=*/nullptr, SC_Extern,
  2106. getCurFPFeatures().isFPConstrained(),
  2107. false, Type->isFunctionProtoType());
  2108. New->setImplicit();
  2109. New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
  2110. // Create Decl objects for each parameter, adding them to the
  2111. // FunctionDecl.
  2112. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
  2113. SmallVector<ParmVarDecl *, 16> Params;
  2114. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  2115. ParmVarDecl *parm = ParmVarDecl::Create(
  2116. Context, New, SourceLocation(), SourceLocation(), nullptr,
  2117. FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
  2118. parm->setScopeInfo(0, i);
  2119. Params.push_back(parm);
  2120. }
  2121. New->setParams(Params);
  2122. }
  2123. AddKnownFunctionAttributes(New);
  2124. return New;
  2125. }
  2126. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  2127. /// file scope. lazily create a decl for it. ForRedeclaration is true
  2128. /// if we're creating this built-in in anticipation of redeclaring the
  2129. /// built-in.
  2130. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  2131. Scope *S, bool ForRedeclaration,
  2132. SourceLocation Loc) {
  2133. LookupNecessaryTypesForBuiltin(S, ID);
  2134. ASTContext::GetBuiltinTypeError Error;
  2135. QualType R = Context.GetBuiltinType(ID, Error);
  2136. if (Error) {
  2137. if (!ForRedeclaration)
  2138. return nullptr;
  2139. // If we have a builtin without an associated type we should not emit a
  2140. // warning when we were not able to find a type for it.
  2141. if (Error == ASTContext::GE_Missing_type ||
  2142. Context.BuiltinInfo.allowTypeMismatch(ID))
  2143. return nullptr;
  2144. // If we could not find a type for setjmp it is because the jmp_buf type was
  2145. // not defined prior to the setjmp declaration.
  2146. if (Error == ASTContext::GE_Missing_setjmp) {
  2147. Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
  2148. << Context.BuiltinInfo.getName(ID);
  2149. return nullptr;
  2150. }
  2151. // Generally, we emit a warning that the declaration requires the
  2152. // appropriate header.
  2153. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  2154. << getHeaderName(Context.BuiltinInfo, ID, Error)
  2155. << Context.BuiltinInfo.getName(ID);
  2156. return nullptr;
  2157. }
  2158. if (!ForRedeclaration &&
  2159. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  2160. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  2161. Diag(Loc, LangOpts.C99 ? diag::ext_implicit_lib_function_decl_c99
  2162. : diag::ext_implicit_lib_function_decl)
  2163. << Context.BuiltinInfo.getName(ID) << R;
  2164. if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
  2165. Diag(Loc, diag::note_include_header_or_declare)
  2166. << Header << Context.BuiltinInfo.getName(ID);
  2167. }
  2168. if (R.isNull())
  2169. return nullptr;
  2170. FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
  2171. RegisterLocallyScopedExternCDecl(New, S);
  2172. // TUScope is the translation-unit scope to insert this function into.
  2173. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  2174. // relate Scopes to DeclContexts, and probably eliminate CurContext
  2175. // entirely, but we're not there yet.
  2176. DeclContext *SavedContext = CurContext;
  2177. CurContext = New->getDeclContext();
  2178. PushOnScopeChains(New, TUScope);
  2179. CurContext = SavedContext;
  2180. return New;
  2181. }
  2182. /// Typedef declarations don't have linkage, but they still denote the same
  2183. /// entity if their types are the same.
  2184. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  2185. /// isSameEntity.
  2186. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  2187. TypedefNameDecl *Decl,
  2188. LookupResult &Previous) {
  2189. // This is only interesting when modules are enabled.
  2190. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  2191. return;
  2192. // Empty sets are uninteresting.
  2193. if (Previous.empty())
  2194. return;
  2195. LookupResult::Filter Filter = Previous.makeFilter();
  2196. while (Filter.hasNext()) {
  2197. NamedDecl *Old = Filter.next();
  2198. // Non-hidden declarations are never ignored.
  2199. if (S.isVisible(Old))
  2200. continue;
  2201. // Declarations of the same entity are not ignored, even if they have
  2202. // different linkages.
  2203. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  2204. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  2205. Decl->getUnderlyingType()))
  2206. continue;
  2207. // If both declarations give a tag declaration a typedef name for linkage
  2208. // purposes, then they declare the same entity.
  2209. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  2210. Decl->getAnonDeclWithTypedefName())
  2211. continue;
  2212. }
  2213. Filter.erase();
  2214. }
  2215. Filter.done();
  2216. }
  2217. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  2218. QualType OldType;
  2219. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  2220. OldType = OldTypedef->getUnderlyingType();
  2221. else
  2222. OldType = Context.getTypeDeclType(Old);
  2223. QualType NewType = New->getUnderlyingType();
  2224. if (NewType->isVariablyModifiedType()) {
  2225. // Must not redefine a typedef with a variably-modified type.
  2226. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  2227. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  2228. << Kind << NewType;
  2229. if (Old->getLocation().isValid())
  2230. notePreviousDefinition(Old, New->getLocation());
  2231. New->setInvalidDecl();
  2232. return true;
  2233. }
  2234. if (OldType != NewType &&
  2235. !OldType->isDependentType() &&
  2236. !NewType->isDependentType() &&
  2237. !Context.hasSameType(OldType, NewType)) {
  2238. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  2239. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  2240. << Kind << NewType << OldType;
  2241. if (Old->getLocation().isValid())
  2242. notePreviousDefinition(Old, New->getLocation());
  2243. New->setInvalidDecl();
  2244. return true;
  2245. }
  2246. return false;
  2247. }
  2248. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  2249. /// same name and scope as a previous declaration 'Old'. Figure out
  2250. /// how to resolve this situation, merging decls or emitting
  2251. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  2252. ///
  2253. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  2254. LookupResult &OldDecls) {
  2255. // If the new decl is known invalid already, don't bother doing any
  2256. // merging checks.
  2257. if (New->isInvalidDecl()) return;
  2258. // Allow multiple definitions for ObjC built-in typedefs.
  2259. // FIXME: Verify the underlying types are equivalent!
  2260. if (getLangOpts().ObjC) {
  2261. const IdentifierInfo *TypeID = New->getIdentifier();
  2262. switch (TypeID->getLength()) {
  2263. default: break;
  2264. case 2:
  2265. {
  2266. if (!TypeID->isStr("id"))
  2267. break;
  2268. QualType T = New->getUnderlyingType();
  2269. if (!T->isPointerType())
  2270. break;
  2271. if (!T->isVoidPointerType()) {
  2272. QualType PT = T->castAs<PointerType>()->getPointeeType();
  2273. if (!PT->isStructureType())
  2274. break;
  2275. }
  2276. Context.setObjCIdRedefinitionType(T);
  2277. // Install the built-in type for 'id', ignoring the current definition.
  2278. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  2279. return;
  2280. }
  2281. case 5:
  2282. if (!TypeID->isStr("Class"))
  2283. break;
  2284. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  2285. // Install the built-in type for 'Class', ignoring the current definition.
  2286. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  2287. return;
  2288. case 3:
  2289. if (!TypeID->isStr("SEL"))
  2290. break;
  2291. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  2292. // Install the built-in type for 'SEL', ignoring the current definition.
  2293. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  2294. return;
  2295. }
  2296. // Fall through - the typedef name was not a builtin type.
  2297. }
  2298. // Verify the old decl was also a type.
  2299. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  2300. if (!Old) {
  2301. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2302. << New->getDeclName();
  2303. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  2304. if (OldD->getLocation().isValid())
  2305. notePreviousDefinition(OldD, New->getLocation());
  2306. return New->setInvalidDecl();
  2307. }
  2308. // If the old declaration is invalid, just give up here.
  2309. if (Old->isInvalidDecl())
  2310. return New->setInvalidDecl();
  2311. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  2312. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  2313. auto *NewTag = New->getAnonDeclWithTypedefName();
  2314. NamedDecl *Hidden = nullptr;
  2315. if (OldTag && NewTag &&
  2316. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  2317. !hasVisibleDefinition(OldTag, &Hidden)) {
  2318. // There is a definition of this tag, but it is not visible. Use it
  2319. // instead of our tag.
  2320. New->setTypeForDecl(OldTD->getTypeForDecl());
  2321. if (OldTD->isModed())
  2322. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  2323. OldTD->getUnderlyingType());
  2324. else
  2325. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  2326. // Make the old tag definition visible.
  2327. makeMergedDefinitionVisible(Hidden);
  2328. // If this was an unscoped enumeration, yank all of its enumerators
  2329. // out of the scope.
  2330. if (isa<EnumDecl>(NewTag)) {
  2331. Scope *EnumScope = getNonFieldDeclScope(S);
  2332. for (auto *D : NewTag->decls()) {
  2333. auto *ED = cast<EnumConstantDecl>(D);
  2334. assert(EnumScope->isDeclScope(ED));
  2335. EnumScope->RemoveDecl(ED);
  2336. IdResolver.RemoveDecl(ED);
  2337. ED->getLexicalDeclContext()->removeDecl(ED);
  2338. }
  2339. }
  2340. }
  2341. }
  2342. // If the typedef types are not identical, reject them in all languages and
  2343. // with any extensions enabled.
  2344. if (isIncompatibleTypedef(Old, New))
  2345. return;
  2346. // The types match. Link up the redeclaration chain and merge attributes if
  2347. // the old declaration was a typedef.
  2348. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  2349. New->setPreviousDecl(Typedef);
  2350. mergeDeclAttributes(New, Old);
  2351. }
  2352. if (getLangOpts().MicrosoftExt)
  2353. return;
  2354. if (getLangOpts().CPlusPlus) {
  2355. // C++ [dcl.typedef]p2:
  2356. // In a given non-class scope, a typedef specifier can be used to
  2357. // redefine the name of any type declared in that scope to refer
  2358. // to the type to which it already refers.
  2359. if (!isa<CXXRecordDecl>(CurContext))
  2360. return;
  2361. // C++0x [dcl.typedef]p4:
  2362. // In a given class scope, a typedef specifier can be used to redefine
  2363. // any class-name declared in that scope that is not also a typedef-name
  2364. // to refer to the type to which it already refers.
  2365. //
  2366. // This wording came in via DR424, which was a correction to the
  2367. // wording in DR56, which accidentally banned code like:
  2368. //
  2369. // struct S {
  2370. // typedef struct A { } A;
  2371. // };
  2372. //
  2373. // in the C++03 standard. We implement the C++0x semantics, which
  2374. // allow the above but disallow
  2375. //
  2376. // struct S {
  2377. // typedef int I;
  2378. // typedef int I;
  2379. // };
  2380. //
  2381. // since that was the intent of DR56.
  2382. if (!isa<TypedefNameDecl>(Old))
  2383. return;
  2384. Diag(New->getLocation(), diag::err_redefinition)
  2385. << New->getDeclName();
  2386. notePreviousDefinition(Old, New->getLocation());
  2387. return New->setInvalidDecl();
  2388. }
  2389. // Modules always permit redefinition of typedefs, as does C11.
  2390. if (getLangOpts().Modules || getLangOpts().C11)
  2391. return;
  2392. // If we have a redefinition of a typedef in C, emit a warning. This warning
  2393. // is normally mapped to an error, but can be controlled with
  2394. // -Wtypedef-redefinition. If either the original or the redefinition is
  2395. // in a system header, don't emit this for compatibility with GCC.
  2396. if (getDiagnostics().getSuppressSystemWarnings() &&
  2397. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  2398. (Old->isImplicit() ||
  2399. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  2400. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  2401. return;
  2402. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2403. << New->getDeclName();
  2404. notePreviousDefinition(Old, New->getLocation());
  2405. }
  2406. /// DeclhasAttr - returns true if decl Declaration already has the target
  2407. /// attribute.
  2408. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2409. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2410. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2411. for (const auto *i : D->attrs())
  2412. if (i->getKind() == A->getKind()) {
  2413. if (Ann) {
  2414. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2415. return true;
  2416. continue;
  2417. }
  2418. // FIXME: Don't hardcode this check
  2419. if (OA && isa<OwnershipAttr>(i))
  2420. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2421. return true;
  2422. }
  2423. return false;
  2424. }
  2425. static bool isAttributeTargetADefinition(Decl *D) {
  2426. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2427. return VD->isThisDeclarationADefinition();
  2428. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2429. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2430. return true;
  2431. }
  2432. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2433. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2434. ///
  2435. /// \return \c true if any attributes were added to \p New.
  2436. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2437. // Look for alignas attributes on Old, and pick out whichever attribute
  2438. // specifies the strictest alignment requirement.
  2439. AlignedAttr *OldAlignasAttr = nullptr;
  2440. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2441. unsigned OldAlign = 0;
  2442. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2443. // FIXME: We have no way of representing inherited dependent alignments
  2444. // in a case like:
  2445. // template<int A, int B> struct alignas(A) X;
  2446. // template<int A, int B> struct alignas(B) X {};
  2447. // For now, we just ignore any alignas attributes which are not on the
  2448. // definition in such a case.
  2449. if (I->isAlignmentDependent())
  2450. return false;
  2451. if (I->isAlignas())
  2452. OldAlignasAttr = I;
  2453. unsigned Align = I->getAlignment(S.Context);
  2454. if (Align > OldAlign) {
  2455. OldAlign = Align;
  2456. OldStrictestAlignAttr = I;
  2457. }
  2458. }
  2459. // Look for alignas attributes on New.
  2460. AlignedAttr *NewAlignasAttr = nullptr;
  2461. unsigned NewAlign = 0;
  2462. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2463. if (I->isAlignmentDependent())
  2464. return false;
  2465. if (I->isAlignas())
  2466. NewAlignasAttr = I;
  2467. unsigned Align = I->getAlignment(S.Context);
  2468. if (Align > NewAlign)
  2469. NewAlign = Align;
  2470. }
  2471. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2472. // Both declarations have 'alignas' attributes. We require them to match.
  2473. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2474. // fall short. (If two declarations both have alignas, they must both match
  2475. // every definition, and so must match each other if there is a definition.)
  2476. // If either declaration only contains 'alignas(0)' specifiers, then it
  2477. // specifies the natural alignment for the type.
  2478. if (OldAlign == 0 || NewAlign == 0) {
  2479. QualType Ty;
  2480. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2481. Ty = VD->getType();
  2482. else
  2483. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2484. if (OldAlign == 0)
  2485. OldAlign = S.Context.getTypeAlign(Ty);
  2486. if (NewAlign == 0)
  2487. NewAlign = S.Context.getTypeAlign(Ty);
  2488. }
  2489. if (OldAlign != NewAlign) {
  2490. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2491. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2492. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2493. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2494. }
  2495. }
  2496. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2497. // C++11 [dcl.align]p6:
  2498. // if any declaration of an entity has an alignment-specifier,
  2499. // every defining declaration of that entity shall specify an
  2500. // equivalent alignment.
  2501. // C11 6.7.5/7:
  2502. // If the definition of an object does not have an alignment
  2503. // specifier, any other declaration of that object shall also
  2504. // have no alignment specifier.
  2505. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2506. << OldAlignasAttr;
  2507. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2508. << OldAlignasAttr;
  2509. }
  2510. bool AnyAdded = false;
  2511. // Ensure we have an attribute representing the strictest alignment.
  2512. if (OldAlign > NewAlign) {
  2513. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2514. Clone->setInherited(true);
  2515. New->addAttr(Clone);
  2516. AnyAdded = true;
  2517. }
  2518. // Ensure we have an alignas attribute if the old declaration had one.
  2519. if (OldAlignasAttr && !NewAlignasAttr &&
  2520. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2521. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2522. Clone->setInherited(true);
  2523. New->addAttr(Clone);
  2524. AnyAdded = true;
  2525. }
  2526. return AnyAdded;
  2527. }
  2528. #define WANT_DECL_MERGE_LOGIC
  2529. #include "clang/Sema/AttrParsedAttrImpl.inc"
  2530. #undef WANT_DECL_MERGE_LOGIC
  2531. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2532. const InheritableAttr *Attr,
  2533. Sema::AvailabilityMergeKind AMK) {
  2534. // Diagnose any mutual exclusions between the attribute that we want to add
  2535. // and attributes that already exist on the declaration.
  2536. if (!DiagnoseMutualExclusions(S, D, Attr))
  2537. return false;
  2538. // This function copies an attribute Attr from a previous declaration to the
  2539. // new declaration D if the new declaration doesn't itself have that attribute
  2540. // yet or if that attribute allows duplicates.
  2541. // If you're adding a new attribute that requires logic different from
  2542. // "use explicit attribute on decl if present, else use attribute from
  2543. // previous decl", for example if the attribute needs to be consistent
  2544. // between redeclarations, you need to call a custom merge function here.
  2545. InheritableAttr *NewAttr = nullptr;
  2546. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2547. NewAttr = S.mergeAvailabilityAttr(
  2548. D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
  2549. AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
  2550. AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
  2551. AA->getPriority());
  2552. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2553. NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
  2554. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2555. NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
  2556. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2557. NewAttr = S.mergeDLLImportAttr(D, *ImportA);
  2558. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2559. NewAttr = S.mergeDLLExportAttr(D, *ExportA);
  2560. else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
  2561. NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
  2562. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2563. NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
  2564. FA->getFirstArg());
  2565. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2566. NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
  2567. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2568. NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
  2569. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2570. NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
  2571. IA->getInheritanceModel());
  2572. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2573. NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
  2574. &S.Context.Idents.get(AA->getSpelling()));
  2575. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2576. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2577. isa<CUDAGlobalAttr>(Attr))) {
  2578. // CUDA target attributes are part of function signature for
  2579. // overloading purposes and must not be merged.
  2580. return false;
  2581. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2582. NewAttr = S.mergeMinSizeAttr(D, *MA);
  2583. else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
  2584. NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
  2585. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2586. NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
  2587. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2588. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2589. else if (isa<AlignedAttr>(Attr))
  2590. // AlignedAttrs are handled separately, because we need to handle all
  2591. // such attributes on a declaration at the same time.
  2592. NewAttr = nullptr;
  2593. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2594. (AMK == Sema::AMK_Override ||
  2595. AMK == Sema::AMK_ProtocolImplementation ||
  2596. AMK == Sema::AMK_OptionalProtocolImplementation))
  2597. NewAttr = nullptr;
  2598. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2599. NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
  2600. else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
  2601. NewAttr = S.mergeImportModuleAttr(D, *IMA);
  2602. else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
  2603. NewAttr = S.mergeImportNameAttr(D, *INA);
  2604. else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
  2605. NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
  2606. else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
  2607. NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
  2608. else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
  2609. NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
  2610. else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr))
  2611. NewAttr =
  2612. S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ());
  2613. else if (const auto *SA = dyn_cast<HLSLShaderAttr>(Attr))
  2614. NewAttr = S.mergeHLSLShaderAttr(D, *SA, SA->getType());
  2615. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2616. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2617. if (NewAttr) {
  2618. NewAttr->setInherited(true);
  2619. D->addAttr(NewAttr);
  2620. if (isa<MSInheritanceAttr>(NewAttr))
  2621. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2622. return true;
  2623. }
  2624. return false;
  2625. }
  2626. static const NamedDecl *getDefinition(const Decl *D) {
  2627. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2628. return TD->getDefinition();
  2629. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2630. const VarDecl *Def = VD->getDefinition();
  2631. if (Def)
  2632. return Def;
  2633. return VD->getActingDefinition();
  2634. }
  2635. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2636. const FunctionDecl *Def = nullptr;
  2637. if (FD->isDefined(Def, true))
  2638. return Def;
  2639. }
  2640. return nullptr;
  2641. }
  2642. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2643. for (const auto *Attribute : D->attrs())
  2644. if (Attribute->getKind() == Kind)
  2645. return true;
  2646. return false;
  2647. }
  2648. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2649. /// there are no new attributes in this declaration.
  2650. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2651. if (!New->hasAttrs())
  2652. return;
  2653. const NamedDecl *Def = getDefinition(Old);
  2654. if (!Def || Def == New)
  2655. return;
  2656. AttrVec &NewAttributes = New->getAttrs();
  2657. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2658. const Attr *NewAttribute = NewAttributes[I];
  2659. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2660. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2661. Sema::SkipBodyInfo SkipBody;
  2662. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2663. // If we're skipping this definition, drop the "alias" attribute.
  2664. if (SkipBody.ShouldSkip) {
  2665. NewAttributes.erase(NewAttributes.begin() + I);
  2666. --E;
  2667. continue;
  2668. }
  2669. } else {
  2670. VarDecl *VD = cast<VarDecl>(New);
  2671. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2672. VarDecl::TentativeDefinition
  2673. ? diag::err_alias_after_tentative
  2674. : diag::err_redefinition;
  2675. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2676. if (Diag == diag::err_redefinition)
  2677. S.notePreviousDefinition(Def, VD->getLocation());
  2678. else
  2679. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2680. VD->setInvalidDecl();
  2681. }
  2682. ++I;
  2683. continue;
  2684. }
  2685. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2686. // Tentative definitions are only interesting for the alias check above.
  2687. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2688. ++I;
  2689. continue;
  2690. }
  2691. }
  2692. if (hasAttribute(Def, NewAttribute->getKind())) {
  2693. ++I;
  2694. continue; // regular attr merging will take care of validating this.
  2695. }
  2696. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2697. // C's _Noreturn is allowed to be added to a function after it is defined.
  2698. ++I;
  2699. continue;
  2700. } else if (isa<UuidAttr>(NewAttribute)) {
  2701. // msvc will allow a subsequent definition to add an uuid to a class
  2702. ++I;
  2703. continue;
  2704. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2705. if (AA->isAlignas()) {
  2706. // C++11 [dcl.align]p6:
  2707. // if any declaration of an entity has an alignment-specifier,
  2708. // every defining declaration of that entity shall specify an
  2709. // equivalent alignment.
  2710. // C11 6.7.5/7:
  2711. // If the definition of an object does not have an alignment
  2712. // specifier, any other declaration of that object shall also
  2713. // have no alignment specifier.
  2714. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2715. << AA;
  2716. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2717. << AA;
  2718. NewAttributes.erase(NewAttributes.begin() + I);
  2719. --E;
  2720. continue;
  2721. }
  2722. } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
  2723. // If there is a C definition followed by a redeclaration with this
  2724. // attribute then there are two different definitions. In C++, prefer the
  2725. // standard diagnostics.
  2726. if (!S.getLangOpts().CPlusPlus) {
  2727. S.Diag(NewAttribute->getLocation(),
  2728. diag::err_loader_uninitialized_redeclaration);
  2729. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2730. NewAttributes.erase(NewAttributes.begin() + I);
  2731. --E;
  2732. continue;
  2733. }
  2734. } else if (isa<SelectAnyAttr>(NewAttribute) &&
  2735. cast<VarDecl>(New)->isInline() &&
  2736. !cast<VarDecl>(New)->isInlineSpecified()) {
  2737. // Don't warn about applying selectany to implicitly inline variables.
  2738. // Older compilers and language modes would require the use of selectany
  2739. // to make such variables inline, and it would have no effect if we
  2740. // honored it.
  2741. ++I;
  2742. continue;
  2743. } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
  2744. // We allow to add OMP[Begin]DeclareVariantAttr to be added to
  2745. // declarations after definitions.
  2746. ++I;
  2747. continue;
  2748. }
  2749. S.Diag(NewAttribute->getLocation(),
  2750. diag::warn_attribute_precede_definition);
  2751. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2752. NewAttributes.erase(NewAttributes.begin() + I);
  2753. --E;
  2754. }
  2755. }
  2756. static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
  2757. const ConstInitAttr *CIAttr,
  2758. bool AttrBeforeInit) {
  2759. SourceLocation InsertLoc = InitDecl->getInnerLocStart();
  2760. // Figure out a good way to write this specifier on the old declaration.
  2761. // FIXME: We should just use the spelling of CIAttr, but we don't preserve
  2762. // enough of the attribute list spelling information to extract that without
  2763. // heroics.
  2764. std::string SuitableSpelling;
  2765. if (S.getLangOpts().CPlusPlus20)
  2766. SuitableSpelling = std::string(
  2767. S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
  2768. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2769. SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
  2770. InsertLoc, {tok::l_square, tok::l_square,
  2771. S.PP.getIdentifierInfo("clang"), tok::coloncolon,
  2772. S.PP.getIdentifierInfo("require_constant_initialization"),
  2773. tok::r_square, tok::r_square}));
  2774. if (SuitableSpelling.empty())
  2775. SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
  2776. InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
  2777. S.PP.getIdentifierInfo("require_constant_initialization"),
  2778. tok::r_paren, tok::r_paren}));
  2779. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
  2780. SuitableSpelling = "constinit";
  2781. if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
  2782. SuitableSpelling = "[[clang::require_constant_initialization]]";
  2783. if (SuitableSpelling.empty())
  2784. SuitableSpelling = "__attribute__((require_constant_initialization))";
  2785. SuitableSpelling += " ";
  2786. if (AttrBeforeInit) {
  2787. // extern constinit int a;
  2788. // int a = 0; // error (missing 'constinit'), accepted as extension
  2789. assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
  2790. S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
  2791. << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2792. S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
  2793. } else {
  2794. // int a = 0;
  2795. // constinit extern int a; // error (missing 'constinit')
  2796. S.Diag(CIAttr->getLocation(),
  2797. CIAttr->isConstinit() ? diag::err_constinit_added_too_late
  2798. : diag::warn_require_const_init_added_too_late)
  2799. << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
  2800. S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
  2801. << CIAttr->isConstinit()
  2802. << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
  2803. }
  2804. }
  2805. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2806. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2807. AvailabilityMergeKind AMK) {
  2808. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2809. UsedAttr *NewAttr = OldAttr->clone(Context);
  2810. NewAttr->setInherited(true);
  2811. New->addAttr(NewAttr);
  2812. }
  2813. if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
  2814. RetainAttr *NewAttr = OldAttr->clone(Context);
  2815. NewAttr->setInherited(true);
  2816. New->addAttr(NewAttr);
  2817. }
  2818. if (!Old->hasAttrs() && !New->hasAttrs())
  2819. return;
  2820. // [dcl.constinit]p1:
  2821. // If the [constinit] specifier is applied to any declaration of a
  2822. // variable, it shall be applied to the initializing declaration.
  2823. const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
  2824. const auto *NewConstInit = New->getAttr<ConstInitAttr>();
  2825. if (bool(OldConstInit) != bool(NewConstInit)) {
  2826. const auto *OldVD = cast<VarDecl>(Old);
  2827. auto *NewVD = cast<VarDecl>(New);
  2828. // Find the initializing declaration. Note that we might not have linked
  2829. // the new declaration into the redeclaration chain yet.
  2830. const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
  2831. if (!InitDecl &&
  2832. (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
  2833. InitDecl = NewVD;
  2834. if (InitDecl == NewVD) {
  2835. // This is the initializing declaration. If it would inherit 'constinit',
  2836. // that's ill-formed. (Note that we do not apply this to the attribute
  2837. // form).
  2838. if (OldConstInit && OldConstInit->isConstinit())
  2839. diagnoseMissingConstinit(*this, NewVD, OldConstInit,
  2840. /*AttrBeforeInit=*/true);
  2841. } else if (NewConstInit) {
  2842. // This is the first time we've been told that this declaration should
  2843. // have a constant initializer. If we already saw the initializing
  2844. // declaration, this is too late.
  2845. if (InitDecl && InitDecl != NewVD) {
  2846. diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
  2847. /*AttrBeforeInit=*/false);
  2848. NewVD->dropAttr<ConstInitAttr>();
  2849. }
  2850. }
  2851. }
  2852. // Attributes declared post-definition are currently ignored.
  2853. checkNewAttributesAfterDef(*this, New, Old);
  2854. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2855. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2856. if (!OldA->isEquivalent(NewA)) {
  2857. // This redeclaration changes __asm__ label.
  2858. Diag(New->getLocation(), diag::err_different_asm_label);
  2859. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2860. }
  2861. } else if (Old->isUsed()) {
  2862. // This redeclaration adds an __asm__ label to a declaration that has
  2863. // already been ODR-used.
  2864. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2865. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2866. }
  2867. }
  2868. // Re-declaration cannot add abi_tag's.
  2869. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2870. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2871. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2872. if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
  2873. Diag(NewAbiTagAttr->getLocation(),
  2874. diag::err_new_abi_tag_on_redeclaration)
  2875. << NewTag;
  2876. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2877. }
  2878. }
  2879. } else {
  2880. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2881. Diag(Old->getLocation(), diag::note_previous_declaration);
  2882. }
  2883. }
  2884. // This redeclaration adds a section attribute.
  2885. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2886. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2887. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2888. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2889. Diag(Old->getLocation(), diag::note_previous_declaration);
  2890. }
  2891. }
  2892. }
  2893. // Redeclaration adds code-seg attribute.
  2894. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2895. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2896. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2897. Diag(New->getLocation(), diag::warn_mismatched_section)
  2898. << 0 /*codeseg*/;
  2899. Diag(Old->getLocation(), diag::note_previous_declaration);
  2900. }
  2901. if (!Old->hasAttrs())
  2902. return;
  2903. bool foundAny = New->hasAttrs();
  2904. // Ensure that any moving of objects within the allocated map is done before
  2905. // we process them.
  2906. if (!foundAny) New->setAttrs(AttrVec());
  2907. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2908. // Ignore deprecated/unavailable/availability attributes if requested.
  2909. AvailabilityMergeKind LocalAMK = AMK_None;
  2910. if (isa<DeprecatedAttr>(I) ||
  2911. isa<UnavailableAttr>(I) ||
  2912. isa<AvailabilityAttr>(I)) {
  2913. switch (AMK) {
  2914. case AMK_None:
  2915. continue;
  2916. case AMK_Redeclaration:
  2917. case AMK_Override:
  2918. case AMK_ProtocolImplementation:
  2919. case AMK_OptionalProtocolImplementation:
  2920. LocalAMK = AMK;
  2921. break;
  2922. }
  2923. }
  2924. // Already handled.
  2925. if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
  2926. continue;
  2927. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2928. foundAny = true;
  2929. }
  2930. if (mergeAlignedAttrs(*this, New, Old))
  2931. foundAny = true;
  2932. if (!foundAny) New->dropAttrs();
  2933. }
  2934. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2935. /// to the new one.
  2936. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2937. const ParmVarDecl *oldDecl,
  2938. Sema &S) {
  2939. // C++11 [dcl.attr.depend]p2:
  2940. // The first declaration of a function shall specify the
  2941. // carries_dependency attribute for its declarator-id if any declaration
  2942. // of the function specifies the carries_dependency attribute.
  2943. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2944. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2945. S.Diag(CDA->getLocation(),
  2946. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2947. // Find the first declaration of the parameter.
  2948. // FIXME: Should we build redeclaration chains for function parameters?
  2949. const FunctionDecl *FirstFD =
  2950. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2951. const ParmVarDecl *FirstVD =
  2952. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2953. S.Diag(FirstVD->getLocation(),
  2954. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2955. }
  2956. if (!oldDecl->hasAttrs())
  2957. return;
  2958. bool foundAny = newDecl->hasAttrs();
  2959. // Ensure that any moving of objects within the allocated map is
  2960. // done before we process them.
  2961. if (!foundAny) newDecl->setAttrs(AttrVec());
  2962. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2963. if (!DeclHasAttr(newDecl, I)) {
  2964. InheritableAttr *newAttr =
  2965. cast<InheritableParamAttr>(I->clone(S.Context));
  2966. newAttr->setInherited(true);
  2967. newDecl->addAttr(newAttr);
  2968. foundAny = true;
  2969. }
  2970. }
  2971. if (!foundAny) newDecl->dropAttrs();
  2972. }
  2973. static bool EquivalentArrayTypes(QualType Old, QualType New,
  2974. const ASTContext &Ctx) {
  2975. auto NoSizeInfo = [&Ctx](QualType Ty) {
  2976. if (Ty->isIncompleteArrayType() || Ty->isPointerType())
  2977. return true;
  2978. if (const auto *VAT = Ctx.getAsVariableArrayType(Ty))
  2979. return VAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star;
  2980. return false;
  2981. };
  2982. // `type[]` is equivalent to `type *` and `type[*]`.
  2983. if (NoSizeInfo(Old) && NoSizeInfo(New))
  2984. return true;
  2985. // Don't try to compare VLA sizes, unless one of them has the star modifier.
  2986. if (Old->isVariableArrayType() && New->isVariableArrayType()) {
  2987. const auto *OldVAT = Ctx.getAsVariableArrayType(Old);
  2988. const auto *NewVAT = Ctx.getAsVariableArrayType(New);
  2989. if ((OldVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star) ^
  2990. (NewVAT->getSizeModifier() == ArrayType::ArraySizeModifier::Star))
  2991. return false;
  2992. return true;
  2993. }
  2994. // Only compare size, ignore Size modifiers and CVR.
  2995. if (Old->isConstantArrayType() && New->isConstantArrayType()) {
  2996. return Ctx.getAsConstantArrayType(Old)->getSize() ==
  2997. Ctx.getAsConstantArrayType(New)->getSize();
  2998. }
  2999. // Don't try to compare dependent sized array
  3000. if (Old->isDependentSizedArrayType() && New->isDependentSizedArrayType()) {
  3001. return true;
  3002. }
  3003. return Old == New;
  3004. }
  3005. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  3006. const ParmVarDecl *OldParam,
  3007. Sema &S) {
  3008. if (auto Oldnullability = OldParam->getType()->getNullability()) {
  3009. if (auto Newnullability = NewParam->getType()->getNullability()) {
  3010. if (*Oldnullability != *Newnullability) {
  3011. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  3012. << DiagNullabilityKind(
  3013. *Newnullability,
  3014. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  3015. != 0))
  3016. << DiagNullabilityKind(
  3017. *Oldnullability,
  3018. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  3019. != 0));
  3020. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  3021. }
  3022. } else {
  3023. QualType NewT = NewParam->getType();
  3024. NewT = S.Context.getAttributedType(
  3025. AttributedType::getNullabilityAttrKind(*Oldnullability),
  3026. NewT, NewT);
  3027. NewParam->setType(NewT);
  3028. }
  3029. }
  3030. const auto *OldParamDT = dyn_cast<DecayedType>(OldParam->getType());
  3031. const auto *NewParamDT = dyn_cast<DecayedType>(NewParam->getType());
  3032. if (OldParamDT && NewParamDT &&
  3033. OldParamDT->getPointeeType() == NewParamDT->getPointeeType()) {
  3034. QualType OldParamOT = OldParamDT->getOriginalType();
  3035. QualType NewParamOT = NewParamDT->getOriginalType();
  3036. if (!EquivalentArrayTypes(OldParamOT, NewParamOT, S.getASTContext())) {
  3037. S.Diag(NewParam->getLocation(), diag::warn_inconsistent_array_form)
  3038. << NewParam << NewParamOT;
  3039. S.Diag(OldParam->getLocation(), diag::note_previous_declaration_as)
  3040. << OldParamOT;
  3041. }
  3042. }
  3043. }
  3044. namespace {
  3045. /// Used in MergeFunctionDecl to keep track of function parameters in
  3046. /// C.
  3047. struct GNUCompatibleParamWarning {
  3048. ParmVarDecl *OldParm;
  3049. ParmVarDecl *NewParm;
  3050. QualType PromotedType;
  3051. };
  3052. } // end anonymous namespace
  3053. // Determine whether the previous declaration was a definition, implicit
  3054. // declaration, or a declaration.
  3055. template <typename T>
  3056. static std::pair<diag::kind, SourceLocation>
  3057. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  3058. diag::kind PrevDiag;
  3059. SourceLocation OldLocation = Old->getLocation();
  3060. if (Old->isThisDeclarationADefinition())
  3061. PrevDiag = diag::note_previous_definition;
  3062. else if (Old->isImplicit()) {
  3063. PrevDiag = diag::note_previous_implicit_declaration;
  3064. if (const auto *FD = dyn_cast<FunctionDecl>(Old)) {
  3065. if (FD->getBuiltinID())
  3066. PrevDiag = diag::note_previous_builtin_declaration;
  3067. }
  3068. if (OldLocation.isInvalid())
  3069. OldLocation = New->getLocation();
  3070. } else
  3071. PrevDiag = diag::note_previous_declaration;
  3072. return std::make_pair(PrevDiag, OldLocation);
  3073. }
  3074. /// canRedefineFunction - checks if a function can be redefined. Currently,
  3075. /// only extern inline functions can be redefined, and even then only in
  3076. /// GNU89 mode.
  3077. static bool canRedefineFunction(const FunctionDecl *FD,
  3078. const LangOptions& LangOpts) {
  3079. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  3080. !LangOpts.CPlusPlus &&
  3081. FD->isInlineSpecified() &&
  3082. FD->getStorageClass() == SC_Extern);
  3083. }
  3084. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  3085. const AttributedType *AT = T->getAs<AttributedType>();
  3086. while (AT && !AT->isCallingConv())
  3087. AT = AT->getModifiedType()->getAs<AttributedType>();
  3088. return AT;
  3089. }
  3090. template <typename T>
  3091. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  3092. const DeclContext *DC = Old->getDeclContext();
  3093. if (DC->isRecord())
  3094. return false;
  3095. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  3096. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  3097. return true;
  3098. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  3099. return true;
  3100. return false;
  3101. }
  3102. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  3103. static bool isExternC(VarTemplateDecl *) { return false; }
  3104. static bool isExternC(FunctionTemplateDecl *) { return false; }
  3105. /// Check whether a redeclaration of an entity introduced by a
  3106. /// using-declaration is valid, given that we know it's not an overload
  3107. /// (nor a hidden tag declaration).
  3108. template<typename ExpectedDecl>
  3109. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  3110. ExpectedDecl *New) {
  3111. // C++11 [basic.scope.declarative]p4:
  3112. // Given a set of declarations in a single declarative region, each of
  3113. // which specifies the same unqualified name,
  3114. // -- they shall all refer to the same entity, or all refer to functions
  3115. // and function templates; or
  3116. // -- exactly one declaration shall declare a class name or enumeration
  3117. // name that is not a typedef name and the other declarations shall all
  3118. // refer to the same variable or enumerator, or all refer to functions
  3119. // and function templates; in this case the class name or enumeration
  3120. // name is hidden (3.3.10).
  3121. // C++11 [namespace.udecl]p14:
  3122. // If a function declaration in namespace scope or block scope has the
  3123. // same name and the same parameter-type-list as a function introduced
  3124. // by a using-declaration, and the declarations do not declare the same
  3125. // function, the program is ill-formed.
  3126. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  3127. if (Old &&
  3128. !Old->getDeclContext()->getRedeclContext()->Equals(
  3129. New->getDeclContext()->getRedeclContext()) &&
  3130. !(isExternC(Old) && isExternC(New)))
  3131. Old = nullptr;
  3132. if (!Old) {
  3133. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  3134. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  3135. S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
  3136. return true;
  3137. }
  3138. return false;
  3139. }
  3140. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  3141. const FunctionDecl *B) {
  3142. assert(A->getNumParams() == B->getNumParams());
  3143. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  3144. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  3145. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  3146. if (AttrA == AttrB)
  3147. return true;
  3148. return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
  3149. AttrA->isDynamic() == AttrB->isDynamic();
  3150. };
  3151. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  3152. }
  3153. /// If necessary, adjust the semantic declaration context for a qualified
  3154. /// declaration to name the correct inline namespace within the qualifier.
  3155. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  3156. DeclaratorDecl *OldD) {
  3157. // The only case where we need to update the DeclContext is when
  3158. // redeclaration lookup for a qualified name finds a declaration
  3159. // in an inline namespace within the context named by the qualifier:
  3160. //
  3161. // inline namespace N { int f(); }
  3162. // int ::f(); // Sema DC needs adjusting from :: to N::.
  3163. //
  3164. // For unqualified declarations, the semantic context *can* change
  3165. // along the redeclaration chain (for local extern declarations,
  3166. // extern "C" declarations, and friend declarations in particular).
  3167. if (!NewD->getQualifier())
  3168. return;
  3169. // NewD is probably already in the right context.
  3170. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  3171. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  3172. if (NamedDC->Equals(SemaDC))
  3173. return;
  3174. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  3175. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  3176. "unexpected context for redeclaration");
  3177. auto *LexDC = NewD->getLexicalDeclContext();
  3178. auto FixSemaDC = [=](NamedDecl *D) {
  3179. if (!D)
  3180. return;
  3181. D->setDeclContext(SemaDC);
  3182. D->setLexicalDeclContext(LexDC);
  3183. };
  3184. FixSemaDC(NewD);
  3185. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  3186. FixSemaDC(FD->getDescribedFunctionTemplate());
  3187. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  3188. FixSemaDC(VD->getDescribedVarTemplate());
  3189. }
  3190. /// MergeFunctionDecl - We just parsed a function 'New' from
  3191. /// declarator D which has the same name and scope as a previous
  3192. /// declaration 'Old'. Figure out how to resolve this situation,
  3193. /// merging decls or emitting diagnostics as appropriate.
  3194. ///
  3195. /// In C++, New and Old must be declarations that are not
  3196. /// overloaded. Use IsOverload to determine whether New and Old are
  3197. /// overloaded, and to select the Old declaration that New should be
  3198. /// merged with.
  3199. ///
  3200. /// Returns true if there was an error, false otherwise.
  3201. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S,
  3202. bool MergeTypeWithOld, bool NewDeclIsDefn) {
  3203. // Verify the old decl was also a function.
  3204. FunctionDecl *Old = OldD->getAsFunction();
  3205. if (!Old) {
  3206. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  3207. if (New->getFriendObjectKind()) {
  3208. Diag(New->getLocation(), diag::err_using_decl_friend);
  3209. Diag(Shadow->getTargetDecl()->getLocation(),
  3210. diag::note_using_decl_target);
  3211. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
  3212. << 0;
  3213. return true;
  3214. }
  3215. // Check whether the two declarations might declare the same function or
  3216. // function template.
  3217. if (FunctionTemplateDecl *NewTemplate =
  3218. New->getDescribedFunctionTemplate()) {
  3219. if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
  3220. NewTemplate))
  3221. return true;
  3222. OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
  3223. ->getAsFunction();
  3224. } else {
  3225. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  3226. return true;
  3227. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  3228. }
  3229. } else {
  3230. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3231. << New->getDeclName();
  3232. notePreviousDefinition(OldD, New->getLocation());
  3233. return true;
  3234. }
  3235. }
  3236. // If the old declaration was found in an inline namespace and the new
  3237. // declaration was qualified, update the DeclContext to match.
  3238. adjustDeclContextForDeclaratorDecl(New, Old);
  3239. // If the old declaration is invalid, just give up here.
  3240. if (Old->isInvalidDecl())
  3241. return true;
  3242. // Disallow redeclaration of some builtins.
  3243. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  3244. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  3245. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  3246. << Old << Old->getType();
  3247. return true;
  3248. }
  3249. diag::kind PrevDiag;
  3250. SourceLocation OldLocation;
  3251. std::tie(PrevDiag, OldLocation) =
  3252. getNoteDiagForInvalidRedeclaration(Old, New);
  3253. // Don't complain about this if we're in GNU89 mode and the old function
  3254. // is an extern inline function.
  3255. // Don't complain about specializations. They are not supposed to have
  3256. // storage classes.
  3257. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  3258. New->getStorageClass() == SC_Static &&
  3259. Old->hasExternalFormalLinkage() &&
  3260. !New->getTemplateSpecializationInfo() &&
  3261. !canRedefineFunction(Old, getLangOpts())) {
  3262. if (getLangOpts().MicrosoftExt) {
  3263. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  3264. Diag(OldLocation, PrevDiag);
  3265. } else {
  3266. Diag(New->getLocation(), diag::err_static_non_static) << New;
  3267. Diag(OldLocation, PrevDiag);
  3268. return true;
  3269. }
  3270. }
  3271. if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
  3272. if (!Old->hasAttr<InternalLinkageAttr>()) {
  3273. Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
  3274. << ILA;
  3275. Diag(Old->getLocation(), diag::note_previous_declaration);
  3276. New->dropAttr<InternalLinkageAttr>();
  3277. }
  3278. if (auto *EA = New->getAttr<ErrorAttr>()) {
  3279. if (!Old->hasAttr<ErrorAttr>()) {
  3280. Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
  3281. Diag(Old->getLocation(), diag::note_previous_declaration);
  3282. New->dropAttr<ErrorAttr>();
  3283. }
  3284. }
  3285. if (CheckRedeclarationInModule(New, Old))
  3286. return true;
  3287. if (!getLangOpts().CPlusPlus) {
  3288. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  3289. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  3290. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  3291. << New << OldOvl;
  3292. // Try our best to find a decl that actually has the overloadable
  3293. // attribute for the note. In most cases (e.g. programs with only one
  3294. // broken declaration/definition), this won't matter.
  3295. //
  3296. // FIXME: We could do this if we juggled some extra state in
  3297. // OverloadableAttr, rather than just removing it.
  3298. const Decl *DiagOld = Old;
  3299. if (OldOvl) {
  3300. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  3301. const auto *A = D->getAttr<OverloadableAttr>();
  3302. return A && !A->isImplicit();
  3303. });
  3304. // If we've implicitly added *all* of the overloadable attrs to this
  3305. // chain, emitting a "previous redecl" note is pointless.
  3306. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  3307. }
  3308. if (DiagOld)
  3309. Diag(DiagOld->getLocation(),
  3310. diag::note_attribute_overloadable_prev_overload)
  3311. << OldOvl;
  3312. if (OldOvl)
  3313. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  3314. else
  3315. New->dropAttr<OverloadableAttr>();
  3316. }
  3317. }
  3318. // If a function is first declared with a calling convention, but is later
  3319. // declared or defined without one, all following decls assume the calling
  3320. // convention of the first.
  3321. //
  3322. // It's OK if a function is first declared without a calling convention,
  3323. // but is later declared or defined with the default calling convention.
  3324. //
  3325. // To test if either decl has an explicit calling convention, we look for
  3326. // AttributedType sugar nodes on the type as written. If they are missing or
  3327. // were canonicalized away, we assume the calling convention was implicit.
  3328. //
  3329. // Note also that we DO NOT return at this point, because we still have
  3330. // other tests to run.
  3331. QualType OldQType = Context.getCanonicalType(Old->getType());
  3332. QualType NewQType = Context.getCanonicalType(New->getType());
  3333. const FunctionType *OldType = cast<FunctionType>(OldQType);
  3334. const FunctionType *NewType = cast<FunctionType>(NewQType);
  3335. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  3336. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  3337. bool RequiresAdjustment = false;
  3338. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  3339. FunctionDecl *First = Old->getFirstDecl();
  3340. const FunctionType *FT =
  3341. First->getType().getCanonicalType()->castAs<FunctionType>();
  3342. FunctionType::ExtInfo FI = FT->getExtInfo();
  3343. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  3344. if (!NewCCExplicit) {
  3345. // Inherit the CC from the previous declaration if it was specified
  3346. // there but not here.
  3347. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  3348. RequiresAdjustment = true;
  3349. } else if (Old->getBuiltinID()) {
  3350. // Builtin attribute isn't propagated to the new one yet at this point,
  3351. // so we check if the old one is a builtin.
  3352. // Calling Conventions on a Builtin aren't really useful and setting a
  3353. // default calling convention and cdecl'ing some builtin redeclarations is
  3354. // common, so warn and ignore the calling convention on the redeclaration.
  3355. Diag(New->getLocation(), diag::warn_cconv_unsupported)
  3356. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  3357. << (int)CallingConventionIgnoredReason::BuiltinFunction;
  3358. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  3359. RequiresAdjustment = true;
  3360. } else {
  3361. // Calling conventions aren't compatible, so complain.
  3362. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  3363. Diag(New->getLocation(), diag::err_cconv_change)
  3364. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  3365. << !FirstCCExplicit
  3366. << (!FirstCCExplicit ? "" :
  3367. FunctionType::getNameForCallConv(FI.getCC()));
  3368. // Put the note on the first decl, since it is the one that matters.
  3369. Diag(First->getLocation(), diag::note_previous_declaration);
  3370. return true;
  3371. }
  3372. }
  3373. // FIXME: diagnose the other way around?
  3374. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  3375. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  3376. RequiresAdjustment = true;
  3377. }
  3378. // Merge regparm attribute.
  3379. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  3380. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  3381. if (NewTypeInfo.getHasRegParm()) {
  3382. Diag(New->getLocation(), diag::err_regparm_mismatch)
  3383. << NewType->getRegParmType()
  3384. << OldType->getRegParmType();
  3385. Diag(OldLocation, diag::note_previous_declaration);
  3386. return true;
  3387. }
  3388. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  3389. RequiresAdjustment = true;
  3390. }
  3391. // Merge ns_returns_retained attribute.
  3392. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  3393. if (NewTypeInfo.getProducesResult()) {
  3394. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  3395. << "'ns_returns_retained'";
  3396. Diag(OldLocation, diag::note_previous_declaration);
  3397. return true;
  3398. }
  3399. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  3400. RequiresAdjustment = true;
  3401. }
  3402. if (OldTypeInfo.getNoCallerSavedRegs() !=
  3403. NewTypeInfo.getNoCallerSavedRegs()) {
  3404. if (NewTypeInfo.getNoCallerSavedRegs()) {
  3405. AnyX86NoCallerSavedRegistersAttr *Attr =
  3406. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  3407. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  3408. Diag(OldLocation, diag::note_previous_declaration);
  3409. return true;
  3410. }
  3411. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  3412. RequiresAdjustment = true;
  3413. }
  3414. if (RequiresAdjustment) {
  3415. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  3416. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  3417. New->setType(QualType(AdjustedType, 0));
  3418. NewQType = Context.getCanonicalType(New->getType());
  3419. }
  3420. // If this redeclaration makes the function inline, we may need to add it to
  3421. // UndefinedButUsed.
  3422. if (!Old->isInlined() && New->isInlined() &&
  3423. !New->hasAttr<GNUInlineAttr>() &&
  3424. !getLangOpts().GNUInline &&
  3425. Old->isUsed(false) &&
  3426. !Old->isDefined() && !New->isThisDeclarationADefinition())
  3427. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3428. SourceLocation()));
  3429. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  3430. // about it.
  3431. if (New->hasAttr<GNUInlineAttr>() &&
  3432. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  3433. UndefinedButUsed.erase(Old->getCanonicalDecl());
  3434. }
  3435. // If pass_object_size params don't match up perfectly, this isn't a valid
  3436. // redeclaration.
  3437. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  3438. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  3439. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  3440. << New->getDeclName();
  3441. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3442. return true;
  3443. }
  3444. if (getLangOpts().CPlusPlus) {
  3445. // C++1z [over.load]p2
  3446. // Certain function declarations cannot be overloaded:
  3447. // -- Function declarations that differ only in the return type,
  3448. // the exception specification, or both cannot be overloaded.
  3449. // Check the exception specifications match. This may recompute the type of
  3450. // both Old and New if it resolved exception specifications, so grab the
  3451. // types again after this. Because this updates the type, we do this before
  3452. // any of the other checks below, which may update the "de facto" NewQType
  3453. // but do not necessarily update the type of New.
  3454. if (CheckEquivalentExceptionSpec(Old, New))
  3455. return true;
  3456. OldQType = Context.getCanonicalType(Old->getType());
  3457. NewQType = Context.getCanonicalType(New->getType());
  3458. // Go back to the type source info to compare the declared return types,
  3459. // per C++1y [dcl.type.auto]p13:
  3460. // Redeclarations or specializations of a function or function template
  3461. // with a declared return type that uses a placeholder type shall also
  3462. // use that placeholder, not a deduced type.
  3463. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  3464. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  3465. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  3466. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  3467. OldDeclaredReturnType)) {
  3468. QualType ResQT;
  3469. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  3470. OldDeclaredReturnType->isObjCObjectPointerType())
  3471. // FIXME: This does the wrong thing for a deduced return type.
  3472. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  3473. if (ResQT.isNull()) {
  3474. if (New->isCXXClassMember() && New->isOutOfLine())
  3475. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  3476. << New << New->getReturnTypeSourceRange();
  3477. else
  3478. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  3479. << New->getReturnTypeSourceRange();
  3480. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  3481. << Old->getReturnTypeSourceRange();
  3482. return true;
  3483. }
  3484. else
  3485. NewQType = ResQT;
  3486. }
  3487. QualType OldReturnType = OldType->getReturnType();
  3488. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  3489. if (OldReturnType != NewReturnType) {
  3490. // If this function has a deduced return type and has already been
  3491. // defined, copy the deduced value from the old declaration.
  3492. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  3493. if (OldAT && OldAT->isDeduced()) {
  3494. QualType DT = OldAT->getDeducedType();
  3495. if (DT.isNull()) {
  3496. New->setType(SubstAutoTypeDependent(New->getType()));
  3497. NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
  3498. } else {
  3499. New->setType(SubstAutoType(New->getType(), DT));
  3500. NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
  3501. }
  3502. }
  3503. }
  3504. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  3505. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  3506. if (OldMethod && NewMethod) {
  3507. // Preserve triviality.
  3508. NewMethod->setTrivial(OldMethod->isTrivial());
  3509. // MSVC allows explicit template specialization at class scope:
  3510. // 2 CXXMethodDecls referring to the same function will be injected.
  3511. // We don't want a redeclaration error.
  3512. bool IsClassScopeExplicitSpecialization =
  3513. OldMethod->isFunctionTemplateSpecialization() &&
  3514. NewMethod->isFunctionTemplateSpecialization();
  3515. bool isFriend = NewMethod->getFriendObjectKind();
  3516. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  3517. !IsClassScopeExplicitSpecialization) {
  3518. // -- Member function declarations with the same name and the
  3519. // same parameter types cannot be overloaded if any of them
  3520. // is a static member function declaration.
  3521. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  3522. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  3523. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3524. return true;
  3525. }
  3526. // C++ [class.mem]p1:
  3527. // [...] A member shall not be declared twice in the
  3528. // member-specification, except that a nested class or member
  3529. // class template can be declared and then later defined.
  3530. if (!inTemplateInstantiation()) {
  3531. unsigned NewDiag;
  3532. if (isa<CXXConstructorDecl>(OldMethod))
  3533. NewDiag = diag::err_constructor_redeclared;
  3534. else if (isa<CXXDestructorDecl>(NewMethod))
  3535. NewDiag = diag::err_destructor_redeclared;
  3536. else if (isa<CXXConversionDecl>(NewMethod))
  3537. NewDiag = diag::err_conv_function_redeclared;
  3538. else
  3539. NewDiag = diag::err_member_redeclared;
  3540. Diag(New->getLocation(), NewDiag);
  3541. } else {
  3542. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  3543. << New << New->getType();
  3544. }
  3545. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3546. return true;
  3547. // Complain if this is an explicit declaration of a special
  3548. // member that was initially declared implicitly.
  3549. //
  3550. // As an exception, it's okay to befriend such methods in order
  3551. // to permit the implicit constructor/destructor/operator calls.
  3552. } else if (OldMethod->isImplicit()) {
  3553. if (isFriend) {
  3554. NewMethod->setImplicit();
  3555. } else {
  3556. Diag(NewMethod->getLocation(),
  3557. diag::err_definition_of_implicitly_declared_member)
  3558. << New << getSpecialMember(OldMethod);
  3559. return true;
  3560. }
  3561. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  3562. Diag(NewMethod->getLocation(),
  3563. diag::err_definition_of_explicitly_defaulted_member)
  3564. << getSpecialMember(OldMethod);
  3565. return true;
  3566. }
  3567. }
  3568. // C++11 [dcl.attr.noreturn]p1:
  3569. // The first declaration of a function shall specify the noreturn
  3570. // attribute if any declaration of that function specifies the noreturn
  3571. // attribute.
  3572. if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
  3573. if (!Old->hasAttr<CXX11NoReturnAttr>()) {
  3574. Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
  3575. << NRA;
  3576. Diag(Old->getLocation(), diag::note_previous_declaration);
  3577. }
  3578. // C++11 [dcl.attr.depend]p2:
  3579. // The first declaration of a function shall specify the
  3580. // carries_dependency attribute for its declarator-id if any declaration
  3581. // of the function specifies the carries_dependency attribute.
  3582. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  3583. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  3584. Diag(CDA->getLocation(),
  3585. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  3586. Diag(Old->getFirstDecl()->getLocation(),
  3587. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  3588. }
  3589. // (C++98 8.3.5p3):
  3590. // All declarations for a function shall agree exactly in both the
  3591. // return type and the parameter-type-list.
  3592. // We also want to respect all the extended bits except noreturn.
  3593. // noreturn should now match unless the old type info didn't have it.
  3594. QualType OldQTypeForComparison = OldQType;
  3595. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3596. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3597. const FunctionType *OldTypeForComparison
  3598. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3599. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3600. assert(OldQTypeForComparison.isCanonical());
  3601. }
  3602. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3603. // As a special case, retain the language linkage from previous
  3604. // declarations of a friend function as an extension.
  3605. //
  3606. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3607. // and is useful because there's otherwise no way to specify language
  3608. // linkage within class scope.
  3609. //
  3610. // Check cautiously as the friend object kind isn't yet complete.
  3611. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3612. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3613. Diag(OldLocation, PrevDiag);
  3614. } else {
  3615. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3616. Diag(OldLocation, PrevDiag);
  3617. return true;
  3618. }
  3619. }
  3620. // If the function types are compatible, merge the declarations. Ignore the
  3621. // exception specifier because it was already checked above in
  3622. // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
  3623. // about incompatible types under -fms-compatibility.
  3624. if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
  3625. NewQType))
  3626. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3627. // If the types are imprecise (due to dependent constructs in friends or
  3628. // local extern declarations), it's OK if they differ. We'll check again
  3629. // during instantiation.
  3630. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3631. return false;
  3632. // Fall through for conflicting redeclarations and redefinitions.
  3633. }
  3634. // C: Function types need to be compatible, not identical. This handles
  3635. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3636. if (!getLangOpts().CPlusPlus) {
  3637. // C99 6.7.5.3p15: ...If one type has a parameter type list and the other
  3638. // type is specified by a function definition that contains a (possibly
  3639. // empty) identifier list, both shall agree in the number of parameters
  3640. // and the type of each parameter shall be compatible with the type that
  3641. // results from the application of default argument promotions to the
  3642. // type of the corresponding identifier. ...
  3643. // This cannot be handled by ASTContext::typesAreCompatible() because that
  3644. // doesn't know whether the function type is for a definition or not when
  3645. // eventually calling ASTContext::mergeFunctionTypes(). The only situation
  3646. // we need to cover here is that the number of arguments agree as the
  3647. // default argument promotion rules were already checked by
  3648. // ASTContext::typesAreCompatible().
  3649. if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn &&
  3650. Old->getNumParams() != New->getNumParams() && !Old->isImplicit()) {
  3651. if (Old->hasInheritedPrototype())
  3652. Old = Old->getCanonicalDecl();
  3653. Diag(New->getLocation(), diag::err_conflicting_types) << New;
  3654. Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
  3655. return true;
  3656. }
  3657. // If we are merging two functions where only one of them has a prototype,
  3658. // we may have enough information to decide to issue a diagnostic that the
  3659. // function without a protoype will change behavior in C2x. This handles
  3660. // cases like:
  3661. // void i(); void i(int j);
  3662. // void i(int j); void i();
  3663. // void i(); void i(int j) {}
  3664. // See ActOnFinishFunctionBody() for other cases of the behavior change
  3665. // diagnostic. See GetFullTypeForDeclarator() for handling of a function
  3666. // type without a prototype.
  3667. if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() &&
  3668. !New->isImplicit() && !Old->isImplicit()) {
  3669. const FunctionDecl *WithProto, *WithoutProto;
  3670. if (New->hasWrittenPrototype()) {
  3671. WithProto = New;
  3672. WithoutProto = Old;
  3673. } else {
  3674. WithProto = Old;
  3675. WithoutProto = New;
  3676. }
  3677. if (WithProto->getNumParams() != 0) {
  3678. if (WithoutProto->getBuiltinID() == 0 && !WithoutProto->isImplicit()) {
  3679. // The one without the prototype will be changing behavior in C2x, so
  3680. // warn about that one so long as it's a user-visible declaration.
  3681. bool IsWithoutProtoADef = false, IsWithProtoADef = false;
  3682. if (WithoutProto == New)
  3683. IsWithoutProtoADef = NewDeclIsDefn;
  3684. else
  3685. IsWithProtoADef = NewDeclIsDefn;
  3686. Diag(WithoutProto->getLocation(),
  3687. diag::warn_non_prototype_changes_behavior)
  3688. << IsWithoutProtoADef << (WithoutProto->getNumParams() ? 0 : 1)
  3689. << (WithoutProto == Old) << IsWithProtoADef;
  3690. // The reason the one without the prototype will be changing behavior
  3691. // is because of the one with the prototype, so note that so long as
  3692. // it's a user-visible declaration. There is one exception to this:
  3693. // when the new declaration is a definition without a prototype, the
  3694. // old declaration with a prototype is not the cause of the issue,
  3695. // and that does not need to be noted because the one with a
  3696. // prototype will not change behavior in C2x.
  3697. if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit() &&
  3698. !IsWithoutProtoADef)
  3699. Diag(WithProto->getLocation(), diag::note_conflicting_prototype);
  3700. }
  3701. }
  3702. }
  3703. if (Context.typesAreCompatible(OldQType, NewQType)) {
  3704. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3705. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3706. const FunctionProtoType *OldProto = nullptr;
  3707. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3708. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3709. // The old declaration provided a function prototype, but the
  3710. // new declaration does not. Merge in the prototype.
  3711. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3712. NewQType = Context.getFunctionType(NewFuncType->getReturnType(),
  3713. OldProto->getParamTypes(),
  3714. OldProto->getExtProtoInfo());
  3715. New->setType(NewQType);
  3716. New->setHasInheritedPrototype();
  3717. // Synthesize parameters with the same types.
  3718. SmallVector<ParmVarDecl *, 16> Params;
  3719. for (const auto &ParamType : OldProto->param_types()) {
  3720. ParmVarDecl *Param = ParmVarDecl::Create(
  3721. Context, New, SourceLocation(), SourceLocation(), nullptr,
  3722. ParamType, /*TInfo=*/nullptr, SC_None, nullptr);
  3723. Param->setScopeInfo(0, Params.size());
  3724. Param->setImplicit();
  3725. Params.push_back(Param);
  3726. }
  3727. New->setParams(Params);
  3728. }
  3729. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3730. }
  3731. }
  3732. // Check if the function types are compatible when pointer size address
  3733. // spaces are ignored.
  3734. if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
  3735. return false;
  3736. // GNU C permits a K&R definition to follow a prototype declaration
  3737. // if the declared types of the parameters in the K&R definition
  3738. // match the types in the prototype declaration, even when the
  3739. // promoted types of the parameters from the K&R definition differ
  3740. // from the types in the prototype. GCC then keeps the types from
  3741. // the prototype.
  3742. //
  3743. // If a variadic prototype is followed by a non-variadic K&R definition,
  3744. // the K&R definition becomes variadic. This is sort of an edge case, but
  3745. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3746. // C99 6.9.1p8.
  3747. if (!getLangOpts().CPlusPlus &&
  3748. Old->hasPrototype() && !New->hasPrototype() &&
  3749. New->getType()->getAs<FunctionProtoType>() &&
  3750. Old->getNumParams() == New->getNumParams()) {
  3751. SmallVector<QualType, 16> ArgTypes;
  3752. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3753. const FunctionProtoType *OldProto
  3754. = Old->getType()->getAs<FunctionProtoType>();
  3755. const FunctionProtoType *NewProto
  3756. = New->getType()->getAs<FunctionProtoType>();
  3757. // Determine whether this is the GNU C extension.
  3758. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3759. NewProto->getReturnType());
  3760. bool LooseCompatible = !MergedReturn.isNull();
  3761. for (unsigned Idx = 0, End = Old->getNumParams();
  3762. LooseCompatible && Idx != End; ++Idx) {
  3763. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3764. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3765. if (Context.typesAreCompatible(OldParm->getType(),
  3766. NewProto->getParamType(Idx))) {
  3767. ArgTypes.push_back(NewParm->getType());
  3768. } else if (Context.typesAreCompatible(OldParm->getType(),
  3769. NewParm->getType(),
  3770. /*CompareUnqualified=*/true)) {
  3771. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3772. NewProto->getParamType(Idx) };
  3773. Warnings.push_back(Warn);
  3774. ArgTypes.push_back(NewParm->getType());
  3775. } else
  3776. LooseCompatible = false;
  3777. }
  3778. if (LooseCompatible) {
  3779. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3780. Diag(Warnings[Warn].NewParm->getLocation(),
  3781. diag::ext_param_promoted_not_compatible_with_prototype)
  3782. << Warnings[Warn].PromotedType
  3783. << Warnings[Warn].OldParm->getType();
  3784. if (Warnings[Warn].OldParm->getLocation().isValid())
  3785. Diag(Warnings[Warn].OldParm->getLocation(),
  3786. diag::note_previous_declaration);
  3787. }
  3788. if (MergeTypeWithOld)
  3789. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3790. OldProto->getExtProtoInfo()));
  3791. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3792. }
  3793. // Fall through to diagnose conflicting types.
  3794. }
  3795. // A function that has already been declared has been redeclared or
  3796. // defined with a different type; show an appropriate diagnostic.
  3797. // If the previous declaration was an implicitly-generated builtin
  3798. // declaration, then at the very least we should use a specialized note.
  3799. unsigned BuiltinID;
  3800. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3801. // If it's actually a library-defined builtin function like 'malloc'
  3802. // or 'printf', just warn about the incompatible redeclaration.
  3803. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3804. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3805. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3806. << Old << Old->getType();
  3807. return false;
  3808. }
  3809. PrevDiag = diag::note_previous_builtin_declaration;
  3810. }
  3811. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3812. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3813. return true;
  3814. }
  3815. /// Completes the merge of two function declarations that are
  3816. /// known to be compatible.
  3817. ///
  3818. /// This routine handles the merging of attributes and other
  3819. /// properties of function declarations from the old declaration to
  3820. /// the new declaration, once we know that New is in fact a
  3821. /// redeclaration of Old.
  3822. ///
  3823. /// \returns false
  3824. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3825. Scope *S, bool MergeTypeWithOld) {
  3826. // Merge the attributes
  3827. mergeDeclAttributes(New, Old);
  3828. // Merge "pure" flag.
  3829. if (Old->isPure())
  3830. New->setPure();
  3831. // Merge "used" flag.
  3832. if (Old->getMostRecentDecl()->isUsed(false))
  3833. New->setIsUsed();
  3834. // Merge attributes from the parameters. These can mismatch with K&R
  3835. // declarations.
  3836. if (New->getNumParams() == Old->getNumParams())
  3837. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3838. ParmVarDecl *NewParam = New->getParamDecl(i);
  3839. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3840. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3841. mergeParamDeclTypes(NewParam, OldParam, *this);
  3842. }
  3843. if (getLangOpts().CPlusPlus)
  3844. return MergeCXXFunctionDecl(New, Old, S);
  3845. // Merge the function types so the we get the composite types for the return
  3846. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3847. // was visible.
  3848. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3849. if (!Merged.isNull() && MergeTypeWithOld)
  3850. New->setType(Merged);
  3851. return false;
  3852. }
  3853. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3854. ObjCMethodDecl *oldMethod) {
  3855. // Merge the attributes, including deprecated/unavailable
  3856. AvailabilityMergeKind MergeKind =
  3857. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3858. ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
  3859. : AMK_ProtocolImplementation)
  3860. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3861. : AMK_Override;
  3862. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3863. // Merge attributes from the parameters.
  3864. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3865. oe = oldMethod->param_end();
  3866. for (ObjCMethodDecl::param_iterator
  3867. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3868. ni != ne && oi != oe; ++ni, ++oi)
  3869. mergeParamDeclAttributes(*ni, *oi, *this);
  3870. CheckObjCMethodOverride(newMethod, oldMethod);
  3871. }
  3872. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3873. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3874. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3875. ? diag::err_redefinition_different_type
  3876. : diag::err_redeclaration_different_type)
  3877. << New->getDeclName() << New->getType() << Old->getType();
  3878. diag::kind PrevDiag;
  3879. SourceLocation OldLocation;
  3880. std::tie(PrevDiag, OldLocation)
  3881. = getNoteDiagForInvalidRedeclaration(Old, New);
  3882. S.Diag(OldLocation, PrevDiag);
  3883. New->setInvalidDecl();
  3884. }
  3885. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3886. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3887. /// emitting diagnostics as appropriate.
  3888. ///
  3889. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3890. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3891. /// is attached.
  3892. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3893. bool MergeTypeWithOld) {
  3894. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3895. return;
  3896. QualType MergedT;
  3897. if (getLangOpts().CPlusPlus) {
  3898. if (New->getType()->isUndeducedType()) {
  3899. // We don't know what the new type is until the initializer is attached.
  3900. return;
  3901. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3902. // These could still be something that needs exception specs checked.
  3903. return MergeVarDeclExceptionSpecs(New, Old);
  3904. }
  3905. // C++ [basic.link]p10:
  3906. // [...] the types specified by all declarations referring to a given
  3907. // object or function shall be identical, except that declarations for an
  3908. // array object can specify array types that differ by the presence or
  3909. // absence of a major array bound (8.3.4).
  3910. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3911. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3912. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3913. // We are merging a variable declaration New into Old. If it has an array
  3914. // bound, and that bound differs from Old's bound, we should diagnose the
  3915. // mismatch.
  3916. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3917. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3918. PrevVD = PrevVD->getPreviousDecl()) {
  3919. QualType PrevVDTy = PrevVD->getType();
  3920. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3921. continue;
  3922. if (!Context.hasSameType(New->getType(), PrevVDTy))
  3923. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3924. }
  3925. }
  3926. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3927. if (Context.hasSameType(OldArray->getElementType(),
  3928. NewArray->getElementType()))
  3929. MergedT = New->getType();
  3930. }
  3931. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3932. // has no array bound, it should not inherit one from Old, if Old is not
  3933. // visible.
  3934. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3935. if (Context.hasSameType(OldArray->getElementType(),
  3936. NewArray->getElementType()))
  3937. MergedT = Old->getType();
  3938. }
  3939. }
  3940. else if (New->getType()->isObjCObjectPointerType() &&
  3941. Old->getType()->isObjCObjectPointerType()) {
  3942. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3943. Old->getType());
  3944. }
  3945. } else {
  3946. // C 6.2.7p2:
  3947. // All declarations that refer to the same object or function shall have
  3948. // compatible type.
  3949. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3950. }
  3951. if (MergedT.isNull()) {
  3952. // It's OK if we couldn't merge types if either type is dependent, for a
  3953. // block-scope variable. In other cases (static data members of class
  3954. // templates, variable templates, ...), we require the types to be
  3955. // equivalent.
  3956. // FIXME: The C++ standard doesn't say anything about this.
  3957. if ((New->getType()->isDependentType() ||
  3958. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3959. // If the old type was dependent, we can't merge with it, so the new type
  3960. // becomes dependent for now. We'll reproduce the original type when we
  3961. // instantiate the TypeSourceInfo for the variable.
  3962. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3963. New->setType(Context.DependentTy);
  3964. return;
  3965. }
  3966. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3967. }
  3968. // Don't actually update the type on the new declaration if the old
  3969. // declaration was an extern declaration in a different scope.
  3970. if (MergeTypeWithOld)
  3971. New->setType(MergedT);
  3972. }
  3973. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3974. LookupResult &Previous) {
  3975. // C11 6.2.7p4:
  3976. // For an identifier with internal or external linkage declared
  3977. // in a scope in which a prior declaration of that identifier is
  3978. // visible, if the prior declaration specifies internal or
  3979. // external linkage, the type of the identifier at the later
  3980. // declaration becomes the composite type.
  3981. //
  3982. // If the variable isn't visible, we do not merge with its type.
  3983. if (Previous.isShadowed())
  3984. return false;
  3985. if (S.getLangOpts().CPlusPlus) {
  3986. // C++11 [dcl.array]p3:
  3987. // If there is a preceding declaration of the entity in the same
  3988. // scope in which the bound was specified, an omitted array bound
  3989. // is taken to be the same as in that earlier declaration.
  3990. return NewVD->isPreviousDeclInSameBlockScope() ||
  3991. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3992. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3993. } else {
  3994. // If the old declaration was function-local, don't merge with its
  3995. // type unless we're in the same function.
  3996. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3997. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3998. }
  3999. }
  4000. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  4001. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  4002. /// situation, merging decls or emitting diagnostics as appropriate.
  4003. ///
  4004. /// Tentative definition rules (C99 6.9.2p2) are checked by
  4005. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  4006. /// definitions here, since the initializer hasn't been attached.
  4007. ///
  4008. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  4009. // If the new decl is already invalid, don't do any other checking.
  4010. if (New->isInvalidDecl())
  4011. return;
  4012. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  4013. return;
  4014. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  4015. // Verify the old decl was also a variable or variable template.
  4016. VarDecl *Old = nullptr;
  4017. VarTemplateDecl *OldTemplate = nullptr;
  4018. if (Previous.isSingleResult()) {
  4019. if (NewTemplate) {
  4020. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  4021. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  4022. if (auto *Shadow =
  4023. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  4024. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  4025. return New->setInvalidDecl();
  4026. } else {
  4027. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  4028. if (auto *Shadow =
  4029. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  4030. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  4031. return New->setInvalidDecl();
  4032. }
  4033. }
  4034. if (!Old) {
  4035. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  4036. << New->getDeclName();
  4037. notePreviousDefinition(Previous.getRepresentativeDecl(),
  4038. New->getLocation());
  4039. return New->setInvalidDecl();
  4040. }
  4041. // If the old declaration was found in an inline namespace and the new
  4042. // declaration was qualified, update the DeclContext to match.
  4043. adjustDeclContextForDeclaratorDecl(New, Old);
  4044. // Ensure the template parameters are compatible.
  4045. if (NewTemplate &&
  4046. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  4047. OldTemplate->getTemplateParameters(),
  4048. /*Complain=*/true, TPL_TemplateMatch))
  4049. return New->setInvalidDecl();
  4050. // C++ [class.mem]p1:
  4051. // A member shall not be declared twice in the member-specification [...]
  4052. //
  4053. // Here, we need only consider static data members.
  4054. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  4055. Diag(New->getLocation(), diag::err_duplicate_member)
  4056. << New->getIdentifier();
  4057. Diag(Old->getLocation(), diag::note_previous_declaration);
  4058. New->setInvalidDecl();
  4059. }
  4060. mergeDeclAttributes(New, Old);
  4061. // Warn if an already-declared variable is made a weak_import in a subsequent
  4062. // declaration
  4063. if (New->hasAttr<WeakImportAttr>() &&
  4064. Old->getStorageClass() == SC_None &&
  4065. !Old->hasAttr<WeakImportAttr>()) {
  4066. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  4067. Diag(Old->getLocation(), diag::note_previous_declaration);
  4068. // Remove weak_import attribute on new declaration.
  4069. New->dropAttr<WeakImportAttr>();
  4070. }
  4071. if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
  4072. if (!Old->hasAttr<InternalLinkageAttr>()) {
  4073. Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
  4074. << ILA;
  4075. Diag(Old->getLocation(), diag::note_previous_declaration);
  4076. New->dropAttr<InternalLinkageAttr>();
  4077. }
  4078. // Merge the types.
  4079. VarDecl *MostRecent = Old->getMostRecentDecl();
  4080. if (MostRecent != Old) {
  4081. MergeVarDeclTypes(New, MostRecent,
  4082. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  4083. if (New->isInvalidDecl())
  4084. return;
  4085. }
  4086. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  4087. if (New->isInvalidDecl())
  4088. return;
  4089. diag::kind PrevDiag;
  4090. SourceLocation OldLocation;
  4091. std::tie(PrevDiag, OldLocation) =
  4092. getNoteDiagForInvalidRedeclaration(Old, New);
  4093. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  4094. if (New->getStorageClass() == SC_Static &&
  4095. !New->isStaticDataMember() &&
  4096. Old->hasExternalFormalLinkage()) {
  4097. if (getLangOpts().MicrosoftExt) {
  4098. Diag(New->getLocation(), diag::ext_static_non_static)
  4099. << New->getDeclName();
  4100. Diag(OldLocation, PrevDiag);
  4101. } else {
  4102. Diag(New->getLocation(), diag::err_static_non_static)
  4103. << New->getDeclName();
  4104. Diag(OldLocation, PrevDiag);
  4105. return New->setInvalidDecl();
  4106. }
  4107. }
  4108. // C99 6.2.2p4:
  4109. // For an identifier declared with the storage-class specifier
  4110. // extern in a scope in which a prior declaration of that
  4111. // identifier is visible,23) if the prior declaration specifies
  4112. // internal or external linkage, the linkage of the identifier at
  4113. // the later declaration is the same as the linkage specified at
  4114. // the prior declaration. If no prior declaration is visible, or
  4115. // if the prior declaration specifies no linkage, then the
  4116. // identifier has external linkage.
  4117. if (New->hasExternalStorage() && Old->hasLinkage())
  4118. /* Okay */;
  4119. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  4120. !New->isStaticDataMember() &&
  4121. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  4122. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  4123. Diag(OldLocation, PrevDiag);
  4124. return New->setInvalidDecl();
  4125. }
  4126. // Check if extern is followed by non-extern and vice-versa.
  4127. if (New->hasExternalStorage() &&
  4128. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  4129. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  4130. Diag(OldLocation, PrevDiag);
  4131. return New->setInvalidDecl();
  4132. }
  4133. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  4134. !New->hasExternalStorage()) {
  4135. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  4136. Diag(OldLocation, PrevDiag);
  4137. return New->setInvalidDecl();
  4138. }
  4139. if (CheckRedeclarationInModule(New, Old))
  4140. return;
  4141. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  4142. // FIXME: The test for external storage here seems wrong? We still
  4143. // need to check for mismatches.
  4144. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  4145. // Don't complain about out-of-line definitions of static members.
  4146. !(Old->getLexicalDeclContext()->isRecord() &&
  4147. !New->getLexicalDeclContext()->isRecord())) {
  4148. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  4149. Diag(OldLocation, PrevDiag);
  4150. return New->setInvalidDecl();
  4151. }
  4152. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  4153. if (VarDecl *Def = Old->getDefinition()) {
  4154. // C++1z [dcl.fcn.spec]p4:
  4155. // If the definition of a variable appears in a translation unit before
  4156. // its first declaration as inline, the program is ill-formed.
  4157. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  4158. Diag(Def->getLocation(), diag::note_previous_definition);
  4159. }
  4160. }
  4161. // If this redeclaration makes the variable inline, we may need to add it to
  4162. // UndefinedButUsed.
  4163. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  4164. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  4165. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  4166. SourceLocation()));
  4167. if (New->getTLSKind() != Old->getTLSKind()) {
  4168. if (!Old->getTLSKind()) {
  4169. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  4170. Diag(OldLocation, PrevDiag);
  4171. } else if (!New->getTLSKind()) {
  4172. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  4173. Diag(OldLocation, PrevDiag);
  4174. } else {
  4175. // Do not allow redeclaration to change the variable between requiring
  4176. // static and dynamic initialization.
  4177. // FIXME: GCC allows this, but uses the TLS keyword on the first
  4178. // declaration to determine the kind. Do we need to be compatible here?
  4179. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  4180. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  4181. Diag(OldLocation, PrevDiag);
  4182. }
  4183. }
  4184. // C++ doesn't have tentative definitions, so go right ahead and check here.
  4185. if (getLangOpts().CPlusPlus) {
  4186. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  4187. Old->getCanonicalDecl()->isConstexpr()) {
  4188. // This definition won't be a definition any more once it's been merged.
  4189. Diag(New->getLocation(),
  4190. diag::warn_deprecated_redundant_constexpr_static_def);
  4191. } else if (New->isThisDeclarationADefinition() == VarDecl::Definition) {
  4192. VarDecl *Def = Old->getDefinition();
  4193. if (Def && checkVarDeclRedefinition(Def, New))
  4194. return;
  4195. }
  4196. }
  4197. if (haveIncompatibleLanguageLinkages(Old, New)) {
  4198. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  4199. Diag(OldLocation, PrevDiag);
  4200. New->setInvalidDecl();
  4201. return;
  4202. }
  4203. // Merge "used" flag.
  4204. if (Old->getMostRecentDecl()->isUsed(false))
  4205. New->setIsUsed();
  4206. // Keep a chain of previous declarations.
  4207. New->setPreviousDecl(Old);
  4208. if (NewTemplate)
  4209. NewTemplate->setPreviousDecl(OldTemplate);
  4210. // Inherit access appropriately.
  4211. New->setAccess(Old->getAccess());
  4212. if (NewTemplate)
  4213. NewTemplate->setAccess(New->getAccess());
  4214. if (Old->isInline())
  4215. New->setImplicitlyInline();
  4216. }
  4217. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  4218. SourceManager &SrcMgr = getSourceManager();
  4219. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  4220. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  4221. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  4222. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  4223. auto &HSI = PP.getHeaderSearchInfo();
  4224. StringRef HdrFilename =
  4225. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  4226. auto noteFromModuleOrInclude = [&](Module *Mod,
  4227. SourceLocation IncLoc) -> bool {
  4228. // Redefinition errors with modules are common with non modular mapped
  4229. // headers, example: a non-modular header H in module A that also gets
  4230. // included directly in a TU. Pointing twice to the same header/definition
  4231. // is confusing, try to get better diagnostics when modules is on.
  4232. if (IncLoc.isValid()) {
  4233. if (Mod) {
  4234. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  4235. << HdrFilename.str() << Mod->getFullModuleName();
  4236. if (!Mod->DefinitionLoc.isInvalid())
  4237. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  4238. << Mod->getFullModuleName();
  4239. } else {
  4240. Diag(IncLoc, diag::note_redefinition_include_same_file)
  4241. << HdrFilename.str();
  4242. }
  4243. return true;
  4244. }
  4245. return false;
  4246. };
  4247. // Is it the same file and same offset? Provide more information on why
  4248. // this leads to a redefinition error.
  4249. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  4250. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  4251. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  4252. bool EmittedDiag =
  4253. noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  4254. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  4255. // If the header has no guards, emit a note suggesting one.
  4256. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  4257. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  4258. if (EmittedDiag)
  4259. return;
  4260. }
  4261. // Redefinition coming from different files or couldn't do better above.
  4262. if (Old->getLocation().isValid())
  4263. Diag(Old->getLocation(), diag::note_previous_definition);
  4264. }
  4265. /// We've just determined that \p Old and \p New both appear to be definitions
  4266. /// of the same variable. Either diagnose or fix the problem.
  4267. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  4268. if (!hasVisibleDefinition(Old) &&
  4269. (New->getFormalLinkage() == InternalLinkage ||
  4270. New->isInline() ||
  4271. isa<VarTemplateSpecializationDecl>(New) ||
  4272. New->getDescribedVarTemplate() ||
  4273. New->getNumTemplateParameterLists() ||
  4274. New->getDeclContext()->isDependentContext())) {
  4275. // The previous definition is hidden, and multiple definitions are
  4276. // permitted (in separate TUs). Demote this to a declaration.
  4277. New->demoteThisDefinitionToDeclaration();
  4278. // Make the canonical definition visible.
  4279. if (auto *OldTD = Old->getDescribedVarTemplate())
  4280. makeMergedDefinitionVisible(OldTD);
  4281. makeMergedDefinitionVisible(Old);
  4282. return false;
  4283. } else {
  4284. Diag(New->getLocation(), diag::err_redefinition) << New;
  4285. notePreviousDefinition(Old, New->getLocation());
  4286. New->setInvalidDecl();
  4287. return true;
  4288. }
  4289. }
  4290. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  4291. /// no declarator (e.g. "struct foo;") is parsed.
  4292. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  4293. DeclSpec &DS,
  4294. const ParsedAttributesView &DeclAttrs,
  4295. RecordDecl *&AnonRecord) {
  4296. return ParsedFreeStandingDeclSpec(
  4297. S, AS, DS, DeclAttrs, MultiTemplateParamsArg(), false, AnonRecord);
  4298. }
  4299. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  4300. // disambiguate entities defined in different scopes.
  4301. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  4302. // compatibility.
  4303. // We will pick our mangling number depending on which version of MSVC is being
  4304. // targeted.
  4305. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  4306. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  4307. ? S->getMSCurManglingNumber()
  4308. : S->getMSLastManglingNumber();
  4309. }
  4310. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  4311. if (!Context.getLangOpts().CPlusPlus)
  4312. return;
  4313. if (isa<CXXRecordDecl>(Tag->getParent())) {
  4314. // If this tag is the direct child of a class, number it if
  4315. // it is anonymous.
  4316. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  4317. return;
  4318. MangleNumberingContext &MCtx =
  4319. Context.getManglingNumberContext(Tag->getParent());
  4320. Context.setManglingNumber(
  4321. Tag, MCtx.getManglingNumber(
  4322. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  4323. return;
  4324. }
  4325. // If this tag isn't a direct child of a class, number it if it is local.
  4326. MangleNumberingContext *MCtx;
  4327. Decl *ManglingContextDecl;
  4328. std::tie(MCtx, ManglingContextDecl) =
  4329. getCurrentMangleNumberContext(Tag->getDeclContext());
  4330. if (MCtx) {
  4331. Context.setManglingNumber(
  4332. Tag, MCtx->getManglingNumber(
  4333. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  4334. }
  4335. }
  4336. namespace {
  4337. struct NonCLikeKind {
  4338. enum {
  4339. None,
  4340. BaseClass,
  4341. DefaultMemberInit,
  4342. Lambda,
  4343. Friend,
  4344. OtherMember,
  4345. Invalid,
  4346. } Kind = None;
  4347. SourceRange Range;
  4348. explicit operator bool() { return Kind != None; }
  4349. };
  4350. }
  4351. /// Determine whether a class is C-like, according to the rules of C++
  4352. /// [dcl.typedef] for anonymous classes with typedef names for linkage.
  4353. static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
  4354. if (RD->isInvalidDecl())
  4355. return {NonCLikeKind::Invalid, {}};
  4356. // C++ [dcl.typedef]p9: [P1766R1]
  4357. // An unnamed class with a typedef name for linkage purposes shall not
  4358. //
  4359. // -- have any base classes
  4360. if (RD->getNumBases())
  4361. return {NonCLikeKind::BaseClass,
  4362. SourceRange(RD->bases_begin()->getBeginLoc(),
  4363. RD->bases_end()[-1].getEndLoc())};
  4364. bool Invalid = false;
  4365. for (Decl *D : RD->decls()) {
  4366. // Don't complain about things we already diagnosed.
  4367. if (D->isInvalidDecl()) {
  4368. Invalid = true;
  4369. continue;
  4370. }
  4371. // -- have any [...] default member initializers
  4372. if (auto *FD = dyn_cast<FieldDecl>(D)) {
  4373. if (FD->hasInClassInitializer()) {
  4374. auto *Init = FD->getInClassInitializer();
  4375. return {NonCLikeKind::DefaultMemberInit,
  4376. Init ? Init->getSourceRange() : D->getSourceRange()};
  4377. }
  4378. continue;
  4379. }
  4380. // FIXME: We don't allow friend declarations. This violates the wording of
  4381. // P1766, but not the intent.
  4382. if (isa<FriendDecl>(D))
  4383. return {NonCLikeKind::Friend, D->getSourceRange()};
  4384. // -- declare any members other than non-static data members, member
  4385. // enumerations, or member classes,
  4386. if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
  4387. isa<EnumDecl>(D))
  4388. continue;
  4389. auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
  4390. if (!MemberRD) {
  4391. if (D->isImplicit())
  4392. continue;
  4393. return {NonCLikeKind::OtherMember, D->getSourceRange()};
  4394. }
  4395. // -- contain a lambda-expression,
  4396. if (MemberRD->isLambda())
  4397. return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
  4398. // and all member classes shall also satisfy these requirements
  4399. // (recursively).
  4400. if (MemberRD->isThisDeclarationADefinition()) {
  4401. if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
  4402. return Kind;
  4403. }
  4404. }
  4405. return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
  4406. }
  4407. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  4408. TypedefNameDecl *NewTD) {
  4409. if (TagFromDeclSpec->isInvalidDecl())
  4410. return;
  4411. // Do nothing if the tag already has a name for linkage purposes.
  4412. if (TagFromDeclSpec->hasNameForLinkage())
  4413. return;
  4414. // A well-formed anonymous tag must always be a TUK_Definition.
  4415. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  4416. // The type must match the tag exactly; no qualifiers allowed.
  4417. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  4418. Context.getTagDeclType(TagFromDeclSpec))) {
  4419. if (getLangOpts().CPlusPlus)
  4420. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  4421. return;
  4422. }
  4423. // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
  4424. // An unnamed class with a typedef name for linkage purposes shall [be
  4425. // C-like].
  4426. //
  4427. // FIXME: Also diagnose if we've already computed the linkage. That ideally
  4428. // shouldn't happen, but there are constructs that the language rule doesn't
  4429. // disallow for which we can't reasonably avoid computing linkage early.
  4430. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
  4431. NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
  4432. : NonCLikeKind();
  4433. bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
  4434. if (NonCLike || ChangesLinkage) {
  4435. if (NonCLike.Kind == NonCLikeKind::Invalid)
  4436. return;
  4437. unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
  4438. if (ChangesLinkage) {
  4439. // If the linkage changes, we can't accept this as an extension.
  4440. if (NonCLike.Kind == NonCLikeKind::None)
  4441. DiagID = diag::err_typedef_changes_linkage;
  4442. else
  4443. DiagID = diag::err_non_c_like_anon_struct_in_typedef;
  4444. }
  4445. SourceLocation FixitLoc =
  4446. getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
  4447. llvm::SmallString<40> TextToInsert;
  4448. TextToInsert += ' ';
  4449. TextToInsert += NewTD->getIdentifier()->getName();
  4450. Diag(FixitLoc, DiagID)
  4451. << isa<TypeAliasDecl>(NewTD)
  4452. << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
  4453. if (NonCLike.Kind != NonCLikeKind::None) {
  4454. Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
  4455. << NonCLike.Kind - 1 << NonCLike.Range;
  4456. }
  4457. Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
  4458. << NewTD << isa<TypeAliasDecl>(NewTD);
  4459. if (ChangesLinkage)
  4460. return;
  4461. }
  4462. // Otherwise, set this as the anon-decl typedef for the tag.
  4463. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  4464. }
  4465. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  4466. switch (T) {
  4467. case DeclSpec::TST_class:
  4468. return 0;
  4469. case DeclSpec::TST_struct:
  4470. return 1;
  4471. case DeclSpec::TST_interface:
  4472. return 2;
  4473. case DeclSpec::TST_union:
  4474. return 3;
  4475. case DeclSpec::TST_enum:
  4476. return 4;
  4477. default:
  4478. llvm_unreachable("unexpected type specifier");
  4479. }
  4480. }
  4481. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  4482. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  4483. /// parameters to cope with template friend declarations.
  4484. Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
  4485. DeclSpec &DS,
  4486. const ParsedAttributesView &DeclAttrs,
  4487. MultiTemplateParamsArg TemplateParams,
  4488. bool IsExplicitInstantiation,
  4489. RecordDecl *&AnonRecord) {
  4490. Decl *TagD = nullptr;
  4491. TagDecl *Tag = nullptr;
  4492. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  4493. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  4494. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  4495. DS.getTypeSpecType() == DeclSpec::TST_union ||
  4496. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  4497. TagD = DS.getRepAsDecl();
  4498. if (!TagD) // We probably had an error
  4499. return nullptr;
  4500. // Note that the above type specs guarantee that the
  4501. // type rep is a Decl, whereas in many of the others
  4502. // it's a Type.
  4503. if (isa<TagDecl>(TagD))
  4504. Tag = cast<TagDecl>(TagD);
  4505. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  4506. Tag = CTD->getTemplatedDecl();
  4507. }
  4508. if (Tag) {
  4509. handleTagNumbering(Tag, S);
  4510. Tag->setFreeStanding();
  4511. if (Tag->isInvalidDecl())
  4512. return Tag;
  4513. }
  4514. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  4515. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  4516. // or incomplete types shall not be restrict-qualified."
  4517. if (TypeQuals & DeclSpec::TQ_restrict)
  4518. Diag(DS.getRestrictSpecLoc(),
  4519. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  4520. << DS.getSourceRange();
  4521. }
  4522. if (DS.isInlineSpecified())
  4523. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  4524. << getLangOpts().CPlusPlus17;
  4525. if (DS.hasConstexprSpecifier()) {
  4526. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  4527. // and definitions of functions and variables.
  4528. // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
  4529. // the declaration of a function or function template
  4530. if (Tag)
  4531. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  4532. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
  4533. << static_cast<int>(DS.getConstexprSpecifier());
  4534. else
  4535. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
  4536. << static_cast<int>(DS.getConstexprSpecifier());
  4537. // Don't emit warnings after this error.
  4538. return TagD;
  4539. }
  4540. DiagnoseFunctionSpecifiers(DS);
  4541. if (DS.isFriendSpecified()) {
  4542. // If we're dealing with a decl but not a TagDecl, assume that
  4543. // whatever routines created it handled the friendship aspect.
  4544. if (TagD && !Tag)
  4545. return nullptr;
  4546. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  4547. }
  4548. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  4549. bool IsExplicitSpecialization =
  4550. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  4551. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  4552. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  4553. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  4554. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  4555. // nested-name-specifier unless it is an explicit instantiation
  4556. // or an explicit specialization.
  4557. //
  4558. // FIXME: We allow class template partial specializations here too, per the
  4559. // obvious intent of DR1819.
  4560. //
  4561. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  4562. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  4563. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  4564. return nullptr;
  4565. }
  4566. // Track whether this decl-specifier declares anything.
  4567. bool DeclaresAnything = true;
  4568. // Handle anonymous struct definitions.
  4569. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  4570. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  4571. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  4572. if (getLangOpts().CPlusPlus ||
  4573. Record->getDeclContext()->isRecord()) {
  4574. // If CurContext is a DeclContext that can contain statements,
  4575. // RecursiveASTVisitor won't visit the decls that
  4576. // BuildAnonymousStructOrUnion() will put into CurContext.
  4577. // Also store them here so that they can be part of the
  4578. // DeclStmt that gets created in this case.
  4579. // FIXME: Also return the IndirectFieldDecls created by
  4580. // BuildAnonymousStructOr union, for the same reason?
  4581. if (CurContext->isFunctionOrMethod())
  4582. AnonRecord = Record;
  4583. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  4584. Context.getPrintingPolicy());
  4585. }
  4586. DeclaresAnything = false;
  4587. }
  4588. }
  4589. // C11 6.7.2.1p2:
  4590. // A struct-declaration that does not declare an anonymous structure or
  4591. // anonymous union shall contain a struct-declarator-list.
  4592. //
  4593. // This rule also existed in C89 and C99; the grammar for struct-declaration
  4594. // did not permit a struct-declaration without a struct-declarator-list.
  4595. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  4596. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  4597. // Check for Microsoft C extension: anonymous struct/union member.
  4598. // Handle 2 kinds of anonymous struct/union:
  4599. // struct STRUCT;
  4600. // union UNION;
  4601. // and
  4602. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  4603. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  4604. if ((Tag && Tag->getDeclName()) ||
  4605. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  4606. RecordDecl *Record = nullptr;
  4607. if (Tag)
  4608. Record = dyn_cast<RecordDecl>(Tag);
  4609. else if (const RecordType *RT =
  4610. DS.getRepAsType().get()->getAsStructureType())
  4611. Record = RT->getDecl();
  4612. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  4613. Record = UT->getDecl();
  4614. if (Record && getLangOpts().MicrosoftExt) {
  4615. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  4616. << Record->isUnion() << DS.getSourceRange();
  4617. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  4618. }
  4619. DeclaresAnything = false;
  4620. }
  4621. }
  4622. // Skip all the checks below if we have a type error.
  4623. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  4624. (TagD && TagD->isInvalidDecl()))
  4625. return TagD;
  4626. if (getLangOpts().CPlusPlus &&
  4627. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  4628. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  4629. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  4630. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  4631. DeclaresAnything = false;
  4632. if (!DS.isMissingDeclaratorOk()) {
  4633. // Customize diagnostic for a typedef missing a name.
  4634. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  4635. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  4636. << DS.getSourceRange();
  4637. else
  4638. DeclaresAnything = false;
  4639. }
  4640. if (DS.isModulePrivateSpecified() &&
  4641. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  4642. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  4643. << Tag->getTagKind()
  4644. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  4645. ActOnDocumentableDecl(TagD);
  4646. // C 6.7/2:
  4647. // A declaration [...] shall declare at least a declarator [...], a tag,
  4648. // or the members of an enumeration.
  4649. // C++ [dcl.dcl]p3:
  4650. // [If there are no declarators], and except for the declaration of an
  4651. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  4652. // names into the program, or shall redeclare a name introduced by a
  4653. // previous declaration.
  4654. if (!DeclaresAnything) {
  4655. // In C, we allow this as a (popular) extension / bug. Don't bother
  4656. // producing further diagnostics for redundant qualifiers after this.
  4657. Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
  4658. ? diag::err_no_declarators
  4659. : diag::ext_no_declarators)
  4660. << DS.getSourceRange();
  4661. return TagD;
  4662. }
  4663. // C++ [dcl.stc]p1:
  4664. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  4665. // init-declarator-list of the declaration shall not be empty.
  4666. // C++ [dcl.fct.spec]p1:
  4667. // If a cv-qualifier appears in a decl-specifier-seq, the
  4668. // init-declarator-list of the declaration shall not be empty.
  4669. //
  4670. // Spurious qualifiers here appear to be valid in C.
  4671. unsigned DiagID = diag::warn_standalone_specifier;
  4672. if (getLangOpts().CPlusPlus)
  4673. DiagID = diag::ext_standalone_specifier;
  4674. // Note that a linkage-specification sets a storage class, but
  4675. // 'extern "C" struct foo;' is actually valid and not theoretically
  4676. // useless.
  4677. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  4678. if (SCS == DeclSpec::SCS_mutable)
  4679. // Since mutable is not a viable storage class specifier in C, there is
  4680. // no reason to treat it as an extension. Instead, diagnose as an error.
  4681. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  4682. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  4683. Diag(DS.getStorageClassSpecLoc(), DiagID)
  4684. << DeclSpec::getSpecifierName(SCS);
  4685. }
  4686. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  4687. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  4688. << DeclSpec::getSpecifierName(TSCS);
  4689. if (DS.getTypeQualifiers()) {
  4690. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4691. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  4692. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4693. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  4694. // Restrict is covered above.
  4695. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4696. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  4697. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4698. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  4699. }
  4700. // Warn about ignored type attributes, for example:
  4701. // __attribute__((aligned)) struct A;
  4702. // Attributes should be placed after tag to apply to type declaration.
  4703. if (!DS.getAttributes().empty() || !DeclAttrs.empty()) {
  4704. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  4705. if (TypeSpecType == DeclSpec::TST_class ||
  4706. TypeSpecType == DeclSpec::TST_struct ||
  4707. TypeSpecType == DeclSpec::TST_interface ||
  4708. TypeSpecType == DeclSpec::TST_union ||
  4709. TypeSpecType == DeclSpec::TST_enum) {
  4710. for (const ParsedAttr &AL : DS.getAttributes())
  4711. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4712. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4713. for (const ParsedAttr &AL : DeclAttrs)
  4714. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  4715. << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
  4716. }
  4717. }
  4718. return TagD;
  4719. }
  4720. /// We are trying to inject an anonymous member into the given scope;
  4721. /// check if there's an existing declaration that can't be overloaded.
  4722. ///
  4723. /// \return true if this is a forbidden redeclaration
  4724. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  4725. Scope *S,
  4726. DeclContext *Owner,
  4727. DeclarationName Name,
  4728. SourceLocation NameLoc,
  4729. bool IsUnion) {
  4730. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  4731. Sema::ForVisibleRedeclaration);
  4732. if (!SemaRef.LookupName(R, S)) return false;
  4733. // Pick a representative declaration.
  4734. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  4735. assert(PrevDecl && "Expected a non-null Decl");
  4736. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  4737. return false;
  4738. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  4739. << IsUnion << Name;
  4740. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  4741. return true;
  4742. }
  4743. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  4744. /// anonymous struct or union AnonRecord into the owning context Owner
  4745. /// and scope S. This routine will be invoked just after we realize
  4746. /// that an unnamed union or struct is actually an anonymous union or
  4747. /// struct, e.g.,
  4748. ///
  4749. /// @code
  4750. /// union {
  4751. /// int i;
  4752. /// float f;
  4753. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  4754. /// // f into the surrounding scope.x
  4755. /// @endcode
  4756. ///
  4757. /// This routine is recursive, injecting the names of nested anonymous
  4758. /// structs/unions into the owning context and scope as well.
  4759. static bool
  4760. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  4761. RecordDecl *AnonRecord, AccessSpecifier AS,
  4762. SmallVectorImpl<NamedDecl *> &Chaining) {
  4763. bool Invalid = false;
  4764. // Look every FieldDecl and IndirectFieldDecl with a name.
  4765. for (auto *D : AnonRecord->decls()) {
  4766. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  4767. cast<NamedDecl>(D)->getDeclName()) {
  4768. ValueDecl *VD = cast<ValueDecl>(D);
  4769. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4770. VD->getLocation(),
  4771. AnonRecord->isUnion())) {
  4772. // C++ [class.union]p2:
  4773. // The names of the members of an anonymous union shall be
  4774. // distinct from the names of any other entity in the
  4775. // scope in which the anonymous union is declared.
  4776. Invalid = true;
  4777. } else {
  4778. // C++ [class.union]p2:
  4779. // For the purpose of name lookup, after the anonymous union
  4780. // definition, the members of the anonymous union are
  4781. // considered to have been defined in the scope in which the
  4782. // anonymous union is declared.
  4783. unsigned OldChainingSize = Chaining.size();
  4784. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4785. Chaining.append(IF->chain_begin(), IF->chain_end());
  4786. else
  4787. Chaining.push_back(VD);
  4788. assert(Chaining.size() >= 2);
  4789. NamedDecl **NamedChain =
  4790. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4791. for (unsigned i = 0; i < Chaining.size(); i++)
  4792. NamedChain[i] = Chaining[i];
  4793. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4794. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4795. VD->getType(), {NamedChain, Chaining.size()});
  4796. for (const auto *Attr : VD->attrs())
  4797. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4798. IndirectField->setAccess(AS);
  4799. IndirectField->setImplicit();
  4800. SemaRef.PushOnScopeChains(IndirectField, S);
  4801. // That includes picking up the appropriate access specifier.
  4802. if (AS != AS_none) IndirectField->setAccess(AS);
  4803. Chaining.resize(OldChainingSize);
  4804. }
  4805. }
  4806. }
  4807. return Invalid;
  4808. }
  4809. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4810. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4811. /// illegal input values are mapped to SC_None.
  4812. static StorageClass
  4813. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4814. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4815. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4816. "Parser allowed 'typedef' as storage class VarDecl.");
  4817. switch (StorageClassSpec) {
  4818. case DeclSpec::SCS_unspecified: return SC_None;
  4819. case DeclSpec::SCS_extern:
  4820. if (DS.isExternInLinkageSpec())
  4821. return SC_None;
  4822. return SC_Extern;
  4823. case DeclSpec::SCS_static: return SC_Static;
  4824. case DeclSpec::SCS_auto: return SC_Auto;
  4825. case DeclSpec::SCS_register: return SC_Register;
  4826. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4827. // Illegal SCSs map to None: error reporting is up to the caller.
  4828. case DeclSpec::SCS_mutable: // Fall through.
  4829. case DeclSpec::SCS_typedef: return SC_None;
  4830. }
  4831. llvm_unreachable("unknown storage class specifier");
  4832. }
  4833. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4834. assert(Record->hasInClassInitializer());
  4835. for (const auto *I : Record->decls()) {
  4836. const auto *FD = dyn_cast<FieldDecl>(I);
  4837. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4838. FD = IFD->getAnonField();
  4839. if (FD && FD->hasInClassInitializer())
  4840. return FD->getLocation();
  4841. }
  4842. llvm_unreachable("couldn't find in-class initializer");
  4843. }
  4844. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4845. SourceLocation DefaultInitLoc) {
  4846. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4847. return;
  4848. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4849. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4850. }
  4851. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4852. CXXRecordDecl *AnonUnion) {
  4853. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4854. return;
  4855. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4856. }
  4857. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4858. /// anonymous structure or union. Anonymous unions are a C++ feature
  4859. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4860. /// are a C11 feature and GNU C++ extension.
  4861. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4862. AccessSpecifier AS,
  4863. RecordDecl *Record,
  4864. const PrintingPolicy &Policy) {
  4865. DeclContext *Owner = Record->getDeclContext();
  4866. // Diagnose whether this anonymous struct/union is an extension.
  4867. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4868. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4869. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4870. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4871. else if (!Record->isUnion() && !getLangOpts().C11)
  4872. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4873. // C and C++ require different kinds of checks for anonymous
  4874. // structs/unions.
  4875. bool Invalid = false;
  4876. if (getLangOpts().CPlusPlus) {
  4877. const char *PrevSpec = nullptr;
  4878. if (Record->isUnion()) {
  4879. // C++ [class.union]p6:
  4880. // C++17 [class.union.anon]p2:
  4881. // Anonymous unions declared in a named namespace or in the
  4882. // global namespace shall be declared static.
  4883. unsigned DiagID;
  4884. DeclContext *OwnerScope = Owner->getRedeclContext();
  4885. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4886. (OwnerScope->isTranslationUnit() ||
  4887. (OwnerScope->isNamespace() &&
  4888. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4889. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4890. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4891. // Recover by adding 'static'.
  4892. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4893. PrevSpec, DiagID, Policy);
  4894. }
  4895. // C++ [class.union]p6:
  4896. // A storage class is not allowed in a declaration of an
  4897. // anonymous union in a class scope.
  4898. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4899. isa<RecordDecl>(Owner)) {
  4900. Diag(DS.getStorageClassSpecLoc(),
  4901. diag::err_anonymous_union_with_storage_spec)
  4902. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4903. // Recover by removing the storage specifier.
  4904. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4905. SourceLocation(),
  4906. PrevSpec, DiagID, Context.getPrintingPolicy());
  4907. }
  4908. }
  4909. // Ignore const/volatile/restrict qualifiers.
  4910. if (DS.getTypeQualifiers()) {
  4911. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4912. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4913. << Record->isUnion() << "const"
  4914. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4915. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4916. Diag(DS.getVolatileSpecLoc(),
  4917. diag::ext_anonymous_struct_union_qualified)
  4918. << Record->isUnion() << "volatile"
  4919. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4920. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4921. Diag(DS.getRestrictSpecLoc(),
  4922. diag::ext_anonymous_struct_union_qualified)
  4923. << Record->isUnion() << "restrict"
  4924. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4925. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4926. Diag(DS.getAtomicSpecLoc(),
  4927. diag::ext_anonymous_struct_union_qualified)
  4928. << Record->isUnion() << "_Atomic"
  4929. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4930. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4931. Diag(DS.getUnalignedSpecLoc(),
  4932. diag::ext_anonymous_struct_union_qualified)
  4933. << Record->isUnion() << "__unaligned"
  4934. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4935. DS.ClearTypeQualifiers();
  4936. }
  4937. // C++ [class.union]p2:
  4938. // The member-specification of an anonymous union shall only
  4939. // define non-static data members. [Note: nested types and
  4940. // functions cannot be declared within an anonymous union. ]
  4941. for (auto *Mem : Record->decls()) {
  4942. // Ignore invalid declarations; we already diagnosed them.
  4943. if (Mem->isInvalidDecl())
  4944. continue;
  4945. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4946. // C++ [class.union]p3:
  4947. // An anonymous union shall not have private or protected
  4948. // members (clause 11).
  4949. assert(FD->getAccess() != AS_none);
  4950. if (FD->getAccess() != AS_public) {
  4951. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4952. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4953. Invalid = true;
  4954. }
  4955. // C++ [class.union]p1
  4956. // An object of a class with a non-trivial constructor, a non-trivial
  4957. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4958. // assignment operator cannot be a member of a union, nor can an
  4959. // array of such objects.
  4960. if (CheckNontrivialField(FD))
  4961. Invalid = true;
  4962. } else if (Mem->isImplicit()) {
  4963. // Any implicit members are fine.
  4964. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4965. // This is a type that showed up in an
  4966. // elaborated-type-specifier inside the anonymous struct or
  4967. // union, but which actually declares a type outside of the
  4968. // anonymous struct or union. It's okay.
  4969. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4970. if (!MemRecord->isAnonymousStructOrUnion() &&
  4971. MemRecord->getDeclName()) {
  4972. // Visual C++ allows type definition in anonymous struct or union.
  4973. if (getLangOpts().MicrosoftExt)
  4974. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4975. << Record->isUnion();
  4976. else {
  4977. // This is a nested type declaration.
  4978. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4979. << Record->isUnion();
  4980. Invalid = true;
  4981. }
  4982. } else {
  4983. // This is an anonymous type definition within another anonymous type.
  4984. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4985. // not part of standard C++.
  4986. Diag(MemRecord->getLocation(),
  4987. diag::ext_anonymous_record_with_anonymous_type)
  4988. << Record->isUnion();
  4989. }
  4990. } else if (isa<AccessSpecDecl>(Mem)) {
  4991. // Any access specifier is fine.
  4992. } else if (isa<StaticAssertDecl>(Mem)) {
  4993. // In C++1z, static_assert declarations are also fine.
  4994. } else {
  4995. // We have something that isn't a non-static data
  4996. // member. Complain about it.
  4997. unsigned DK = diag::err_anonymous_record_bad_member;
  4998. if (isa<TypeDecl>(Mem))
  4999. DK = diag::err_anonymous_record_with_type;
  5000. else if (isa<FunctionDecl>(Mem))
  5001. DK = diag::err_anonymous_record_with_function;
  5002. else if (isa<VarDecl>(Mem))
  5003. DK = diag::err_anonymous_record_with_static;
  5004. // Visual C++ allows type definition in anonymous struct or union.
  5005. if (getLangOpts().MicrosoftExt &&
  5006. DK == diag::err_anonymous_record_with_type)
  5007. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  5008. << Record->isUnion();
  5009. else {
  5010. Diag(Mem->getLocation(), DK) << Record->isUnion();
  5011. Invalid = true;
  5012. }
  5013. }
  5014. }
  5015. // C++11 [class.union]p8 (DR1460):
  5016. // At most one variant member of a union may have a
  5017. // brace-or-equal-initializer.
  5018. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  5019. Owner->isRecord())
  5020. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  5021. cast<CXXRecordDecl>(Record));
  5022. }
  5023. if (!Record->isUnion() && !Owner->isRecord()) {
  5024. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  5025. << getLangOpts().CPlusPlus;
  5026. Invalid = true;
  5027. }
  5028. // C++ [dcl.dcl]p3:
  5029. // [If there are no declarators], and except for the declaration of an
  5030. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  5031. // names into the program
  5032. // C++ [class.mem]p2:
  5033. // each such member-declaration shall either declare at least one member
  5034. // name of the class or declare at least one unnamed bit-field
  5035. //
  5036. // For C this is an error even for a named struct, and is diagnosed elsewhere.
  5037. if (getLangOpts().CPlusPlus && Record->field_empty())
  5038. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  5039. // Mock up a declarator.
  5040. Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::Member);
  5041. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  5042. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  5043. // Create a declaration for this anonymous struct/union.
  5044. NamedDecl *Anon = nullptr;
  5045. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  5046. Anon = FieldDecl::Create(
  5047. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  5048. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  5049. /*BitWidth=*/nullptr, /*Mutable=*/false,
  5050. /*InitStyle=*/ICIS_NoInit);
  5051. Anon->setAccess(AS);
  5052. ProcessDeclAttributes(S, Anon, Dc);
  5053. if (getLangOpts().CPlusPlus)
  5054. FieldCollector->Add(cast<FieldDecl>(Anon));
  5055. } else {
  5056. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  5057. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  5058. if (SCSpec == DeclSpec::SCS_mutable) {
  5059. // mutable can only appear on non-static class members, so it's always
  5060. // an error here
  5061. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  5062. Invalid = true;
  5063. SC = SC_None;
  5064. }
  5065. assert(DS.getAttributes().empty() && "No attribute expected");
  5066. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  5067. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  5068. Context.getTypeDeclType(Record), TInfo, SC);
  5069. // Default-initialize the implicit variable. This initialization will be
  5070. // trivial in almost all cases, except if a union member has an in-class
  5071. // initializer:
  5072. // union { int n = 0; };
  5073. ActOnUninitializedDecl(Anon);
  5074. }
  5075. Anon->setImplicit();
  5076. // Mark this as an anonymous struct/union type.
  5077. Record->setAnonymousStructOrUnion(true);
  5078. // Add the anonymous struct/union object to the current
  5079. // context. We'll be referencing this object when we refer to one of
  5080. // its members.
  5081. Owner->addDecl(Anon);
  5082. // Inject the members of the anonymous struct/union into the owning
  5083. // context and into the identifier resolver chain for name lookup
  5084. // purposes.
  5085. SmallVector<NamedDecl*, 2> Chain;
  5086. Chain.push_back(Anon);
  5087. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  5088. Invalid = true;
  5089. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  5090. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  5091. MangleNumberingContext *MCtx;
  5092. Decl *ManglingContextDecl;
  5093. std::tie(MCtx, ManglingContextDecl) =
  5094. getCurrentMangleNumberContext(NewVD->getDeclContext());
  5095. if (MCtx) {
  5096. Context.setManglingNumber(
  5097. NewVD, MCtx->getManglingNumber(
  5098. NewVD, getMSManglingNumber(getLangOpts(), S)));
  5099. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  5100. }
  5101. }
  5102. }
  5103. if (Invalid)
  5104. Anon->setInvalidDecl();
  5105. return Anon;
  5106. }
  5107. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  5108. /// Microsoft C anonymous structure.
  5109. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  5110. /// Example:
  5111. ///
  5112. /// struct A { int a; };
  5113. /// struct B { struct A; int b; };
  5114. ///
  5115. /// void foo() {
  5116. /// B var;
  5117. /// var.a = 3;
  5118. /// }
  5119. ///
  5120. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  5121. RecordDecl *Record) {
  5122. assert(Record && "expected a record!");
  5123. // Mock up a declarator.
  5124. Declarator Dc(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
  5125. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  5126. assert(TInfo && "couldn't build declarator info for anonymous struct");
  5127. auto *ParentDecl = cast<RecordDecl>(CurContext);
  5128. QualType RecTy = Context.getTypeDeclType(Record);
  5129. // Create a declaration for this anonymous struct.
  5130. NamedDecl *Anon =
  5131. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  5132. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  5133. /*BitWidth=*/nullptr, /*Mutable=*/false,
  5134. /*InitStyle=*/ICIS_NoInit);
  5135. Anon->setImplicit();
  5136. // Add the anonymous struct object to the current context.
  5137. CurContext->addDecl(Anon);
  5138. // Inject the members of the anonymous struct into the current
  5139. // context and into the identifier resolver chain for name lookup
  5140. // purposes.
  5141. SmallVector<NamedDecl*, 2> Chain;
  5142. Chain.push_back(Anon);
  5143. RecordDecl *RecordDef = Record->getDefinition();
  5144. if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
  5145. diag::err_field_incomplete_or_sizeless) ||
  5146. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  5147. AS_none, Chain)) {
  5148. Anon->setInvalidDecl();
  5149. ParentDecl->setInvalidDecl();
  5150. }
  5151. return Anon;
  5152. }
  5153. /// GetNameForDeclarator - Determine the full declaration name for the
  5154. /// given Declarator.
  5155. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  5156. return GetNameFromUnqualifiedId(D.getName());
  5157. }
  5158. /// Retrieves the declaration name from a parsed unqualified-id.
  5159. DeclarationNameInfo
  5160. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  5161. DeclarationNameInfo NameInfo;
  5162. NameInfo.setLoc(Name.StartLocation);
  5163. switch (Name.getKind()) {
  5164. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  5165. case UnqualifiedIdKind::IK_Identifier:
  5166. NameInfo.setName(Name.Identifier);
  5167. return NameInfo;
  5168. case UnqualifiedIdKind::IK_DeductionGuideName: {
  5169. // C++ [temp.deduct.guide]p3:
  5170. // The simple-template-id shall name a class template specialization.
  5171. // The template-name shall be the same identifier as the template-name
  5172. // of the simple-template-id.
  5173. // These together intend to imply that the template-name shall name a
  5174. // class template.
  5175. // FIXME: template<typename T> struct X {};
  5176. // template<typename T> using Y = X<T>;
  5177. // Y(int) -> Y<int>;
  5178. // satisfies these rules but does not name a class template.
  5179. TemplateName TN = Name.TemplateName.get().get();
  5180. auto *Template = TN.getAsTemplateDecl();
  5181. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  5182. Diag(Name.StartLocation,
  5183. diag::err_deduction_guide_name_not_class_template)
  5184. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  5185. if (Template)
  5186. Diag(Template->getLocation(), diag::note_template_decl_here);
  5187. return DeclarationNameInfo();
  5188. }
  5189. NameInfo.setName(
  5190. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  5191. return NameInfo;
  5192. }
  5193. case UnqualifiedIdKind::IK_OperatorFunctionId:
  5194. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  5195. Name.OperatorFunctionId.Operator));
  5196. NameInfo.setCXXOperatorNameRange(SourceRange(
  5197. Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
  5198. return NameInfo;
  5199. case UnqualifiedIdKind::IK_LiteralOperatorId:
  5200. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  5201. Name.Identifier));
  5202. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  5203. return NameInfo;
  5204. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  5205. TypeSourceInfo *TInfo;
  5206. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  5207. if (Ty.isNull())
  5208. return DeclarationNameInfo();
  5209. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  5210. Context.getCanonicalType(Ty)));
  5211. NameInfo.setNamedTypeInfo(TInfo);
  5212. return NameInfo;
  5213. }
  5214. case UnqualifiedIdKind::IK_ConstructorName: {
  5215. TypeSourceInfo *TInfo;
  5216. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  5217. if (Ty.isNull())
  5218. return DeclarationNameInfo();
  5219. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  5220. Context.getCanonicalType(Ty)));
  5221. NameInfo.setNamedTypeInfo(TInfo);
  5222. return NameInfo;
  5223. }
  5224. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  5225. // In well-formed code, we can only have a constructor
  5226. // template-id that refers to the current context, so go there
  5227. // to find the actual type being constructed.
  5228. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  5229. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  5230. return DeclarationNameInfo();
  5231. // Determine the type of the class being constructed.
  5232. QualType CurClassType = Context.getTypeDeclType(CurClass);
  5233. // FIXME: Check two things: that the template-id names the same type as
  5234. // CurClassType, and that the template-id does not occur when the name
  5235. // was qualified.
  5236. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  5237. Context.getCanonicalType(CurClassType)));
  5238. // FIXME: should we retrieve TypeSourceInfo?
  5239. NameInfo.setNamedTypeInfo(nullptr);
  5240. return NameInfo;
  5241. }
  5242. case UnqualifiedIdKind::IK_DestructorName: {
  5243. TypeSourceInfo *TInfo;
  5244. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  5245. if (Ty.isNull())
  5246. return DeclarationNameInfo();
  5247. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  5248. Context.getCanonicalType(Ty)));
  5249. NameInfo.setNamedTypeInfo(TInfo);
  5250. return NameInfo;
  5251. }
  5252. case UnqualifiedIdKind::IK_TemplateId: {
  5253. TemplateName TName = Name.TemplateId->Template.get();
  5254. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  5255. return Context.getNameForTemplate(TName, TNameLoc);
  5256. }
  5257. } // switch (Name.getKind())
  5258. llvm_unreachable("Unknown name kind");
  5259. }
  5260. static QualType getCoreType(QualType Ty) {
  5261. do {
  5262. if (Ty->isPointerType() || Ty->isReferenceType())
  5263. Ty = Ty->getPointeeType();
  5264. else if (Ty->isArrayType())
  5265. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  5266. else
  5267. return Ty.withoutLocalFastQualifiers();
  5268. } while (true);
  5269. }
  5270. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  5271. /// and Definition have "nearly" matching parameters. This heuristic is
  5272. /// used to improve diagnostics in the case where an out-of-line function
  5273. /// definition doesn't match any declaration within the class or namespace.
  5274. /// Also sets Params to the list of indices to the parameters that differ
  5275. /// between the declaration and the definition. If hasSimilarParameters
  5276. /// returns true and Params is empty, then all of the parameters match.
  5277. static bool hasSimilarParameters(ASTContext &Context,
  5278. FunctionDecl *Declaration,
  5279. FunctionDecl *Definition,
  5280. SmallVectorImpl<unsigned> &Params) {
  5281. Params.clear();
  5282. if (Declaration->param_size() != Definition->param_size())
  5283. return false;
  5284. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  5285. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  5286. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  5287. // The parameter types are identical
  5288. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  5289. continue;
  5290. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  5291. QualType DefParamBaseTy = getCoreType(DefParamTy);
  5292. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  5293. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  5294. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  5295. (DeclTyName && DeclTyName == DefTyName))
  5296. Params.push_back(Idx);
  5297. else // The two parameters aren't even close
  5298. return false;
  5299. }
  5300. return true;
  5301. }
  5302. /// RebuildDeclaratorInCurrentInstantiation - Checks whether the given
  5303. /// declarator needs to be rebuilt in the current instantiation.
  5304. /// Any bits of declarator which appear before the name are valid for
  5305. /// consideration here. That's specifically the type in the decl spec
  5306. /// and the base type in any member-pointer chunks.
  5307. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  5308. DeclarationName Name) {
  5309. // The types we specifically need to rebuild are:
  5310. // - typenames, typeofs, and decltypes
  5311. // - types which will become injected class names
  5312. // Of course, we also need to rebuild any type referencing such a
  5313. // type. It's safest to just say "dependent", but we call out a
  5314. // few cases here.
  5315. DeclSpec &DS = D.getMutableDeclSpec();
  5316. switch (DS.getTypeSpecType()) {
  5317. case DeclSpec::TST_typename:
  5318. case DeclSpec::TST_typeofType:
  5319. case DeclSpec::TST_typeof_unqualType:
  5320. #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
  5321. #include "clang/Basic/TransformTypeTraits.def"
  5322. case DeclSpec::TST_atomic: {
  5323. // Grab the type from the parser.
  5324. TypeSourceInfo *TSI = nullptr;
  5325. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  5326. if (T.isNull() || !T->isInstantiationDependentType()) break;
  5327. // Make sure there's a type source info. This isn't really much
  5328. // of a waste; most dependent types should have type source info
  5329. // attached already.
  5330. if (!TSI)
  5331. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  5332. // Rebuild the type in the current instantiation.
  5333. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  5334. if (!TSI) return true;
  5335. // Store the new type back in the decl spec.
  5336. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  5337. DS.UpdateTypeRep(LocType);
  5338. break;
  5339. }
  5340. case DeclSpec::TST_decltype:
  5341. case DeclSpec::TST_typeof_unqualExpr:
  5342. case DeclSpec::TST_typeofExpr: {
  5343. Expr *E = DS.getRepAsExpr();
  5344. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  5345. if (Result.isInvalid()) return true;
  5346. DS.UpdateExprRep(Result.get());
  5347. break;
  5348. }
  5349. default:
  5350. // Nothing to do for these decl specs.
  5351. break;
  5352. }
  5353. // It doesn't matter what order we do this in.
  5354. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  5355. DeclaratorChunk &Chunk = D.getTypeObject(I);
  5356. // The only type information in the declarator which can come
  5357. // before the declaration name is the base type of a member
  5358. // pointer.
  5359. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  5360. continue;
  5361. // Rebuild the scope specifier in-place.
  5362. CXXScopeSpec &SS = Chunk.Mem.Scope();
  5363. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  5364. return true;
  5365. }
  5366. return false;
  5367. }
  5368. /// Returns true if the declaration is declared in a system header or from a
  5369. /// system macro.
  5370. static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
  5371. return SM.isInSystemHeader(D->getLocation()) ||
  5372. SM.isInSystemMacro(D->getLocation());
  5373. }
  5374. void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
  5375. // Avoid warning twice on the same identifier, and don't warn on redeclaration
  5376. // of system decl.
  5377. if (D->getPreviousDecl() || D->isImplicit())
  5378. return;
  5379. ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
  5380. if (Status != ReservedIdentifierStatus::NotReserved &&
  5381. !isFromSystemHeader(Context.getSourceManager(), D)) {
  5382. Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
  5383. << D << static_cast<int>(Status);
  5384. }
  5385. }
  5386. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  5387. D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
  5388. // Check if we are in an `omp begin/end declare variant` scope. Handle this
  5389. // declaration only if the `bind_to_declaration` extension is set.
  5390. SmallVector<FunctionDecl *, 4> Bases;
  5391. if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
  5392. if (getOMPTraitInfoForSurroundingScope()->isExtensionActive(llvm::omp::TraitProperty::
  5393. implementation_extension_bind_to_declaration))
  5394. ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
  5395. S, D, MultiTemplateParamsArg(), Bases);
  5396. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  5397. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  5398. Dcl && Dcl->getDeclContext()->isFileContext())
  5399. Dcl->setTopLevelDeclInObjCContainer();
  5400. if (!Bases.empty())
  5401. ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
  5402. return Dcl;
  5403. }
  5404. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  5405. /// If T is the name of a class, then each of the following shall have a
  5406. /// name different from T:
  5407. /// - every static data member of class T;
  5408. /// - every member function of class T
  5409. /// - every member of class T that is itself a type;
  5410. /// \returns true if the declaration name violates these rules.
  5411. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  5412. DeclarationNameInfo NameInfo) {
  5413. DeclarationName Name = NameInfo.getName();
  5414. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  5415. while (Record && Record->isAnonymousStructOrUnion())
  5416. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  5417. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  5418. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  5419. return true;
  5420. }
  5421. return false;
  5422. }
  5423. /// Diagnose a declaration whose declarator-id has the given
  5424. /// nested-name-specifier.
  5425. ///
  5426. /// \param SS The nested-name-specifier of the declarator-id.
  5427. ///
  5428. /// \param DC The declaration context to which the nested-name-specifier
  5429. /// resolves.
  5430. ///
  5431. /// \param Name The name of the entity being declared.
  5432. ///
  5433. /// \param Loc The location of the name of the entity being declared.
  5434. ///
  5435. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  5436. /// we're declaring an explicit / partial specialization / instantiation.
  5437. ///
  5438. /// \returns true if we cannot safely recover from this error, false otherwise.
  5439. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  5440. DeclarationName Name,
  5441. SourceLocation Loc, bool IsTemplateId) {
  5442. DeclContext *Cur = CurContext;
  5443. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  5444. Cur = Cur->getParent();
  5445. // If the user provided a superfluous scope specifier that refers back to the
  5446. // class in which the entity is already declared, diagnose and ignore it.
  5447. //
  5448. // class X {
  5449. // void X::f();
  5450. // };
  5451. //
  5452. // Note, it was once ill-formed to give redundant qualification in all
  5453. // contexts, but that rule was removed by DR482.
  5454. if (Cur->Equals(DC)) {
  5455. if (Cur->isRecord()) {
  5456. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  5457. : diag::err_member_extra_qualification)
  5458. << Name << FixItHint::CreateRemoval(SS.getRange());
  5459. SS.clear();
  5460. } else {
  5461. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  5462. }
  5463. return false;
  5464. }
  5465. // Check whether the qualifying scope encloses the scope of the original
  5466. // declaration. For a template-id, we perform the checks in
  5467. // CheckTemplateSpecializationScope.
  5468. if (!Cur->Encloses(DC) && !IsTemplateId) {
  5469. if (Cur->isRecord())
  5470. Diag(Loc, diag::err_member_qualification)
  5471. << Name << SS.getRange();
  5472. else if (isa<TranslationUnitDecl>(DC))
  5473. Diag(Loc, diag::err_invalid_declarator_global_scope)
  5474. << Name << SS.getRange();
  5475. else if (isa<FunctionDecl>(Cur))
  5476. Diag(Loc, diag::err_invalid_declarator_in_function)
  5477. << Name << SS.getRange();
  5478. else if (isa<BlockDecl>(Cur))
  5479. Diag(Loc, diag::err_invalid_declarator_in_block)
  5480. << Name << SS.getRange();
  5481. else if (isa<ExportDecl>(Cur)) {
  5482. if (!isa<NamespaceDecl>(DC))
  5483. Diag(Loc, diag::err_export_non_namespace_scope_name)
  5484. << Name << SS.getRange();
  5485. else
  5486. // The cases that DC is not NamespaceDecl should be handled in
  5487. // CheckRedeclarationExported.
  5488. return false;
  5489. } else
  5490. Diag(Loc, diag::err_invalid_declarator_scope)
  5491. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  5492. return true;
  5493. }
  5494. if (Cur->isRecord()) {
  5495. // Cannot qualify members within a class.
  5496. Diag(Loc, diag::err_member_qualification)
  5497. << Name << SS.getRange();
  5498. SS.clear();
  5499. // C++ constructors and destructors with incorrect scopes can break
  5500. // our AST invariants by having the wrong underlying types. If
  5501. // that's the case, then drop this declaration entirely.
  5502. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  5503. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  5504. !Context.hasSameType(Name.getCXXNameType(),
  5505. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  5506. return true;
  5507. return false;
  5508. }
  5509. // C++11 [dcl.meaning]p1:
  5510. // [...] "The nested-name-specifier of the qualified declarator-id shall
  5511. // not begin with a decltype-specifer"
  5512. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  5513. while (SpecLoc.getPrefix())
  5514. SpecLoc = SpecLoc.getPrefix();
  5515. if (isa_and_nonnull<DecltypeType>(
  5516. SpecLoc.getNestedNameSpecifier()->getAsType()))
  5517. Diag(Loc, diag::err_decltype_in_declarator)
  5518. << SpecLoc.getTypeLoc().getSourceRange();
  5519. return false;
  5520. }
  5521. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  5522. MultiTemplateParamsArg TemplateParamLists) {
  5523. // TODO: consider using NameInfo for diagnostic.
  5524. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  5525. DeclarationName Name = NameInfo.getName();
  5526. // All of these full declarators require an identifier. If it doesn't have
  5527. // one, the ParsedFreeStandingDeclSpec action should be used.
  5528. if (D.isDecompositionDeclarator()) {
  5529. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  5530. } else if (!Name) {
  5531. if (!D.isInvalidType()) // Reject this if we think it is valid.
  5532. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  5533. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  5534. return nullptr;
  5535. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  5536. return nullptr;
  5537. // The scope passed in may not be a decl scope. Zip up the scope tree until
  5538. // we find one that is.
  5539. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  5540. (S->getFlags() & Scope::TemplateParamScope) != 0)
  5541. S = S->getParent();
  5542. DeclContext *DC = CurContext;
  5543. if (D.getCXXScopeSpec().isInvalid())
  5544. D.setInvalidType();
  5545. else if (D.getCXXScopeSpec().isSet()) {
  5546. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  5547. UPPC_DeclarationQualifier))
  5548. return nullptr;
  5549. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  5550. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  5551. if (!DC || isa<EnumDecl>(DC)) {
  5552. // If we could not compute the declaration context, it's because the
  5553. // declaration context is dependent but does not refer to a class,
  5554. // class template, or class template partial specialization. Complain
  5555. // and return early, to avoid the coming semantic disaster.
  5556. Diag(D.getIdentifierLoc(),
  5557. diag::err_template_qualified_declarator_no_match)
  5558. << D.getCXXScopeSpec().getScopeRep()
  5559. << D.getCXXScopeSpec().getRange();
  5560. return nullptr;
  5561. }
  5562. bool IsDependentContext = DC->isDependentContext();
  5563. if (!IsDependentContext &&
  5564. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  5565. return nullptr;
  5566. // If a class is incomplete, do not parse entities inside it.
  5567. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  5568. Diag(D.getIdentifierLoc(),
  5569. diag::err_member_def_undefined_record)
  5570. << Name << DC << D.getCXXScopeSpec().getRange();
  5571. return nullptr;
  5572. }
  5573. if (!D.getDeclSpec().isFriendSpecified()) {
  5574. if (diagnoseQualifiedDeclaration(
  5575. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  5576. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  5577. if (DC->isRecord())
  5578. return nullptr;
  5579. D.setInvalidType();
  5580. }
  5581. }
  5582. // Check whether we need to rebuild the type of the given
  5583. // declaration in the current instantiation.
  5584. if (EnteringContext && IsDependentContext &&
  5585. TemplateParamLists.size() != 0) {
  5586. ContextRAII SavedContext(*this, DC);
  5587. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  5588. D.setInvalidType();
  5589. }
  5590. }
  5591. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5592. QualType R = TInfo->getType();
  5593. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  5594. UPPC_DeclarationType))
  5595. D.setInvalidType();
  5596. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  5597. forRedeclarationInCurContext());
  5598. // See if this is a redefinition of a variable in the same scope.
  5599. if (!D.getCXXScopeSpec().isSet()) {
  5600. bool IsLinkageLookup = false;
  5601. bool CreateBuiltins = false;
  5602. // If the declaration we're planning to build will be a function
  5603. // or object with linkage, then look for another declaration with
  5604. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  5605. //
  5606. // If the declaration we're planning to build will be declared with
  5607. // external linkage in the translation unit, create any builtin with
  5608. // the same name.
  5609. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  5610. /* Do nothing*/;
  5611. else if (CurContext->isFunctionOrMethod() &&
  5612. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  5613. R->isFunctionType())) {
  5614. IsLinkageLookup = true;
  5615. CreateBuiltins =
  5616. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  5617. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  5618. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  5619. CreateBuiltins = true;
  5620. if (IsLinkageLookup) {
  5621. Previous.clear(LookupRedeclarationWithLinkage);
  5622. Previous.setRedeclarationKind(ForExternalRedeclaration);
  5623. }
  5624. LookupName(Previous, S, CreateBuiltins);
  5625. } else { // Something like "int foo::x;"
  5626. LookupQualifiedName(Previous, DC);
  5627. // C++ [dcl.meaning]p1:
  5628. // When the declarator-id is qualified, the declaration shall refer to a
  5629. // previously declared member of the class or namespace to which the
  5630. // qualifier refers (or, in the case of a namespace, of an element of the
  5631. // inline namespace set of that namespace (7.3.1)) or to a specialization
  5632. // thereof; [...]
  5633. //
  5634. // Note that we already checked the context above, and that we do not have
  5635. // enough information to make sure that Previous contains the declaration
  5636. // we want to match. For example, given:
  5637. //
  5638. // class X {
  5639. // void f();
  5640. // void f(float);
  5641. // };
  5642. //
  5643. // void X::f(int) { } // ill-formed
  5644. //
  5645. // In this case, Previous will point to the overload set
  5646. // containing the two f's declared in X, but neither of them
  5647. // matches.
  5648. // C++ [dcl.meaning]p1:
  5649. // [...] the member shall not merely have been introduced by a
  5650. // using-declaration in the scope of the class or namespace nominated by
  5651. // the nested-name-specifier of the declarator-id.
  5652. RemoveUsingDecls(Previous);
  5653. }
  5654. if (Previous.isSingleResult() &&
  5655. Previous.getFoundDecl()->isTemplateParameter()) {
  5656. // Maybe we will complain about the shadowed template parameter.
  5657. if (!D.isInvalidType())
  5658. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  5659. Previous.getFoundDecl());
  5660. // Just pretend that we didn't see the previous declaration.
  5661. Previous.clear();
  5662. }
  5663. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  5664. // Forget that the previous declaration is the injected-class-name.
  5665. Previous.clear();
  5666. // In C++, the previous declaration we find might be a tag type
  5667. // (class or enum). In this case, the new declaration will hide the
  5668. // tag type. Note that this applies to functions, function templates, and
  5669. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  5670. if (Previous.isSingleTagDecl() &&
  5671. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  5672. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  5673. Previous.clear();
  5674. // Check that there are no default arguments other than in the parameters
  5675. // of a function declaration (C++ only).
  5676. if (getLangOpts().CPlusPlus)
  5677. CheckExtraCXXDefaultArguments(D);
  5678. NamedDecl *New;
  5679. bool AddToScope = true;
  5680. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  5681. if (TemplateParamLists.size()) {
  5682. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  5683. return nullptr;
  5684. }
  5685. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  5686. } else if (R->isFunctionType()) {
  5687. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  5688. TemplateParamLists,
  5689. AddToScope);
  5690. } else {
  5691. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  5692. AddToScope);
  5693. }
  5694. if (!New)
  5695. return nullptr;
  5696. // If this has an identifier and is not a function template specialization,
  5697. // add it to the scope stack.
  5698. if (New->getDeclName() && AddToScope)
  5699. PushOnScopeChains(New, S);
  5700. if (isInOpenMPDeclareTargetContext())
  5701. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  5702. return New;
  5703. }
  5704. /// Helper method to turn variable array types into constant array
  5705. /// types in certain situations which would otherwise be errors (for
  5706. /// GCC compatibility).
  5707. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  5708. ASTContext &Context,
  5709. bool &SizeIsNegative,
  5710. llvm::APSInt &Oversized) {
  5711. // This method tries to turn a variable array into a constant
  5712. // array even when the size isn't an ICE. This is necessary
  5713. // for compatibility with code that depends on gcc's buggy
  5714. // constant expression folding, like struct {char x[(int)(char*)2];}
  5715. SizeIsNegative = false;
  5716. Oversized = 0;
  5717. if (T->isDependentType())
  5718. return QualType();
  5719. QualifierCollector Qs;
  5720. const Type *Ty = Qs.strip(T);
  5721. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  5722. QualType Pointee = PTy->getPointeeType();
  5723. QualType FixedType =
  5724. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  5725. Oversized);
  5726. if (FixedType.isNull()) return FixedType;
  5727. FixedType = Context.getPointerType(FixedType);
  5728. return Qs.apply(Context, FixedType);
  5729. }
  5730. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  5731. QualType Inner = PTy->getInnerType();
  5732. QualType FixedType =
  5733. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  5734. Oversized);
  5735. if (FixedType.isNull()) return FixedType;
  5736. FixedType = Context.getParenType(FixedType);
  5737. return Qs.apply(Context, FixedType);
  5738. }
  5739. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  5740. if (!VLATy)
  5741. return QualType();
  5742. QualType ElemTy = VLATy->getElementType();
  5743. if (ElemTy->isVariablyModifiedType()) {
  5744. ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
  5745. SizeIsNegative, Oversized);
  5746. if (ElemTy.isNull())
  5747. return QualType();
  5748. }
  5749. Expr::EvalResult Result;
  5750. if (!VLATy->getSizeExpr() ||
  5751. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  5752. return QualType();
  5753. llvm::APSInt Res = Result.Val.getInt();
  5754. // Check whether the array size is negative.
  5755. if (Res.isSigned() && Res.isNegative()) {
  5756. SizeIsNegative = true;
  5757. return QualType();
  5758. }
  5759. // Check whether the array is too large to be addressed.
  5760. unsigned ActiveSizeBits =
  5761. (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
  5762. !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
  5763. ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
  5764. : Res.getActiveBits();
  5765. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  5766. Oversized = Res;
  5767. return QualType();
  5768. }
  5769. QualType FoldedArrayType = Context.getConstantArrayType(
  5770. ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
  5771. return Qs.apply(Context, FoldedArrayType);
  5772. }
  5773. static void
  5774. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  5775. SrcTL = SrcTL.getUnqualifiedLoc();
  5776. DstTL = DstTL.getUnqualifiedLoc();
  5777. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  5778. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  5779. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  5780. DstPTL.getPointeeLoc());
  5781. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  5782. return;
  5783. }
  5784. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  5785. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  5786. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  5787. DstPTL.getInnerLoc());
  5788. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  5789. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  5790. return;
  5791. }
  5792. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  5793. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  5794. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  5795. TypeLoc DstElemTL = DstATL.getElementLoc();
  5796. if (VariableArrayTypeLoc SrcElemATL =
  5797. SrcElemTL.getAs<VariableArrayTypeLoc>()) {
  5798. ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
  5799. FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
  5800. } else {
  5801. DstElemTL.initializeFullCopy(SrcElemTL);
  5802. }
  5803. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  5804. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  5805. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  5806. }
  5807. /// Helper method to turn variable array types into constant array
  5808. /// types in certain situations which would otherwise be errors (for
  5809. /// GCC compatibility).
  5810. static TypeSourceInfo*
  5811. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  5812. ASTContext &Context,
  5813. bool &SizeIsNegative,
  5814. llvm::APSInt &Oversized) {
  5815. QualType FixedTy
  5816. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  5817. SizeIsNegative, Oversized);
  5818. if (FixedTy.isNull())
  5819. return nullptr;
  5820. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5821. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5822. FixedTInfo->getTypeLoc());
  5823. return FixedTInfo;
  5824. }
  5825. /// Attempt to fold a variable-sized type to a constant-sized type, returning
  5826. /// true if we were successful.
  5827. bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
  5828. QualType &T, SourceLocation Loc,
  5829. unsigned FailedFoldDiagID) {
  5830. bool SizeIsNegative;
  5831. llvm::APSInt Oversized;
  5832. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  5833. TInfo, Context, SizeIsNegative, Oversized);
  5834. if (FixedTInfo) {
  5835. Diag(Loc, diag::ext_vla_folded_to_constant);
  5836. TInfo = FixedTInfo;
  5837. T = FixedTInfo->getType();
  5838. return true;
  5839. }
  5840. if (SizeIsNegative)
  5841. Diag(Loc, diag::err_typecheck_negative_array_size);
  5842. else if (Oversized.getBoolValue())
  5843. Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
  5844. else if (FailedFoldDiagID)
  5845. Diag(Loc, FailedFoldDiagID);
  5846. return false;
  5847. }
  5848. /// Register the given locally-scoped extern "C" declaration so
  5849. /// that it can be found later for redeclarations. We include any extern "C"
  5850. /// declaration that is not visible in the translation unit here, not just
  5851. /// function-scope declarations.
  5852. void
  5853. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5854. if (!getLangOpts().CPlusPlus &&
  5855. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5856. // Don't need to track declarations in the TU in C.
  5857. return;
  5858. // Note that we have a locally-scoped external with this name.
  5859. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5860. }
  5861. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5862. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5863. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5864. return Result.empty() ? nullptr : *Result.begin();
  5865. }
  5866. /// Diagnose function specifiers on a declaration of an identifier that
  5867. /// does not identify a function.
  5868. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5869. // FIXME: We should probably indicate the identifier in question to avoid
  5870. // confusion for constructs like "virtual int a(), b;"
  5871. if (DS.isVirtualSpecified())
  5872. Diag(DS.getVirtualSpecLoc(),
  5873. diag::err_virtual_non_function);
  5874. if (DS.hasExplicitSpecifier())
  5875. Diag(DS.getExplicitSpecLoc(),
  5876. diag::err_explicit_non_function);
  5877. if (DS.isNoreturnSpecified())
  5878. Diag(DS.getNoreturnSpecLoc(),
  5879. diag::err_noreturn_non_function);
  5880. }
  5881. NamedDecl*
  5882. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5883. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5884. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5885. if (D.getCXXScopeSpec().isSet()) {
  5886. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5887. << D.getCXXScopeSpec().getRange();
  5888. D.setInvalidType();
  5889. // Pretend we didn't see the scope specifier.
  5890. DC = CurContext;
  5891. Previous.clear();
  5892. }
  5893. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5894. if (D.getDeclSpec().isInlineSpecified())
  5895. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5896. << getLangOpts().CPlusPlus17;
  5897. if (D.getDeclSpec().hasConstexprSpecifier())
  5898. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5899. << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  5900. if (D.getName().getKind() != UnqualifiedIdKind::IK_Identifier) {
  5901. if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
  5902. Diag(D.getName().StartLocation,
  5903. diag::err_deduction_guide_invalid_specifier)
  5904. << "typedef";
  5905. else
  5906. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5907. << D.getName().getSourceRange();
  5908. return nullptr;
  5909. }
  5910. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5911. if (!NewTD) return nullptr;
  5912. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5913. ProcessDeclAttributes(S, NewTD, D);
  5914. CheckTypedefForVariablyModifiedType(S, NewTD);
  5915. bool Redeclaration = D.isRedeclaration();
  5916. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5917. D.setRedeclaration(Redeclaration);
  5918. return ND;
  5919. }
  5920. void
  5921. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5922. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5923. // then it shall have block scope.
  5924. // Note that variably modified types must be fixed before merging the decl so
  5925. // that redeclarations will match.
  5926. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5927. QualType T = TInfo->getType();
  5928. if (T->isVariablyModifiedType()) {
  5929. setFunctionHasBranchProtectedScope();
  5930. if (S->getFnParent() == nullptr) {
  5931. bool SizeIsNegative;
  5932. llvm::APSInt Oversized;
  5933. TypeSourceInfo *FixedTInfo =
  5934. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5935. SizeIsNegative,
  5936. Oversized);
  5937. if (FixedTInfo) {
  5938. Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
  5939. NewTD->setTypeSourceInfo(FixedTInfo);
  5940. } else {
  5941. if (SizeIsNegative)
  5942. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5943. else if (T->isVariableArrayType())
  5944. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5945. else if (Oversized.getBoolValue())
  5946. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5947. << toString(Oversized, 10);
  5948. else
  5949. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5950. NewTD->setInvalidDecl();
  5951. }
  5952. }
  5953. }
  5954. }
  5955. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5956. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5957. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5958. NamedDecl*
  5959. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5960. LookupResult &Previous, bool &Redeclaration) {
  5961. // Find the shadowed declaration before filtering for scope.
  5962. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5963. // Merge the decl with the existing one if appropriate. If the decl is
  5964. // in an outer scope, it isn't the same thing.
  5965. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5966. /*AllowInlineNamespace*/false);
  5967. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5968. if (!Previous.empty()) {
  5969. Redeclaration = true;
  5970. MergeTypedefNameDecl(S, NewTD, Previous);
  5971. } else {
  5972. inferGslPointerAttribute(NewTD);
  5973. }
  5974. if (ShadowedDecl && !Redeclaration)
  5975. CheckShadow(NewTD, ShadowedDecl, Previous);
  5976. // If this is the C FILE type, notify the AST context.
  5977. if (IdentifierInfo *II = NewTD->getIdentifier())
  5978. if (!NewTD->isInvalidDecl() &&
  5979. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5980. if (II->isStr("FILE"))
  5981. Context.setFILEDecl(NewTD);
  5982. else if (II->isStr("jmp_buf"))
  5983. Context.setjmp_bufDecl(NewTD);
  5984. else if (II->isStr("sigjmp_buf"))
  5985. Context.setsigjmp_bufDecl(NewTD);
  5986. else if (II->isStr("ucontext_t"))
  5987. Context.setucontext_tDecl(NewTD);
  5988. }
  5989. return NewTD;
  5990. }
  5991. /// Determines whether the given declaration is an out-of-scope
  5992. /// previous declaration.
  5993. ///
  5994. /// This routine should be invoked when name lookup has found a
  5995. /// previous declaration (PrevDecl) that is not in the scope where a
  5996. /// new declaration by the same name is being introduced. If the new
  5997. /// declaration occurs in a local scope, previous declarations with
  5998. /// linkage may still be considered previous declarations (C99
  5999. /// 6.2.2p4-5, C++ [basic.link]p6).
  6000. ///
  6001. /// \param PrevDecl the previous declaration found by name
  6002. /// lookup
  6003. ///
  6004. /// \param DC the context in which the new declaration is being
  6005. /// declared.
  6006. ///
  6007. /// \returns true if PrevDecl is an out-of-scope previous declaration
  6008. /// for a new delcaration with the same name.
  6009. static bool
  6010. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  6011. ASTContext &Context) {
  6012. if (!PrevDecl)
  6013. return false;
  6014. if (!PrevDecl->hasLinkage())
  6015. return false;
  6016. if (Context.getLangOpts().CPlusPlus) {
  6017. // C++ [basic.link]p6:
  6018. // If there is a visible declaration of an entity with linkage
  6019. // having the same name and type, ignoring entities declared
  6020. // outside the innermost enclosing namespace scope, the block
  6021. // scope declaration declares that same entity and receives the
  6022. // linkage of the previous declaration.
  6023. DeclContext *OuterContext = DC->getRedeclContext();
  6024. if (!OuterContext->isFunctionOrMethod())
  6025. // This rule only applies to block-scope declarations.
  6026. return false;
  6027. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  6028. if (PrevOuterContext->isRecord())
  6029. // We found a member function: ignore it.
  6030. return false;
  6031. // Find the innermost enclosing namespace for the new and
  6032. // previous declarations.
  6033. OuterContext = OuterContext->getEnclosingNamespaceContext();
  6034. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  6035. // The previous declaration is in a different namespace, so it
  6036. // isn't the same function.
  6037. if (!OuterContext->Equals(PrevOuterContext))
  6038. return false;
  6039. }
  6040. return true;
  6041. }
  6042. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  6043. CXXScopeSpec &SS = D.getCXXScopeSpec();
  6044. if (!SS.isSet()) return;
  6045. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  6046. }
  6047. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  6048. QualType type = decl->getType();
  6049. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  6050. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  6051. // Various kinds of declaration aren't allowed to be __autoreleasing.
  6052. unsigned kind = -1U;
  6053. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  6054. if (var->hasAttr<BlocksAttr>())
  6055. kind = 0; // __block
  6056. else if (!var->hasLocalStorage())
  6057. kind = 1; // global
  6058. } else if (isa<ObjCIvarDecl>(decl)) {
  6059. kind = 3; // ivar
  6060. } else if (isa<FieldDecl>(decl)) {
  6061. kind = 2; // field
  6062. }
  6063. if (kind != -1U) {
  6064. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  6065. << kind;
  6066. }
  6067. } else if (lifetime == Qualifiers::OCL_None) {
  6068. // Try to infer lifetime.
  6069. if (!type->isObjCLifetimeType())
  6070. return false;
  6071. lifetime = type->getObjCARCImplicitLifetime();
  6072. type = Context.getLifetimeQualifiedType(type, lifetime);
  6073. decl->setType(type);
  6074. }
  6075. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  6076. // Thread-local variables cannot have lifetime.
  6077. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  6078. var->getTLSKind()) {
  6079. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  6080. << var->getType();
  6081. return true;
  6082. }
  6083. }
  6084. return false;
  6085. }
  6086. void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
  6087. if (Decl->getType().hasAddressSpace())
  6088. return;
  6089. if (Decl->getType()->isDependentType())
  6090. return;
  6091. if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
  6092. QualType Type = Var->getType();
  6093. if (Type->isSamplerT() || Type->isVoidType())
  6094. return;
  6095. LangAS ImplAS = LangAS::opencl_private;
  6096. // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
  6097. // __opencl_c_program_scope_global_variables feature, the address space
  6098. // for a variable at program scope or a static or extern variable inside
  6099. // a function are inferred to be __global.
  6100. if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
  6101. Var->hasGlobalStorage())
  6102. ImplAS = LangAS::opencl_global;
  6103. // If the original type from a decayed type is an array type and that array
  6104. // type has no address space yet, deduce it now.
  6105. if (auto DT = dyn_cast<DecayedType>(Type)) {
  6106. auto OrigTy = DT->getOriginalType();
  6107. if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
  6108. // Add the address space to the original array type and then propagate
  6109. // that to the element type through `getAsArrayType`.
  6110. OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
  6111. OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
  6112. // Re-generate the decayed type.
  6113. Type = Context.getDecayedType(OrigTy);
  6114. }
  6115. }
  6116. Type = Context.getAddrSpaceQualType(Type, ImplAS);
  6117. // Apply any qualifiers (including address space) from the array type to
  6118. // the element type. This implements C99 6.7.3p8: "If the specification of
  6119. // an array type includes any type qualifiers, the element type is so
  6120. // qualified, not the array type."
  6121. if (Type->isArrayType())
  6122. Type = QualType(Context.getAsArrayType(Type), 0);
  6123. Decl->setType(Type);
  6124. }
  6125. }
  6126. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  6127. // Ensure that an auto decl is deduced otherwise the checks below might cache
  6128. // the wrong linkage.
  6129. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  6130. // 'weak' only applies to declarations with external linkage.
  6131. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  6132. if (!ND.isExternallyVisible()) {
  6133. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  6134. ND.dropAttr<WeakAttr>();
  6135. }
  6136. }
  6137. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  6138. if (ND.isExternallyVisible()) {
  6139. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  6140. ND.dropAttr<WeakRefAttr>();
  6141. ND.dropAttr<AliasAttr>();
  6142. }
  6143. }
  6144. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  6145. if (VD->hasInit()) {
  6146. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  6147. assert(VD->isThisDeclarationADefinition() &&
  6148. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  6149. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  6150. VD->dropAttr<AliasAttr>();
  6151. }
  6152. }
  6153. }
  6154. // 'selectany' only applies to externally visible variable declarations.
  6155. // It does not apply to functions.
  6156. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  6157. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  6158. S.Diag(Attr->getLocation(),
  6159. diag::err_attribute_selectany_non_extern_data);
  6160. ND.dropAttr<SelectAnyAttr>();
  6161. }
  6162. }
  6163. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  6164. auto *VD = dyn_cast<VarDecl>(&ND);
  6165. bool IsAnonymousNS = false;
  6166. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  6167. if (VD) {
  6168. const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
  6169. while (NS && !IsAnonymousNS) {
  6170. IsAnonymousNS = NS->isAnonymousNamespace();
  6171. NS = dyn_cast<NamespaceDecl>(NS->getParent());
  6172. }
  6173. }
  6174. // dll attributes require external linkage. Static locals may have external
  6175. // linkage but still cannot be explicitly imported or exported.
  6176. // In Microsoft mode, a variable defined in anonymous namespace must have
  6177. // external linkage in order to be exported.
  6178. bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
  6179. if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
  6180. (!AnonNSInMicrosoftMode &&
  6181. (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
  6182. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  6183. << &ND << Attr;
  6184. ND.setInvalidDecl();
  6185. }
  6186. }
  6187. // Check the attributes on the function type, if any.
  6188. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  6189. // Don't declare this variable in the second operand of the for-statement;
  6190. // GCC miscompiles that by ending its lifetime before evaluating the
  6191. // third operand. See gcc.gnu.org/PR86769.
  6192. AttributedTypeLoc ATL;
  6193. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  6194. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  6195. TL = ATL.getModifiedLoc()) {
  6196. // The [[lifetimebound]] attribute can be applied to the implicit object
  6197. // parameter of a non-static member function (other than a ctor or dtor)
  6198. // by applying it to the function type.
  6199. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  6200. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  6201. if (!MD || MD->isStatic()) {
  6202. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  6203. << !MD << A->getRange();
  6204. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  6205. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  6206. << isa<CXXDestructorDecl>(MD) << A->getRange();
  6207. }
  6208. }
  6209. }
  6210. }
  6211. }
  6212. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  6213. NamedDecl *NewDecl,
  6214. bool IsSpecialization,
  6215. bool IsDefinition) {
  6216. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  6217. return;
  6218. bool IsTemplate = false;
  6219. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  6220. OldDecl = OldTD->getTemplatedDecl();
  6221. IsTemplate = true;
  6222. if (!IsSpecialization)
  6223. IsDefinition = false;
  6224. }
  6225. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  6226. NewDecl = NewTD->getTemplatedDecl();
  6227. IsTemplate = true;
  6228. }
  6229. if (!OldDecl || !NewDecl)
  6230. return;
  6231. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  6232. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  6233. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  6234. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  6235. // dllimport and dllexport are inheritable attributes so we have to exclude
  6236. // inherited attribute instances.
  6237. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  6238. (NewExportAttr && !NewExportAttr->isInherited());
  6239. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  6240. // the only exception being explicit specializations.
  6241. // Implicitly generated declarations are also excluded for now because there
  6242. // is no other way to switch these to use dllimport or dllexport.
  6243. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  6244. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  6245. // Allow with a warning for free functions and global variables.
  6246. bool JustWarn = false;
  6247. if (!OldDecl->isCXXClassMember()) {
  6248. auto *VD = dyn_cast<VarDecl>(OldDecl);
  6249. if (VD && !VD->getDescribedVarTemplate())
  6250. JustWarn = true;
  6251. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  6252. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  6253. JustWarn = true;
  6254. }
  6255. // We cannot change a declaration that's been used because IR has already
  6256. // been emitted. Dllimported functions will still work though (modulo
  6257. // address equality) as they can use the thunk.
  6258. if (OldDecl->isUsed())
  6259. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  6260. JustWarn = false;
  6261. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  6262. : diag::err_attribute_dll_redeclaration;
  6263. S.Diag(NewDecl->getLocation(), DiagID)
  6264. << NewDecl
  6265. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  6266. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  6267. if (!JustWarn) {
  6268. NewDecl->setInvalidDecl();
  6269. return;
  6270. }
  6271. }
  6272. // A redeclaration is not allowed to drop a dllimport attribute, the only
  6273. // exceptions being inline function definitions (except for function
  6274. // templates), local extern declarations, qualified friend declarations or
  6275. // special MSVC extension: in the last case, the declaration is treated as if
  6276. // it were marked dllexport.
  6277. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  6278. bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
  6279. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  6280. // Ignore static data because out-of-line definitions are diagnosed
  6281. // separately.
  6282. IsStaticDataMember = VD->isStaticDataMember();
  6283. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  6284. VarDecl::DeclarationOnly;
  6285. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  6286. IsInline = FD->isInlined();
  6287. IsQualifiedFriend = FD->getQualifier() &&
  6288. FD->getFriendObjectKind() == Decl::FOK_Declared;
  6289. }
  6290. if (OldImportAttr && !HasNewAttr &&
  6291. (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
  6292. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  6293. if (IsMicrosoftABI && IsDefinition) {
  6294. if (IsSpecialization) {
  6295. S.Diag(
  6296. NewDecl->getLocation(),
  6297. diag::err_attribute_dllimport_function_specialization_definition);
  6298. S.Diag(OldImportAttr->getLocation(), diag::note_attribute);
  6299. NewDecl->dropAttr<DLLImportAttr>();
  6300. } else {
  6301. S.Diag(NewDecl->getLocation(),
  6302. diag::warn_redeclaration_without_import_attribute)
  6303. << NewDecl;
  6304. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  6305. NewDecl->dropAttr<DLLImportAttr>();
  6306. NewDecl->addAttr(DLLExportAttr::CreateImplicit(
  6307. S.Context, NewImportAttr->getRange()));
  6308. }
  6309. } else if (IsMicrosoftABI && IsSpecialization) {
  6310. assert(!IsDefinition);
  6311. // MSVC allows this. Keep the inherited attribute.
  6312. } else {
  6313. S.Diag(NewDecl->getLocation(),
  6314. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  6315. << NewDecl << OldImportAttr;
  6316. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  6317. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  6318. OldDecl->dropAttr<DLLImportAttr>();
  6319. NewDecl->dropAttr<DLLImportAttr>();
  6320. }
  6321. } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
  6322. // In MinGW, seeing a function declared inline drops the dllimport
  6323. // attribute.
  6324. OldDecl->dropAttr<DLLImportAttr>();
  6325. NewDecl->dropAttr<DLLImportAttr>();
  6326. S.Diag(NewDecl->getLocation(),
  6327. diag::warn_dllimport_dropped_from_inline_function)
  6328. << NewDecl << OldImportAttr;
  6329. }
  6330. // A specialization of a class template member function is processed here
  6331. // since it's a redeclaration. If the parent class is dllexport, the
  6332. // specialization inherits that attribute. This doesn't happen automatically
  6333. // since the parent class isn't instantiated until later.
  6334. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  6335. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  6336. !NewImportAttr && !NewExportAttr) {
  6337. if (const DLLExportAttr *ParentExportAttr =
  6338. MD->getParent()->getAttr<DLLExportAttr>()) {
  6339. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  6340. NewAttr->setInherited(true);
  6341. NewDecl->addAttr(NewAttr);
  6342. }
  6343. }
  6344. }
  6345. }
  6346. /// Given that we are within the definition of the given function,
  6347. /// will that definition behave like C99's 'inline', where the
  6348. /// definition is discarded except for optimization purposes?
  6349. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  6350. // Try to avoid calling GetGVALinkageForFunction.
  6351. // All cases of this require the 'inline' keyword.
  6352. if (!FD->isInlined()) return false;
  6353. // This is only possible in C++ with the gnu_inline attribute.
  6354. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  6355. return false;
  6356. // Okay, go ahead and call the relatively-more-expensive function.
  6357. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  6358. }
  6359. /// Determine whether a variable is extern "C" prior to attaching
  6360. /// an initializer. We can't just call isExternC() here, because that
  6361. /// will also compute and cache whether the declaration is externally
  6362. /// visible, which might change when we attach the initializer.
  6363. ///
  6364. /// This can only be used if the declaration is known to not be a
  6365. /// redeclaration of an internal linkage declaration.
  6366. ///
  6367. /// For instance:
  6368. ///
  6369. /// auto x = []{};
  6370. ///
  6371. /// Attaching the initializer here makes this declaration not externally
  6372. /// visible, because its type has internal linkage.
  6373. ///
  6374. /// FIXME: This is a hack.
  6375. template<typename T>
  6376. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  6377. if (S.getLangOpts().CPlusPlus) {
  6378. // In C++, the overloadable attribute negates the effects of extern "C".
  6379. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  6380. return false;
  6381. // So do CUDA's host/device attributes.
  6382. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  6383. D->template hasAttr<CUDAHostAttr>()))
  6384. return false;
  6385. }
  6386. return D->isExternC();
  6387. }
  6388. static bool shouldConsiderLinkage(const VarDecl *VD) {
  6389. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  6390. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  6391. isa<OMPDeclareMapperDecl>(DC))
  6392. return VD->hasExternalStorage();
  6393. if (DC->isFileContext())
  6394. return true;
  6395. if (DC->isRecord())
  6396. return false;
  6397. if (DC->getDeclKind() == Decl::HLSLBuffer)
  6398. return false;
  6399. if (isa<RequiresExprBodyDecl>(DC))
  6400. return false;
  6401. llvm_unreachable("Unexpected context");
  6402. }
  6403. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  6404. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  6405. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  6406. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  6407. return true;
  6408. if (DC->isRecord())
  6409. return false;
  6410. llvm_unreachable("Unexpected context");
  6411. }
  6412. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  6413. ParsedAttr::Kind Kind) {
  6414. // Check decl attributes on the DeclSpec.
  6415. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  6416. return true;
  6417. // Walk the declarator structure, checking decl attributes that were in a type
  6418. // position to the decl itself.
  6419. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  6420. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  6421. return true;
  6422. }
  6423. // Finally, check attributes on the decl itself.
  6424. return PD.getAttributes().hasAttribute(Kind) ||
  6425. PD.getDeclarationAttributes().hasAttribute(Kind);
  6426. }
  6427. /// Adjust the \c DeclContext for a function or variable that might be a
  6428. /// function-local external declaration.
  6429. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  6430. if (!DC->isFunctionOrMethod())
  6431. return false;
  6432. // If this is a local extern function or variable declared within a function
  6433. // template, don't add it into the enclosing namespace scope until it is
  6434. // instantiated; it might have a dependent type right now.
  6435. if (DC->isDependentContext())
  6436. return true;
  6437. // C++11 [basic.link]p7:
  6438. // When a block scope declaration of an entity with linkage is not found to
  6439. // refer to some other declaration, then that entity is a member of the
  6440. // innermost enclosing namespace.
  6441. //
  6442. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  6443. // semantically-enclosing namespace, not a lexically-enclosing one.
  6444. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  6445. DC = DC->getParent();
  6446. return true;
  6447. }
  6448. /// Returns true if given declaration has external C language linkage.
  6449. static bool isDeclExternC(const Decl *D) {
  6450. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  6451. return FD->isExternC();
  6452. if (const auto *VD = dyn_cast<VarDecl>(D))
  6453. return VD->isExternC();
  6454. llvm_unreachable("Unknown type of decl!");
  6455. }
  6456. /// Returns true if there hasn't been any invalid type diagnosed.
  6457. static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
  6458. DeclContext *DC = NewVD->getDeclContext();
  6459. QualType R = NewVD->getType();
  6460. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  6461. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  6462. // argument.
  6463. if (R->isImageType() || R->isPipeType()) {
  6464. Se.Diag(NewVD->getLocation(),
  6465. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  6466. << R;
  6467. NewVD->setInvalidDecl();
  6468. return false;
  6469. }
  6470. // OpenCL v1.2 s6.9.r:
  6471. // The event type cannot be used to declare a program scope variable.
  6472. // OpenCL v2.0 s6.9.q:
  6473. // The clk_event_t and reserve_id_t types cannot be declared in program
  6474. // scope.
  6475. if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
  6476. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  6477. Se.Diag(NewVD->getLocation(),
  6478. diag::err_invalid_type_for_program_scope_var)
  6479. << R;
  6480. NewVD->setInvalidDecl();
  6481. return false;
  6482. }
  6483. }
  6484. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  6485. if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
  6486. Se.getLangOpts())) {
  6487. QualType NR = R.getCanonicalType();
  6488. while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
  6489. NR->isReferenceType()) {
  6490. if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
  6491. NR->isFunctionReferenceType()) {
  6492. Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
  6493. << NR->isReferenceType();
  6494. NewVD->setInvalidDecl();
  6495. return false;
  6496. }
  6497. NR = NR->getPointeeType();
  6498. }
  6499. }
  6500. if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
  6501. Se.getLangOpts())) {
  6502. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  6503. // half array type (unless the cl_khr_fp16 extension is enabled).
  6504. if (Se.Context.getBaseElementType(R)->isHalfType()) {
  6505. Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
  6506. NewVD->setInvalidDecl();
  6507. return false;
  6508. }
  6509. }
  6510. // OpenCL v1.2 s6.9.r:
  6511. // The event type cannot be used with the __local, __constant and __global
  6512. // address space qualifiers.
  6513. if (R->isEventT()) {
  6514. if (R.getAddressSpace() != LangAS::opencl_private) {
  6515. Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
  6516. NewVD->setInvalidDecl();
  6517. return false;
  6518. }
  6519. }
  6520. if (R->isSamplerT()) {
  6521. // OpenCL v1.2 s6.9.b p4:
  6522. // The sampler type cannot be used with the __local and __global address
  6523. // space qualifiers.
  6524. if (R.getAddressSpace() == LangAS::opencl_local ||
  6525. R.getAddressSpace() == LangAS::opencl_global) {
  6526. Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
  6527. NewVD->setInvalidDecl();
  6528. }
  6529. // OpenCL v1.2 s6.12.14.1:
  6530. // A global sampler must be declared with either the constant address
  6531. // space qualifier or with the const qualifier.
  6532. if (DC->isTranslationUnit() &&
  6533. !(R.getAddressSpace() == LangAS::opencl_constant ||
  6534. R.isConstQualified())) {
  6535. Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
  6536. NewVD->setInvalidDecl();
  6537. }
  6538. if (NewVD->isInvalidDecl())
  6539. return false;
  6540. }
  6541. return true;
  6542. }
  6543. template <typename AttrTy>
  6544. static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
  6545. const TypedefNameDecl *TND = TT->getDecl();
  6546. if (const auto *Attribute = TND->getAttr<AttrTy>()) {
  6547. AttrTy *Clone = Attribute->clone(S.Context);
  6548. Clone->setInherited(true);
  6549. D->addAttr(Clone);
  6550. }
  6551. }
  6552. // This function emits warning and a corresponding note based on the
  6553. // ReadOnlyPlacementAttr attribute. The warning checks that all global variable
  6554. // declarations of an annotated type must be const qualified.
  6555. void emitReadOnlyPlacementAttrWarning(Sema &S, const VarDecl *VD) {
  6556. QualType VarType = VD->getType().getCanonicalType();
  6557. // Ignore local declarations (for now) and those with const qualification.
  6558. // TODO: Local variables should not be allowed if their type declaration has
  6559. // ReadOnlyPlacementAttr attribute. To be handled in follow-up patch.
  6560. if (!VD || VD->hasLocalStorage() || VD->getType().isConstQualified())
  6561. return;
  6562. if (VarType->isArrayType()) {
  6563. // Retrieve element type for array declarations.
  6564. VarType = S.getASTContext().getBaseElementType(VarType);
  6565. }
  6566. const RecordDecl *RD = VarType->getAsRecordDecl();
  6567. // Check if the record declaration is present and if it has any attributes.
  6568. if (RD == nullptr)
  6569. return;
  6570. if (const auto *ConstDecl = RD->getAttr<ReadOnlyPlacementAttr>()) {
  6571. S.Diag(VD->getLocation(), diag::warn_var_decl_not_read_only) << RD;
  6572. S.Diag(ConstDecl->getLocation(), diag::note_enforce_read_only_placement);
  6573. return;
  6574. }
  6575. }
  6576. NamedDecl *Sema::ActOnVariableDeclarator(
  6577. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  6578. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  6579. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  6580. QualType R = TInfo->getType();
  6581. DeclarationName Name = GetNameForDeclarator(D).getName();
  6582. IdentifierInfo *II = Name.getAsIdentifierInfo();
  6583. if (D.isDecompositionDeclarator()) {
  6584. // Take the name of the first declarator as our name for diagnostic
  6585. // purposes.
  6586. auto &Decomp = D.getDecompositionDeclarator();
  6587. if (!Decomp.bindings().empty()) {
  6588. II = Decomp.bindings()[0].Name;
  6589. Name = II;
  6590. }
  6591. } else if (!II) {
  6592. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  6593. return nullptr;
  6594. }
  6595. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  6596. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  6597. // dllimport globals without explicit storage class are treated as extern. We
  6598. // have to change the storage class this early to get the right DeclContext.
  6599. if (SC == SC_None && !DC->isRecord() &&
  6600. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  6601. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  6602. SC = SC_Extern;
  6603. DeclContext *OriginalDC = DC;
  6604. bool IsLocalExternDecl = SC == SC_Extern &&
  6605. adjustContextForLocalExternDecl(DC);
  6606. if (SCSpec == DeclSpec::SCS_mutable) {
  6607. // mutable can only appear on non-static class members, so it's always
  6608. // an error here
  6609. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  6610. D.setInvalidType();
  6611. SC = SC_None;
  6612. }
  6613. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  6614. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  6615. D.getDeclSpec().getStorageClassSpecLoc())) {
  6616. // In C++11, the 'register' storage class specifier is deprecated.
  6617. // Suppress the warning in system macros, it's used in macros in some
  6618. // popular C system headers, such as in glibc's htonl() macro.
  6619. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6620. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  6621. : diag::warn_deprecated_register)
  6622. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6623. }
  6624. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  6625. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  6626. // C99 6.9p2: The storage-class specifiers auto and register shall not
  6627. // appear in the declaration specifiers in an external declaration.
  6628. // Global Register+Asm is a GNU extension we support.
  6629. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  6630. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  6631. D.setInvalidType();
  6632. }
  6633. }
  6634. // If this variable has a VLA type and an initializer, try to
  6635. // fold to a constant-sized type. This is otherwise invalid.
  6636. if (D.hasInitializer() && R->isVariableArrayType())
  6637. tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
  6638. /*DiagID=*/0);
  6639. bool IsMemberSpecialization = false;
  6640. bool IsVariableTemplateSpecialization = false;
  6641. bool IsPartialSpecialization = false;
  6642. bool IsVariableTemplate = false;
  6643. VarDecl *NewVD = nullptr;
  6644. VarTemplateDecl *NewTemplate = nullptr;
  6645. TemplateParameterList *TemplateParams = nullptr;
  6646. if (!getLangOpts().CPlusPlus) {
  6647. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  6648. II, R, TInfo, SC);
  6649. if (R->getContainedDeducedType())
  6650. ParsingInitForAutoVars.insert(NewVD);
  6651. if (D.isInvalidType())
  6652. NewVD->setInvalidDecl();
  6653. if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
  6654. NewVD->hasLocalStorage())
  6655. checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
  6656. NTCUC_AutoVar, NTCUK_Destruct);
  6657. } else {
  6658. bool Invalid = false;
  6659. if (DC->isRecord() && !CurContext->isRecord()) {
  6660. // This is an out-of-line definition of a static data member.
  6661. switch (SC) {
  6662. case SC_None:
  6663. break;
  6664. case SC_Static:
  6665. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6666. diag::err_static_out_of_line)
  6667. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6668. break;
  6669. case SC_Auto:
  6670. case SC_Register:
  6671. case SC_Extern:
  6672. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  6673. // to names of variables declared in a block or to function parameters.
  6674. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  6675. // of class members
  6676. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6677. diag::err_storage_class_for_static_member)
  6678. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  6679. break;
  6680. case SC_PrivateExtern:
  6681. llvm_unreachable("C storage class in c++!");
  6682. }
  6683. }
  6684. if (SC == SC_Static && CurContext->isRecord()) {
  6685. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  6686. // Walk up the enclosing DeclContexts to check for any that are
  6687. // incompatible with static data members.
  6688. const DeclContext *FunctionOrMethod = nullptr;
  6689. const CXXRecordDecl *AnonStruct = nullptr;
  6690. for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
  6691. if (Ctxt->isFunctionOrMethod()) {
  6692. FunctionOrMethod = Ctxt;
  6693. break;
  6694. }
  6695. const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
  6696. if (ParentDecl && !ParentDecl->getDeclName()) {
  6697. AnonStruct = ParentDecl;
  6698. break;
  6699. }
  6700. }
  6701. if (FunctionOrMethod) {
  6702. // C++ [class.static.data]p5: A local class shall not have static data
  6703. // members.
  6704. Diag(D.getIdentifierLoc(),
  6705. diag::err_static_data_member_not_allowed_in_local_class)
  6706. << Name << RD->getDeclName() << RD->getTagKind();
  6707. } else if (AnonStruct) {
  6708. // C++ [class.static.data]p4: Unnamed classes and classes contained
  6709. // directly or indirectly within unnamed classes shall not contain
  6710. // static data members.
  6711. Diag(D.getIdentifierLoc(),
  6712. diag::err_static_data_member_not_allowed_in_anon_struct)
  6713. << Name << AnonStruct->getTagKind();
  6714. Invalid = true;
  6715. } else if (RD->isUnion()) {
  6716. // C++98 [class.union]p1: If a union contains a static data member,
  6717. // the program is ill-formed. C++11 drops this restriction.
  6718. Diag(D.getIdentifierLoc(),
  6719. getLangOpts().CPlusPlus11
  6720. ? diag::warn_cxx98_compat_static_data_member_in_union
  6721. : diag::ext_static_data_member_in_union) << Name;
  6722. }
  6723. }
  6724. }
  6725. // Match up the template parameter lists with the scope specifier, then
  6726. // determine whether we have a template or a template specialization.
  6727. bool InvalidScope = false;
  6728. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  6729. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  6730. D.getCXXScopeSpec(),
  6731. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  6732. ? D.getName().TemplateId
  6733. : nullptr,
  6734. TemplateParamLists,
  6735. /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
  6736. Invalid |= InvalidScope;
  6737. if (TemplateParams) {
  6738. if (!TemplateParams->size() &&
  6739. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  6740. // There is an extraneous 'template<>' for this variable. Complain
  6741. // about it, but allow the declaration of the variable.
  6742. Diag(TemplateParams->getTemplateLoc(),
  6743. diag::err_template_variable_noparams)
  6744. << II
  6745. << SourceRange(TemplateParams->getTemplateLoc(),
  6746. TemplateParams->getRAngleLoc());
  6747. TemplateParams = nullptr;
  6748. } else {
  6749. // Check that we can declare a template here.
  6750. if (CheckTemplateDeclScope(S, TemplateParams))
  6751. return nullptr;
  6752. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  6753. // This is an explicit specialization or a partial specialization.
  6754. IsVariableTemplateSpecialization = true;
  6755. IsPartialSpecialization = TemplateParams->size() > 0;
  6756. } else { // if (TemplateParams->size() > 0)
  6757. // This is a template declaration.
  6758. IsVariableTemplate = true;
  6759. // Only C++1y supports variable templates (N3651).
  6760. Diag(D.getIdentifierLoc(),
  6761. getLangOpts().CPlusPlus14
  6762. ? diag::warn_cxx11_compat_variable_template
  6763. : diag::ext_variable_template);
  6764. }
  6765. }
  6766. } else {
  6767. // Check that we can declare a member specialization here.
  6768. if (!TemplateParamLists.empty() && IsMemberSpecialization &&
  6769. CheckTemplateDeclScope(S, TemplateParamLists.back()))
  6770. return nullptr;
  6771. assert((Invalid ||
  6772. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  6773. "should have a 'template<>' for this decl");
  6774. }
  6775. if (IsVariableTemplateSpecialization) {
  6776. SourceLocation TemplateKWLoc =
  6777. TemplateParamLists.size() > 0
  6778. ? TemplateParamLists[0]->getTemplateLoc()
  6779. : SourceLocation();
  6780. DeclResult Res = ActOnVarTemplateSpecialization(
  6781. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  6782. IsPartialSpecialization);
  6783. if (Res.isInvalid())
  6784. return nullptr;
  6785. NewVD = cast<VarDecl>(Res.get());
  6786. AddToScope = false;
  6787. } else if (D.isDecompositionDeclarator()) {
  6788. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  6789. D.getIdentifierLoc(), R, TInfo, SC,
  6790. Bindings);
  6791. } else
  6792. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  6793. D.getIdentifierLoc(), II, R, TInfo, SC);
  6794. // If this is supposed to be a variable template, create it as such.
  6795. if (IsVariableTemplate) {
  6796. NewTemplate =
  6797. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  6798. TemplateParams, NewVD);
  6799. NewVD->setDescribedVarTemplate(NewTemplate);
  6800. }
  6801. // If this decl has an auto type in need of deduction, make a note of the
  6802. // Decl so we can diagnose uses of it in its own initializer.
  6803. if (R->getContainedDeducedType())
  6804. ParsingInitForAutoVars.insert(NewVD);
  6805. if (D.isInvalidType() || Invalid) {
  6806. NewVD->setInvalidDecl();
  6807. if (NewTemplate)
  6808. NewTemplate->setInvalidDecl();
  6809. }
  6810. SetNestedNameSpecifier(*this, NewVD, D);
  6811. // If we have any template parameter lists that don't directly belong to
  6812. // the variable (matching the scope specifier), store them.
  6813. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  6814. if (TemplateParamLists.size() > VDTemplateParamLists)
  6815. NewVD->setTemplateParameterListsInfo(
  6816. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  6817. }
  6818. if (D.getDeclSpec().isInlineSpecified()) {
  6819. if (!getLangOpts().CPlusPlus) {
  6820. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  6821. << 0;
  6822. } else if (CurContext->isFunctionOrMethod()) {
  6823. // 'inline' is not allowed on block scope variable declaration.
  6824. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6825. diag::err_inline_declaration_block_scope) << Name
  6826. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  6827. } else {
  6828. Diag(D.getDeclSpec().getInlineSpecLoc(),
  6829. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  6830. : diag::ext_inline_variable);
  6831. NewVD->setInlineSpecified();
  6832. }
  6833. }
  6834. // Set the lexical context. If the declarator has a C++ scope specifier, the
  6835. // lexical context will be different from the semantic context.
  6836. NewVD->setLexicalDeclContext(CurContext);
  6837. if (NewTemplate)
  6838. NewTemplate->setLexicalDeclContext(CurContext);
  6839. if (IsLocalExternDecl) {
  6840. if (D.isDecompositionDeclarator())
  6841. for (auto *B : Bindings)
  6842. B->setLocalExternDecl();
  6843. else
  6844. NewVD->setLocalExternDecl();
  6845. }
  6846. bool EmitTLSUnsupportedError = false;
  6847. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  6848. // C++11 [dcl.stc]p4:
  6849. // When thread_local is applied to a variable of block scope the
  6850. // storage-class-specifier static is implied if it does not appear
  6851. // explicitly.
  6852. // Core issue: 'static' is not implied if the variable is declared
  6853. // 'extern'.
  6854. if (NewVD->hasLocalStorage() &&
  6855. (SCSpec != DeclSpec::SCS_unspecified ||
  6856. TSCS != DeclSpec::TSCS_thread_local ||
  6857. !DC->isFunctionOrMethod()))
  6858. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6859. diag::err_thread_non_global)
  6860. << DeclSpec::getSpecifierName(TSCS);
  6861. else if (!Context.getTargetInfo().isTLSSupported()) {
  6862. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
  6863. getLangOpts().SYCLIsDevice) {
  6864. // Postpone error emission until we've collected attributes required to
  6865. // figure out whether it's a host or device variable and whether the
  6866. // error should be ignored.
  6867. EmitTLSUnsupportedError = true;
  6868. // We still need to mark the variable as TLS so it shows up in AST with
  6869. // proper storage class for other tools to use even if we're not going
  6870. // to emit any code for it.
  6871. NewVD->setTSCSpec(TSCS);
  6872. } else
  6873. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6874. diag::err_thread_unsupported);
  6875. } else
  6876. NewVD->setTSCSpec(TSCS);
  6877. }
  6878. switch (D.getDeclSpec().getConstexprSpecifier()) {
  6879. case ConstexprSpecKind::Unspecified:
  6880. break;
  6881. case ConstexprSpecKind::Consteval:
  6882. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6883. diag::err_constexpr_wrong_decl_kind)
  6884. << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  6885. [[fallthrough]];
  6886. case ConstexprSpecKind::Constexpr:
  6887. NewVD->setConstexpr(true);
  6888. // C++1z [dcl.spec.constexpr]p1:
  6889. // A static data member declared with the constexpr specifier is
  6890. // implicitly an inline variable.
  6891. if (NewVD->isStaticDataMember() &&
  6892. (getLangOpts().CPlusPlus17 ||
  6893. Context.getTargetInfo().getCXXABI().isMicrosoft()))
  6894. NewVD->setImplicitlyInline();
  6895. break;
  6896. case ConstexprSpecKind::Constinit:
  6897. if (!NewVD->hasGlobalStorage())
  6898. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  6899. diag::err_constinit_local_variable);
  6900. else
  6901. NewVD->addAttr(ConstInitAttr::Create(
  6902. Context, D.getDeclSpec().getConstexprSpecLoc(),
  6903. AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
  6904. break;
  6905. }
  6906. // C99 6.7.4p3
  6907. // An inline definition of a function with external linkage shall
  6908. // not contain a definition of a modifiable object with static or
  6909. // thread storage duration...
  6910. // We only apply this when the function is required to be defined
  6911. // elsewhere, i.e. when the function is not 'extern inline'. Note
  6912. // that a local variable with thread storage duration still has to
  6913. // be marked 'static'. Also note that it's possible to get these
  6914. // semantics in C++ using __attribute__((gnu_inline)).
  6915. if (SC == SC_Static && S->getFnParent() != nullptr &&
  6916. !NewVD->getType().isConstQualified()) {
  6917. FunctionDecl *CurFD = getCurFunctionDecl();
  6918. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  6919. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6920. diag::warn_static_local_in_extern_inline);
  6921. MaybeSuggestAddingStaticToDecl(CurFD);
  6922. }
  6923. }
  6924. if (D.getDeclSpec().isModulePrivateSpecified()) {
  6925. if (IsVariableTemplateSpecialization)
  6926. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6927. << (IsPartialSpecialization ? 1 : 0)
  6928. << FixItHint::CreateRemoval(
  6929. D.getDeclSpec().getModulePrivateSpecLoc());
  6930. else if (IsMemberSpecialization)
  6931. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  6932. << 2
  6933. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  6934. else if (NewVD->hasLocalStorage())
  6935. Diag(NewVD->getLocation(), diag::err_module_private_local)
  6936. << 0 << NewVD
  6937. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  6938. << FixItHint::CreateRemoval(
  6939. D.getDeclSpec().getModulePrivateSpecLoc());
  6940. else {
  6941. NewVD->setModulePrivate();
  6942. if (NewTemplate)
  6943. NewTemplate->setModulePrivate();
  6944. for (auto *B : Bindings)
  6945. B->setModulePrivate();
  6946. }
  6947. }
  6948. if (getLangOpts().OpenCL) {
  6949. deduceOpenCLAddressSpace(NewVD);
  6950. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  6951. if (TSC != TSCS_unspecified) {
  6952. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6953. diag::err_opencl_unknown_type_specifier)
  6954. << getLangOpts().getOpenCLVersionString()
  6955. << DeclSpec::getSpecifierName(TSC) << 1;
  6956. NewVD->setInvalidDecl();
  6957. }
  6958. }
  6959. // Handle attributes prior to checking for duplicates in MergeVarDecl
  6960. ProcessDeclAttributes(S, NewVD, D);
  6961. // FIXME: This is probably the wrong location to be doing this and we should
  6962. // probably be doing this for more attributes (especially for function
  6963. // pointer attributes such as format, warn_unused_result, etc.). Ideally
  6964. // the code to copy attributes would be generated by TableGen.
  6965. if (R->isFunctionPointerType())
  6966. if (const auto *TT = R->getAs<TypedefType>())
  6967. copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
  6968. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
  6969. getLangOpts().SYCLIsDevice) {
  6970. if (EmitTLSUnsupportedError &&
  6971. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  6972. (getLangOpts().OpenMPIsDevice &&
  6973. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
  6974. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  6975. diag::err_thread_unsupported);
  6976. if (EmitTLSUnsupportedError &&
  6977. (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
  6978. targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
  6979. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  6980. // storage [duration]."
  6981. if (SC == SC_None && S->getFnParent() != nullptr &&
  6982. (NewVD->hasAttr<CUDASharedAttr>() ||
  6983. NewVD->hasAttr<CUDAConstantAttr>())) {
  6984. NewVD->setStorageClass(SC_Static);
  6985. }
  6986. }
  6987. // Ensure that dllimport globals without explicit storage class are treated as
  6988. // extern. The storage class is set above using parsed attributes. Now we can
  6989. // check the VarDecl itself.
  6990. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  6991. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  6992. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  6993. // In auto-retain/release, infer strong retension for variables of
  6994. // retainable type.
  6995. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  6996. NewVD->setInvalidDecl();
  6997. // Handle GNU asm-label extension (encoded as an attribute).
  6998. if (Expr *E = (Expr*)D.getAsmLabel()) {
  6999. // The parser guarantees this is a string.
  7000. StringLiteral *SE = cast<StringLiteral>(E);
  7001. StringRef Label = SE->getString();
  7002. if (S->getFnParent() != nullptr) {
  7003. switch (SC) {
  7004. case SC_None:
  7005. case SC_Auto:
  7006. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  7007. break;
  7008. case SC_Register:
  7009. // Local Named register
  7010. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  7011. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  7012. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  7013. break;
  7014. case SC_Static:
  7015. case SC_Extern:
  7016. case SC_PrivateExtern:
  7017. break;
  7018. }
  7019. } else if (SC == SC_Register) {
  7020. // Global Named register
  7021. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  7022. const auto &TI = Context.getTargetInfo();
  7023. bool HasSizeMismatch;
  7024. if (!TI.isValidGCCRegisterName(Label))
  7025. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  7026. else if (!TI.validateGlobalRegisterVariable(Label,
  7027. Context.getTypeSize(R),
  7028. HasSizeMismatch))
  7029. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  7030. else if (HasSizeMismatch)
  7031. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  7032. }
  7033. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  7034. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  7035. NewVD->setInvalidDecl(true);
  7036. }
  7037. }
  7038. NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
  7039. /*IsLiteralLabel=*/true,
  7040. SE->getStrTokenLoc(0)));
  7041. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7042. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7043. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  7044. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7045. if (isDeclExternC(NewVD)) {
  7046. NewVD->addAttr(I->second);
  7047. ExtnameUndeclaredIdentifiers.erase(I);
  7048. } else
  7049. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  7050. << /*Variable*/1 << NewVD;
  7051. }
  7052. }
  7053. // Find the shadowed declaration before filtering for scope.
  7054. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  7055. ? getShadowedDeclaration(NewVD, Previous)
  7056. : nullptr;
  7057. // Don't consider existing declarations that are in a different
  7058. // scope and are out-of-semantic-context declarations (if the new
  7059. // declaration has linkage).
  7060. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  7061. D.getCXXScopeSpec().isNotEmpty() ||
  7062. IsMemberSpecialization ||
  7063. IsVariableTemplateSpecialization);
  7064. // Check whether the previous declaration is in the same block scope. This
  7065. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  7066. if (getLangOpts().CPlusPlus &&
  7067. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  7068. NewVD->setPreviousDeclInSameBlockScope(
  7069. Previous.isSingleResult() && !Previous.isShadowed() &&
  7070. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  7071. if (!getLangOpts().CPlusPlus) {
  7072. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  7073. } else {
  7074. // If this is an explicit specialization of a static data member, check it.
  7075. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  7076. CheckMemberSpecialization(NewVD, Previous))
  7077. NewVD->setInvalidDecl();
  7078. // Merge the decl with the existing one if appropriate.
  7079. if (!Previous.empty()) {
  7080. if (Previous.isSingleResult() &&
  7081. isa<FieldDecl>(Previous.getFoundDecl()) &&
  7082. D.getCXXScopeSpec().isSet()) {
  7083. // The user tried to define a non-static data member
  7084. // out-of-line (C++ [dcl.meaning]p1).
  7085. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  7086. << D.getCXXScopeSpec().getRange();
  7087. Previous.clear();
  7088. NewVD->setInvalidDecl();
  7089. }
  7090. } else if (D.getCXXScopeSpec().isSet()) {
  7091. // No previous declaration in the qualifying scope.
  7092. Diag(D.getIdentifierLoc(), diag::err_no_member)
  7093. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  7094. << D.getCXXScopeSpec().getRange();
  7095. NewVD->setInvalidDecl();
  7096. }
  7097. if (!IsVariableTemplateSpecialization)
  7098. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  7099. if (NewTemplate) {
  7100. VarTemplateDecl *PrevVarTemplate =
  7101. NewVD->getPreviousDecl()
  7102. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  7103. : nullptr;
  7104. // Check the template parameter list of this declaration, possibly
  7105. // merging in the template parameter list from the previous variable
  7106. // template declaration.
  7107. if (CheckTemplateParameterList(
  7108. TemplateParams,
  7109. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  7110. : nullptr,
  7111. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  7112. DC->isDependentContext())
  7113. ? TPC_ClassTemplateMember
  7114. : TPC_VarTemplate))
  7115. NewVD->setInvalidDecl();
  7116. // If we are providing an explicit specialization of a static variable
  7117. // template, make a note of that.
  7118. if (PrevVarTemplate &&
  7119. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  7120. PrevVarTemplate->setMemberSpecialization();
  7121. }
  7122. }
  7123. // Diagnose shadowed variables iff this isn't a redeclaration.
  7124. if (ShadowedDecl && !D.isRedeclaration())
  7125. CheckShadow(NewVD, ShadowedDecl, Previous);
  7126. ProcessPragmaWeak(S, NewVD);
  7127. // If this is the first declaration of an extern C variable, update
  7128. // the map of such variables.
  7129. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  7130. isIncompleteDeclExternC(*this, NewVD))
  7131. RegisterLocallyScopedExternCDecl(NewVD, S);
  7132. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  7133. MangleNumberingContext *MCtx;
  7134. Decl *ManglingContextDecl;
  7135. std::tie(MCtx, ManglingContextDecl) =
  7136. getCurrentMangleNumberContext(NewVD->getDeclContext());
  7137. if (MCtx) {
  7138. Context.setManglingNumber(
  7139. NewVD, MCtx->getManglingNumber(
  7140. NewVD, getMSManglingNumber(getLangOpts(), S)));
  7141. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  7142. }
  7143. }
  7144. // Special handling of variable named 'main'.
  7145. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  7146. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  7147. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  7148. // C++ [basic.start.main]p3
  7149. // A program that declares a variable main at global scope is ill-formed.
  7150. if (getLangOpts().CPlusPlus)
  7151. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  7152. // In C, and external-linkage variable named main results in undefined
  7153. // behavior.
  7154. else if (NewVD->hasExternalFormalLinkage())
  7155. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  7156. }
  7157. if (D.isRedeclaration() && !Previous.empty()) {
  7158. NamedDecl *Prev = Previous.getRepresentativeDecl();
  7159. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  7160. D.isFunctionDefinition());
  7161. }
  7162. if (NewTemplate) {
  7163. if (NewVD->isInvalidDecl())
  7164. NewTemplate->setInvalidDecl();
  7165. ActOnDocumentableDecl(NewTemplate);
  7166. return NewTemplate;
  7167. }
  7168. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  7169. CompleteMemberSpecialization(NewVD, Previous);
  7170. emitReadOnlyPlacementAttrWarning(*this, NewVD);
  7171. return NewVD;
  7172. }
  7173. /// Enum describing the %select options in diag::warn_decl_shadow.
  7174. enum ShadowedDeclKind {
  7175. SDK_Local,
  7176. SDK_Global,
  7177. SDK_StaticMember,
  7178. SDK_Field,
  7179. SDK_Typedef,
  7180. SDK_Using,
  7181. SDK_StructuredBinding
  7182. };
  7183. /// Determine what kind of declaration we're shadowing.
  7184. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  7185. const DeclContext *OldDC) {
  7186. if (isa<TypeAliasDecl>(ShadowedDecl))
  7187. return SDK_Using;
  7188. else if (isa<TypedefDecl>(ShadowedDecl))
  7189. return SDK_Typedef;
  7190. else if (isa<BindingDecl>(ShadowedDecl))
  7191. return SDK_StructuredBinding;
  7192. else if (isa<RecordDecl>(OldDC))
  7193. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  7194. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  7195. }
  7196. /// Return the location of the capture if the given lambda captures the given
  7197. /// variable \p VD, or an invalid source location otherwise.
  7198. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  7199. const VarDecl *VD) {
  7200. for (const Capture &Capture : LSI->Captures) {
  7201. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  7202. return Capture.getLocation();
  7203. }
  7204. return SourceLocation();
  7205. }
  7206. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  7207. const LookupResult &R) {
  7208. // Only diagnose if we're shadowing an unambiguous field or variable.
  7209. if (R.getResultKind() != LookupResult::Found)
  7210. return false;
  7211. // Return false if warning is ignored.
  7212. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  7213. }
  7214. /// Return the declaration shadowed by the given variable \p D, or null
  7215. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  7216. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  7217. const LookupResult &R) {
  7218. if (!shouldWarnIfShadowedDecl(Diags, R))
  7219. return nullptr;
  7220. // Don't diagnose declarations at file scope.
  7221. if (D->hasGlobalStorage())
  7222. return nullptr;
  7223. NamedDecl *ShadowedDecl = R.getFoundDecl();
  7224. return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
  7225. : nullptr;
  7226. }
  7227. /// Return the declaration shadowed by the given typedef \p D, or null
  7228. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  7229. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  7230. const LookupResult &R) {
  7231. // Don't warn if typedef declaration is part of a class
  7232. if (D->getDeclContext()->isRecord())
  7233. return nullptr;
  7234. if (!shouldWarnIfShadowedDecl(Diags, R))
  7235. return nullptr;
  7236. NamedDecl *ShadowedDecl = R.getFoundDecl();
  7237. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  7238. }
  7239. /// Return the declaration shadowed by the given variable \p D, or null
  7240. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  7241. NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
  7242. const LookupResult &R) {
  7243. if (!shouldWarnIfShadowedDecl(Diags, R))
  7244. return nullptr;
  7245. NamedDecl *ShadowedDecl = R.getFoundDecl();
  7246. return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
  7247. : nullptr;
  7248. }
  7249. /// Diagnose variable or built-in function shadowing. Implements
  7250. /// -Wshadow.
  7251. ///
  7252. /// This method is called whenever a VarDecl is added to a "useful"
  7253. /// scope.
  7254. ///
  7255. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  7256. /// \param R the lookup of the name
  7257. ///
  7258. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  7259. const LookupResult &R) {
  7260. DeclContext *NewDC = D->getDeclContext();
  7261. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  7262. // Fields are not shadowed by variables in C++ static methods.
  7263. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  7264. if (MD->isStatic())
  7265. return;
  7266. // Fields shadowed by constructor parameters are a special case. Usually
  7267. // the constructor initializes the field with the parameter.
  7268. if (isa<CXXConstructorDecl>(NewDC))
  7269. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  7270. // Remember that this was shadowed so we can either warn about its
  7271. // modification or its existence depending on warning settings.
  7272. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  7273. return;
  7274. }
  7275. }
  7276. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  7277. if (shadowedVar->isExternC()) {
  7278. // For shadowing external vars, make sure that we point to the global
  7279. // declaration, not a locally scoped extern declaration.
  7280. for (auto *I : shadowedVar->redecls())
  7281. if (I->isFileVarDecl()) {
  7282. ShadowedDecl = I;
  7283. break;
  7284. }
  7285. }
  7286. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  7287. unsigned WarningDiag = diag::warn_decl_shadow;
  7288. SourceLocation CaptureLoc;
  7289. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  7290. isa<CXXMethodDecl>(NewDC)) {
  7291. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  7292. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  7293. if (RD->getLambdaCaptureDefault() == LCD_None) {
  7294. // Try to avoid warnings for lambdas with an explicit capture list.
  7295. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  7296. // Warn only when the lambda captures the shadowed decl explicitly.
  7297. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  7298. if (CaptureLoc.isInvalid())
  7299. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  7300. } else {
  7301. // Remember that this was shadowed so we can avoid the warning if the
  7302. // shadowed decl isn't captured and the warning settings allow it.
  7303. cast<LambdaScopeInfo>(getCurFunction())
  7304. ->ShadowingDecls.push_back(
  7305. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  7306. return;
  7307. }
  7308. }
  7309. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  7310. // A variable can't shadow a local variable in an enclosing scope, if
  7311. // they are separated by a non-capturing declaration context.
  7312. for (DeclContext *ParentDC = NewDC;
  7313. ParentDC && !ParentDC->Equals(OldDC);
  7314. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  7315. // Only block literals, captured statements, and lambda expressions
  7316. // can capture; other scopes don't.
  7317. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  7318. !isLambdaCallOperator(ParentDC)) {
  7319. return;
  7320. }
  7321. }
  7322. }
  7323. }
  7324. }
  7325. // Only warn about certain kinds of shadowing for class members.
  7326. if (NewDC && NewDC->isRecord()) {
  7327. // In particular, don't warn about shadowing non-class members.
  7328. if (!OldDC->isRecord())
  7329. return;
  7330. // TODO: should we warn about static data members shadowing
  7331. // static data members from base classes?
  7332. // TODO: don't diagnose for inaccessible shadowed members.
  7333. // This is hard to do perfectly because we might friend the
  7334. // shadowing context, but that's just a false negative.
  7335. }
  7336. DeclarationName Name = R.getLookupName();
  7337. // Emit warning and note.
  7338. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  7339. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  7340. if (!CaptureLoc.isInvalid())
  7341. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  7342. << Name << /*explicitly*/ 1;
  7343. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  7344. }
  7345. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  7346. /// when these variables are captured by the lambda.
  7347. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  7348. for (const auto &Shadow : LSI->ShadowingDecls) {
  7349. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  7350. // Try to avoid the warning when the shadowed decl isn't captured.
  7351. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  7352. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  7353. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  7354. ? diag::warn_decl_shadow_uncaptured_local
  7355. : diag::warn_decl_shadow)
  7356. << Shadow.VD->getDeclName()
  7357. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  7358. if (!CaptureLoc.isInvalid())
  7359. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  7360. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  7361. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  7362. }
  7363. }
  7364. /// Check -Wshadow without the advantage of a previous lookup.
  7365. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  7366. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  7367. return;
  7368. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  7369. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  7370. LookupName(R, S);
  7371. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  7372. CheckShadow(D, ShadowedDecl, R);
  7373. }
  7374. /// Check if 'E', which is an expression that is about to be modified, refers
  7375. /// to a constructor parameter that shadows a field.
  7376. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  7377. // Quickly ignore expressions that can't be shadowing ctor parameters.
  7378. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  7379. return;
  7380. E = E->IgnoreParenImpCasts();
  7381. auto *DRE = dyn_cast<DeclRefExpr>(E);
  7382. if (!DRE)
  7383. return;
  7384. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  7385. auto I = ShadowingDecls.find(D);
  7386. if (I == ShadowingDecls.end())
  7387. return;
  7388. const NamedDecl *ShadowedDecl = I->second;
  7389. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  7390. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  7391. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  7392. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  7393. // Avoid issuing multiple warnings about the same decl.
  7394. ShadowingDecls.erase(I);
  7395. }
  7396. /// Check for conflict between this global or extern "C" declaration and
  7397. /// previous global or extern "C" declarations. This is only used in C++.
  7398. template<typename T>
  7399. static bool checkGlobalOrExternCConflict(
  7400. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  7401. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  7402. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  7403. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  7404. // The common case: this global doesn't conflict with any extern "C"
  7405. // declaration.
  7406. return false;
  7407. }
  7408. if (Prev) {
  7409. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  7410. // Both the old and new declarations have C language linkage. This is a
  7411. // redeclaration.
  7412. Previous.clear();
  7413. Previous.addDecl(Prev);
  7414. return true;
  7415. }
  7416. // This is a global, non-extern "C" declaration, and there is a previous
  7417. // non-global extern "C" declaration. Diagnose if this is a variable
  7418. // declaration.
  7419. if (!isa<VarDecl>(ND))
  7420. return false;
  7421. } else {
  7422. // The declaration is extern "C". Check for any declaration in the
  7423. // translation unit which might conflict.
  7424. if (IsGlobal) {
  7425. // We have already performed the lookup into the translation unit.
  7426. IsGlobal = false;
  7427. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7428. I != E; ++I) {
  7429. if (isa<VarDecl>(*I)) {
  7430. Prev = *I;
  7431. break;
  7432. }
  7433. }
  7434. } else {
  7435. DeclContext::lookup_result R =
  7436. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  7437. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  7438. I != E; ++I) {
  7439. if (isa<VarDecl>(*I)) {
  7440. Prev = *I;
  7441. break;
  7442. }
  7443. // FIXME: If we have any other entity with this name in global scope,
  7444. // the declaration is ill-formed, but that is a defect: it breaks the
  7445. // 'stat' hack, for instance. Only variables can have mangled name
  7446. // clashes with extern "C" declarations, so only they deserve a
  7447. // diagnostic.
  7448. }
  7449. }
  7450. if (!Prev)
  7451. return false;
  7452. }
  7453. // Use the first declaration's location to ensure we point at something which
  7454. // is lexically inside an extern "C" linkage-spec.
  7455. assert(Prev && "should have found a previous declaration to diagnose");
  7456. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  7457. Prev = FD->getFirstDecl();
  7458. else
  7459. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  7460. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  7461. << IsGlobal << ND;
  7462. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  7463. << IsGlobal;
  7464. return false;
  7465. }
  7466. /// Apply special rules for handling extern "C" declarations. Returns \c true
  7467. /// if we have found that this is a redeclaration of some prior entity.
  7468. ///
  7469. /// Per C++ [dcl.link]p6:
  7470. /// Two declarations [for a function or variable] with C language linkage
  7471. /// with the same name that appear in different scopes refer to the same
  7472. /// [entity]. An entity with C language linkage shall not be declared with
  7473. /// the same name as an entity in global scope.
  7474. template<typename T>
  7475. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  7476. LookupResult &Previous) {
  7477. if (!S.getLangOpts().CPlusPlus) {
  7478. // In C, when declaring a global variable, look for a corresponding 'extern'
  7479. // variable declared in function scope. We don't need this in C++, because
  7480. // we find local extern decls in the surrounding file-scope DeclContext.
  7481. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  7482. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  7483. Previous.clear();
  7484. Previous.addDecl(Prev);
  7485. return true;
  7486. }
  7487. }
  7488. return false;
  7489. }
  7490. // A declaration in the translation unit can conflict with an extern "C"
  7491. // declaration.
  7492. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  7493. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  7494. // An extern "C" declaration can conflict with a declaration in the
  7495. // translation unit or can be a redeclaration of an extern "C" declaration
  7496. // in another scope.
  7497. if (isIncompleteDeclExternC(S,ND))
  7498. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  7499. // Neither global nor extern "C": nothing to do.
  7500. return false;
  7501. }
  7502. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  7503. // If the decl is already known invalid, don't check it.
  7504. if (NewVD->isInvalidDecl())
  7505. return;
  7506. QualType T = NewVD->getType();
  7507. // Defer checking an 'auto' type until its initializer is attached.
  7508. if (T->isUndeducedType())
  7509. return;
  7510. if (NewVD->hasAttrs())
  7511. CheckAlignasUnderalignment(NewVD);
  7512. if (T->isObjCObjectType()) {
  7513. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  7514. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  7515. T = Context.getObjCObjectPointerType(T);
  7516. NewVD->setType(T);
  7517. }
  7518. // Emit an error if an address space was applied to decl with local storage.
  7519. // This includes arrays of objects with address space qualifiers, but not
  7520. // automatic variables that point to other address spaces.
  7521. // ISO/IEC TR 18037 S5.1.2
  7522. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  7523. T.getAddressSpace() != LangAS::Default) {
  7524. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  7525. NewVD->setInvalidDecl();
  7526. return;
  7527. }
  7528. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  7529. // scope.
  7530. if (getLangOpts().OpenCLVersion == 120 &&
  7531. !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
  7532. getLangOpts()) &&
  7533. NewVD->isStaticLocal()) {
  7534. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  7535. NewVD->setInvalidDecl();
  7536. return;
  7537. }
  7538. if (getLangOpts().OpenCL) {
  7539. if (!diagnoseOpenCLTypes(*this, NewVD))
  7540. return;
  7541. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  7542. if (NewVD->hasAttr<BlocksAttr>()) {
  7543. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  7544. return;
  7545. }
  7546. if (T->isBlockPointerType()) {
  7547. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  7548. // can't use 'extern' storage class.
  7549. if (!T.isConstQualified()) {
  7550. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  7551. << 0 /*const*/;
  7552. NewVD->setInvalidDecl();
  7553. return;
  7554. }
  7555. if (NewVD->hasExternalStorage()) {
  7556. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  7557. NewVD->setInvalidDecl();
  7558. return;
  7559. }
  7560. }
  7561. // FIXME: Adding local AS in C++ for OpenCL might make sense.
  7562. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  7563. NewVD->hasExternalStorage()) {
  7564. if (!T->isSamplerT() && !T->isDependentType() &&
  7565. !(T.getAddressSpace() == LangAS::opencl_constant ||
  7566. (T.getAddressSpace() == LangAS::opencl_global &&
  7567. getOpenCLOptions().areProgramScopeVariablesSupported(
  7568. getLangOpts())))) {
  7569. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  7570. if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
  7571. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  7572. << Scope << "global or constant";
  7573. else
  7574. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  7575. << Scope << "constant";
  7576. NewVD->setInvalidDecl();
  7577. return;
  7578. }
  7579. } else {
  7580. if (T.getAddressSpace() == LangAS::opencl_global) {
  7581. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7582. << 1 /*is any function*/ << "global";
  7583. NewVD->setInvalidDecl();
  7584. return;
  7585. }
  7586. if (T.getAddressSpace() == LangAS::opencl_constant ||
  7587. T.getAddressSpace() == LangAS::opencl_local) {
  7588. FunctionDecl *FD = getCurFunctionDecl();
  7589. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  7590. // in functions.
  7591. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  7592. if (T.getAddressSpace() == LangAS::opencl_constant)
  7593. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7594. << 0 /*non-kernel only*/ << "constant";
  7595. else
  7596. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  7597. << 0 /*non-kernel only*/ << "local";
  7598. NewVD->setInvalidDecl();
  7599. return;
  7600. }
  7601. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  7602. // in the outermost scope of a kernel function.
  7603. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  7604. if (!getCurScope()->isFunctionScope()) {
  7605. if (T.getAddressSpace() == LangAS::opencl_constant)
  7606. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  7607. << "constant";
  7608. else
  7609. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  7610. << "local";
  7611. NewVD->setInvalidDecl();
  7612. return;
  7613. }
  7614. }
  7615. } else if (T.getAddressSpace() != LangAS::opencl_private &&
  7616. // If we are parsing a template we didn't deduce an addr
  7617. // space yet.
  7618. T.getAddressSpace() != LangAS::Default) {
  7619. // Do not allow other address spaces on automatic variable.
  7620. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  7621. NewVD->setInvalidDecl();
  7622. return;
  7623. }
  7624. }
  7625. }
  7626. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  7627. && !NewVD->hasAttr<BlocksAttr>()) {
  7628. if (getLangOpts().getGC() != LangOptions::NonGC)
  7629. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  7630. else {
  7631. assert(!getLangOpts().ObjCAutoRefCount);
  7632. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  7633. }
  7634. }
  7635. bool isVM = T->isVariablyModifiedType();
  7636. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  7637. NewVD->hasAttr<BlocksAttr>())
  7638. setFunctionHasBranchProtectedScope();
  7639. if ((isVM && NewVD->hasLinkage()) ||
  7640. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  7641. bool SizeIsNegative;
  7642. llvm::APSInt Oversized;
  7643. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  7644. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  7645. QualType FixedT;
  7646. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  7647. FixedT = FixedTInfo->getType();
  7648. else if (FixedTInfo) {
  7649. // Type and type-as-written are canonically different. We need to fix up
  7650. // both types separately.
  7651. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  7652. Oversized);
  7653. }
  7654. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  7655. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  7656. // FIXME: This won't give the correct result for
  7657. // int a[10][n];
  7658. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  7659. if (NewVD->isFileVarDecl())
  7660. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  7661. << SizeRange;
  7662. else if (NewVD->isStaticLocal())
  7663. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  7664. << SizeRange;
  7665. else
  7666. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  7667. << SizeRange;
  7668. NewVD->setInvalidDecl();
  7669. return;
  7670. }
  7671. if (!FixedTInfo) {
  7672. if (NewVD->isFileVarDecl())
  7673. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  7674. else
  7675. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  7676. NewVD->setInvalidDecl();
  7677. return;
  7678. }
  7679. Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
  7680. NewVD->setType(FixedT);
  7681. NewVD->setTypeSourceInfo(FixedTInfo);
  7682. }
  7683. if (T->isVoidType()) {
  7684. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  7685. // of objects and functions.
  7686. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  7687. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  7688. << T;
  7689. NewVD->setInvalidDecl();
  7690. return;
  7691. }
  7692. }
  7693. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  7694. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  7695. NewVD->setInvalidDecl();
  7696. return;
  7697. }
  7698. if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
  7699. Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
  7700. NewVD->setInvalidDecl();
  7701. return;
  7702. }
  7703. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  7704. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  7705. NewVD->setInvalidDecl();
  7706. return;
  7707. }
  7708. if (NewVD->isConstexpr() && !T->isDependentType() &&
  7709. RequireLiteralType(NewVD->getLocation(), T,
  7710. diag::err_constexpr_var_non_literal)) {
  7711. NewVD->setInvalidDecl();
  7712. return;
  7713. }
  7714. // PPC MMA non-pointer types are not allowed as non-local variable types.
  7715. if (Context.getTargetInfo().getTriple().isPPC64() &&
  7716. !NewVD->isLocalVarDecl() &&
  7717. CheckPPCMMAType(T, NewVD->getLocation())) {
  7718. NewVD->setInvalidDecl();
  7719. return;
  7720. }
  7721. // Check that SVE types are only used in functions with SVE available.
  7722. if (T->isSVESizelessBuiltinType() && CurContext->isFunctionOrMethod()) {
  7723. const FunctionDecl *FD = cast<FunctionDecl>(CurContext);
  7724. llvm::StringMap<bool> CallerFeatureMap;
  7725. Context.getFunctionFeatureMap(CallerFeatureMap, FD);
  7726. if (!Builtin::evaluateRequiredTargetFeatures(
  7727. "sve", CallerFeatureMap)) {
  7728. Diag(NewVD->getLocation(), diag::err_sve_vector_in_non_sve_target) << T;
  7729. NewVD->setInvalidDecl();
  7730. return;
  7731. }
  7732. }
  7733. }
  7734. /// Perform semantic checking on a newly-created variable
  7735. /// declaration.
  7736. ///
  7737. /// This routine performs all of the type-checking required for a
  7738. /// variable declaration once it has been built. It is used both to
  7739. /// check variables after they have been parsed and their declarators
  7740. /// have been translated into a declaration, and to check variables
  7741. /// that have been instantiated from a template.
  7742. ///
  7743. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  7744. ///
  7745. /// Returns true if the variable declaration is a redeclaration.
  7746. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  7747. CheckVariableDeclarationType(NewVD);
  7748. // If the decl is already known invalid, don't check it.
  7749. if (NewVD->isInvalidDecl())
  7750. return false;
  7751. // If we did not find anything by this name, look for a non-visible
  7752. // extern "C" declaration with the same name.
  7753. if (Previous.empty() &&
  7754. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  7755. Previous.setShadowed();
  7756. if (!Previous.empty()) {
  7757. MergeVarDecl(NewVD, Previous);
  7758. return true;
  7759. }
  7760. return false;
  7761. }
  7762. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  7763. /// and if so, check that it's a valid override and remember it.
  7764. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  7765. llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
  7766. // Look for methods in base classes that this method might override.
  7767. CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
  7768. /*DetectVirtual=*/false);
  7769. auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  7770. CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
  7771. DeclarationName Name = MD->getDeclName();
  7772. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7773. // We really want to find the base class destructor here.
  7774. QualType T = Context.getTypeDeclType(BaseRecord);
  7775. CanQualType CT = Context.getCanonicalType(T);
  7776. Name = Context.DeclarationNames.getCXXDestructorName(CT);
  7777. }
  7778. for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
  7779. CXXMethodDecl *BaseMD =
  7780. dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
  7781. if (!BaseMD || !BaseMD->isVirtual() ||
  7782. IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
  7783. /*ConsiderCudaAttrs=*/true,
  7784. // C++2a [class.virtual]p2 does not consider requires
  7785. // clauses when overriding.
  7786. /*ConsiderRequiresClauses=*/false))
  7787. continue;
  7788. if (Overridden.insert(BaseMD).second) {
  7789. MD->addOverriddenMethod(BaseMD);
  7790. CheckOverridingFunctionReturnType(MD, BaseMD);
  7791. CheckOverridingFunctionAttributes(MD, BaseMD);
  7792. CheckOverridingFunctionExceptionSpec(MD, BaseMD);
  7793. CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
  7794. }
  7795. // A method can only override one function from each base class. We
  7796. // don't track indirectly overridden methods from bases of bases.
  7797. return true;
  7798. }
  7799. return false;
  7800. };
  7801. DC->lookupInBases(VisitBase, Paths);
  7802. return !Overridden.empty();
  7803. }
  7804. namespace {
  7805. // Struct for holding all of the extra arguments needed by
  7806. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  7807. struct ActOnFDArgs {
  7808. Scope *S;
  7809. Declarator &D;
  7810. MultiTemplateParamsArg TemplateParamLists;
  7811. bool AddToScope;
  7812. };
  7813. } // end anonymous namespace
  7814. namespace {
  7815. // Callback to only accept typo corrections that have a non-zero edit distance.
  7816. // Also only accept corrections that have the same parent decl.
  7817. class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
  7818. public:
  7819. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  7820. CXXRecordDecl *Parent)
  7821. : Context(Context), OriginalFD(TypoFD),
  7822. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  7823. bool ValidateCandidate(const TypoCorrection &candidate) override {
  7824. if (candidate.getEditDistance() == 0)
  7825. return false;
  7826. SmallVector<unsigned, 1> MismatchedParams;
  7827. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  7828. CDeclEnd = candidate.end();
  7829. CDecl != CDeclEnd; ++CDecl) {
  7830. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7831. if (FD && !FD->hasBody() &&
  7832. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  7833. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  7834. CXXRecordDecl *Parent = MD->getParent();
  7835. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  7836. return true;
  7837. } else if (!ExpectedParent) {
  7838. return true;
  7839. }
  7840. }
  7841. }
  7842. return false;
  7843. }
  7844. std::unique_ptr<CorrectionCandidateCallback> clone() override {
  7845. return std::make_unique<DifferentNameValidatorCCC>(*this);
  7846. }
  7847. private:
  7848. ASTContext &Context;
  7849. FunctionDecl *OriginalFD;
  7850. CXXRecordDecl *ExpectedParent;
  7851. };
  7852. } // end anonymous namespace
  7853. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  7854. TypoCorrectedFunctionDefinitions.insert(F);
  7855. }
  7856. /// Generate diagnostics for an invalid function redeclaration.
  7857. ///
  7858. /// This routine handles generating the diagnostic messages for an invalid
  7859. /// function redeclaration, including finding possible similar declarations
  7860. /// or performing typo correction if there are no previous declarations with
  7861. /// the same name.
  7862. ///
  7863. /// Returns a NamedDecl iff typo correction was performed and substituting in
  7864. /// the new declaration name does not cause new errors.
  7865. static NamedDecl *DiagnoseInvalidRedeclaration(
  7866. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  7867. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  7868. DeclarationName Name = NewFD->getDeclName();
  7869. DeclContext *NewDC = NewFD->getDeclContext();
  7870. SmallVector<unsigned, 1> MismatchedParams;
  7871. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  7872. TypoCorrection Correction;
  7873. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  7874. unsigned DiagMsg =
  7875. IsLocalFriend ? diag::err_no_matching_local_friend :
  7876. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  7877. diag::err_member_decl_does_not_match;
  7878. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  7879. IsLocalFriend ? Sema::LookupLocalFriendName
  7880. : Sema::LookupOrdinaryName,
  7881. Sema::ForVisibleRedeclaration);
  7882. NewFD->setInvalidDecl();
  7883. if (IsLocalFriend)
  7884. SemaRef.LookupName(Prev, S);
  7885. else
  7886. SemaRef.LookupQualifiedName(Prev, NewDC);
  7887. assert(!Prev.isAmbiguous() &&
  7888. "Cannot have an ambiguity in previous-declaration lookup");
  7889. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  7890. DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
  7891. MD ? MD->getParent() : nullptr);
  7892. if (!Prev.empty()) {
  7893. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  7894. Func != FuncEnd; ++Func) {
  7895. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  7896. if (FD &&
  7897. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7898. // Add 1 to the index so that 0 can mean the mismatch didn't
  7899. // involve a parameter
  7900. unsigned ParamNum =
  7901. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  7902. NearMatches.push_back(std::make_pair(FD, ParamNum));
  7903. }
  7904. }
  7905. // If the qualified name lookup yielded nothing, try typo correction
  7906. } else if ((Correction = SemaRef.CorrectTypo(
  7907. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  7908. &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
  7909. IsLocalFriend ? nullptr : NewDC))) {
  7910. // Set up everything for the call to ActOnFunctionDeclarator
  7911. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  7912. ExtraArgs.D.getIdentifierLoc());
  7913. Previous.clear();
  7914. Previous.setLookupName(Correction.getCorrection());
  7915. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  7916. CDeclEnd = Correction.end();
  7917. CDecl != CDeclEnd; ++CDecl) {
  7918. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  7919. if (FD && !FD->hasBody() &&
  7920. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  7921. Previous.addDecl(FD);
  7922. }
  7923. }
  7924. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  7925. NamedDecl *Result;
  7926. // Retry building the function declaration with the new previous
  7927. // declarations, and with errors suppressed.
  7928. {
  7929. // Trap errors.
  7930. Sema::SFINAETrap Trap(SemaRef);
  7931. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  7932. // pieces need to verify the typo-corrected C++ declaration and hopefully
  7933. // eliminate the need for the parameter pack ExtraArgs.
  7934. Result = SemaRef.ActOnFunctionDeclarator(
  7935. ExtraArgs.S, ExtraArgs.D,
  7936. Correction.getCorrectionDecl()->getDeclContext(),
  7937. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  7938. ExtraArgs.AddToScope);
  7939. if (Trap.hasErrorOccurred())
  7940. Result = nullptr;
  7941. }
  7942. if (Result) {
  7943. // Determine which correction we picked.
  7944. Decl *Canonical = Result->getCanonicalDecl();
  7945. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  7946. I != E; ++I)
  7947. if ((*I)->getCanonicalDecl() == Canonical)
  7948. Correction.setCorrectionDecl(*I);
  7949. // Let Sema know about the correction.
  7950. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  7951. SemaRef.diagnoseTypo(
  7952. Correction,
  7953. SemaRef.PDiag(IsLocalFriend
  7954. ? diag::err_no_matching_local_friend_suggest
  7955. : diag::err_member_decl_does_not_match_suggest)
  7956. << Name << NewDC << IsDefinition);
  7957. return Result;
  7958. }
  7959. // Pretend the typo correction never occurred
  7960. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  7961. ExtraArgs.D.getIdentifierLoc());
  7962. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  7963. Previous.clear();
  7964. Previous.setLookupName(Name);
  7965. }
  7966. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  7967. << Name << NewDC << IsDefinition << NewFD->getLocation();
  7968. bool NewFDisConst = false;
  7969. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  7970. NewFDisConst = NewMD->isConst();
  7971. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  7972. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  7973. NearMatch != NearMatchEnd; ++NearMatch) {
  7974. FunctionDecl *FD = NearMatch->first;
  7975. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  7976. bool FDisConst = MD && MD->isConst();
  7977. bool IsMember = MD || !IsLocalFriend;
  7978. // FIXME: These notes are poorly worded for the local friend case.
  7979. if (unsigned Idx = NearMatch->second) {
  7980. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  7981. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  7982. if (Loc.isInvalid()) Loc = FD->getLocation();
  7983. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  7984. : diag::note_local_decl_close_param_match)
  7985. << Idx << FDParam->getType()
  7986. << NewFD->getParamDecl(Idx - 1)->getType();
  7987. } else if (FDisConst != NewFDisConst) {
  7988. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  7989. << NewFDisConst << FD->getSourceRange().getEnd()
  7990. << (NewFDisConst
  7991. ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
  7992. .getConstQualifierLoc())
  7993. : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
  7994. .getRParenLoc()
  7995. .getLocWithOffset(1),
  7996. " const"));
  7997. } else
  7998. SemaRef.Diag(FD->getLocation(),
  7999. IsMember ? diag::note_member_def_close_match
  8000. : diag::note_local_decl_close_match);
  8001. }
  8002. return nullptr;
  8003. }
  8004. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  8005. switch (D.getDeclSpec().getStorageClassSpec()) {
  8006. default: llvm_unreachable("Unknown storage class!");
  8007. case DeclSpec::SCS_auto:
  8008. case DeclSpec::SCS_register:
  8009. case DeclSpec::SCS_mutable:
  8010. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  8011. diag::err_typecheck_sclass_func);
  8012. D.getMutableDeclSpec().ClearStorageClassSpecs();
  8013. D.setInvalidType();
  8014. break;
  8015. case DeclSpec::SCS_unspecified: break;
  8016. case DeclSpec::SCS_extern:
  8017. if (D.getDeclSpec().isExternInLinkageSpec())
  8018. return SC_None;
  8019. return SC_Extern;
  8020. case DeclSpec::SCS_static: {
  8021. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  8022. // C99 6.7.1p5:
  8023. // The declaration of an identifier for a function that has
  8024. // block scope shall have no explicit storage-class specifier
  8025. // other than extern
  8026. // See also (C++ [dcl.stc]p4).
  8027. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  8028. diag::err_static_block_func);
  8029. break;
  8030. } else
  8031. return SC_Static;
  8032. }
  8033. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  8034. }
  8035. // No explicit storage class has already been returned
  8036. return SC_None;
  8037. }
  8038. static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  8039. DeclContext *DC, QualType &R,
  8040. TypeSourceInfo *TInfo,
  8041. StorageClass SC,
  8042. bool &IsVirtualOkay) {
  8043. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  8044. DeclarationName Name = NameInfo.getName();
  8045. FunctionDecl *NewFD = nullptr;
  8046. bool isInline = D.getDeclSpec().isInlineSpecified();
  8047. if (!SemaRef.getLangOpts().CPlusPlus) {
  8048. // Determine whether the function was written with a prototype. This is
  8049. // true when:
  8050. // - there is a prototype in the declarator, or
  8051. // - the type R of the function is some kind of typedef or other non-
  8052. // attributed reference to a type name (which eventually refers to a
  8053. // function type). Note, we can't always look at the adjusted type to
  8054. // check this case because attributes may cause a non-function
  8055. // declarator to still have a function type. e.g.,
  8056. // typedef void func(int a);
  8057. // __attribute__((noreturn)) func other_func; // This has a prototype
  8058. bool HasPrototype =
  8059. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  8060. (D.getDeclSpec().isTypeRep() &&
  8061. D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) ||
  8062. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  8063. assert(
  8064. (HasPrototype || !SemaRef.getLangOpts().requiresStrictPrototypes()) &&
  8065. "Strict prototypes are required");
  8066. NewFD = FunctionDecl::Create(
  8067. SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
  8068. SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
  8069. ConstexprSpecKind::Unspecified,
  8070. /*TrailingRequiresClause=*/nullptr);
  8071. if (D.isInvalidType())
  8072. NewFD->setInvalidDecl();
  8073. return NewFD;
  8074. }
  8075. ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
  8076. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  8077. if (ConstexprKind == ConstexprSpecKind::Constinit) {
  8078. SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
  8079. diag::err_constexpr_wrong_decl_kind)
  8080. << static_cast<int>(ConstexprKind);
  8081. ConstexprKind = ConstexprSpecKind::Unspecified;
  8082. D.getMutableDeclSpec().ClearConstexprSpec();
  8083. }
  8084. Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
  8085. // Check that the return type is not an abstract class type.
  8086. // For record types, this is done by the AbstractClassUsageDiagnoser once
  8087. // the class has been completely parsed.
  8088. if (!DC->isRecord() &&
  8089. SemaRef.RequireNonAbstractType(
  8090. D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
  8091. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  8092. D.setInvalidType();
  8093. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  8094. // This is a C++ constructor declaration.
  8095. assert(DC->isRecord() &&
  8096. "Constructors can only be declared in a member context");
  8097. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  8098. return CXXConstructorDecl::Create(
  8099. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  8100. TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
  8101. isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
  8102. InheritedConstructor(), TrailingRequiresClause);
  8103. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  8104. // This is a C++ destructor declaration.
  8105. if (DC->isRecord()) {
  8106. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  8107. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  8108. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  8109. SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
  8110. SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  8111. /*isImplicitlyDeclared=*/false, ConstexprKind,
  8112. TrailingRequiresClause);
  8113. // User defined destructors start as not selected if the class definition is still
  8114. // not done.
  8115. if (Record->isBeingDefined())
  8116. NewDD->setIneligibleOrNotSelected(true);
  8117. // If the destructor needs an implicit exception specification, set it
  8118. // now. FIXME: It'd be nice to be able to create the right type to start
  8119. // with, but the type needs to reference the destructor declaration.
  8120. if (SemaRef.getLangOpts().CPlusPlus11)
  8121. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  8122. IsVirtualOkay = true;
  8123. return NewDD;
  8124. } else {
  8125. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  8126. D.setInvalidType();
  8127. // Create a FunctionDecl to satisfy the function definition parsing
  8128. // code path.
  8129. return FunctionDecl::Create(
  8130. SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
  8131. TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  8132. /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
  8133. }
  8134. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  8135. if (!DC->isRecord()) {
  8136. SemaRef.Diag(D.getIdentifierLoc(),
  8137. diag::err_conv_function_not_member);
  8138. return nullptr;
  8139. }
  8140. SemaRef.CheckConversionDeclarator(D, R, SC);
  8141. if (D.isInvalidType())
  8142. return nullptr;
  8143. IsVirtualOkay = true;
  8144. return CXXConversionDecl::Create(
  8145. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  8146. TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  8147. ExplicitSpecifier, ConstexprKind, SourceLocation(),
  8148. TrailingRequiresClause);
  8149. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  8150. if (TrailingRequiresClause)
  8151. SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
  8152. diag::err_trailing_requires_clause_on_deduction_guide)
  8153. << TrailingRequiresClause->getSourceRange();
  8154. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  8155. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  8156. ExplicitSpecifier, NameInfo, R, TInfo,
  8157. D.getEndLoc());
  8158. } else if (DC->isRecord()) {
  8159. // If the name of the function is the same as the name of the record,
  8160. // then this must be an invalid constructor that has a return type.
  8161. // (The parser checks for a return type and makes the declarator a
  8162. // constructor if it has no return type).
  8163. if (Name.getAsIdentifierInfo() &&
  8164. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  8165. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  8166. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  8167. << SourceRange(D.getIdentifierLoc());
  8168. return nullptr;
  8169. }
  8170. // This is a C++ method declaration.
  8171. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  8172. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  8173. TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  8174. ConstexprKind, SourceLocation(), TrailingRequiresClause);
  8175. IsVirtualOkay = !Ret->isStatic();
  8176. return Ret;
  8177. } else {
  8178. bool isFriend =
  8179. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  8180. if (!isFriend && SemaRef.CurContext->isRecord())
  8181. return nullptr;
  8182. // Determine whether the function was written with a
  8183. // prototype. This true when:
  8184. // - we're in C++ (where every function has a prototype),
  8185. return FunctionDecl::Create(
  8186. SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
  8187. SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
  8188. true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
  8189. }
  8190. }
  8191. enum OpenCLParamType {
  8192. ValidKernelParam,
  8193. PtrPtrKernelParam,
  8194. PtrKernelParam,
  8195. InvalidAddrSpacePtrKernelParam,
  8196. InvalidKernelParam,
  8197. RecordKernelParam
  8198. };
  8199. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  8200. // Size dependent types are just typedefs to normal integer types
  8201. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  8202. // integers other than by their names.
  8203. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  8204. // Remove typedefs one by one until we reach a typedef
  8205. // for a size dependent type.
  8206. QualType DesugaredTy = Ty;
  8207. do {
  8208. ArrayRef<StringRef> Names(SizeTypeNames);
  8209. auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
  8210. if (Names.end() != Match)
  8211. return true;
  8212. Ty = DesugaredTy;
  8213. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  8214. } while (DesugaredTy != Ty);
  8215. return false;
  8216. }
  8217. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  8218. if (PT->isDependentType())
  8219. return InvalidKernelParam;
  8220. if (PT->isPointerType() || PT->isReferenceType()) {
  8221. QualType PointeeType = PT->getPointeeType();
  8222. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  8223. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  8224. PointeeType.getAddressSpace() == LangAS::Default)
  8225. return InvalidAddrSpacePtrKernelParam;
  8226. if (PointeeType->isPointerType()) {
  8227. // This is a pointer to pointer parameter.
  8228. // Recursively check inner type.
  8229. OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
  8230. if (ParamKind == InvalidAddrSpacePtrKernelParam ||
  8231. ParamKind == InvalidKernelParam)
  8232. return ParamKind;
  8233. return PtrPtrKernelParam;
  8234. }
  8235. // C++ for OpenCL v1.0 s2.4:
  8236. // Moreover the types used in parameters of the kernel functions must be:
  8237. // Standard layout types for pointer parameters. The same applies to
  8238. // reference if an implementation supports them in kernel parameters.
  8239. if (S.getLangOpts().OpenCLCPlusPlus &&
  8240. !S.getOpenCLOptions().isAvailableOption(
  8241. "__cl_clang_non_portable_kernel_param_types", S.getLangOpts())) {
  8242. auto CXXRec = PointeeType.getCanonicalType()->getAsCXXRecordDecl();
  8243. bool IsStandardLayoutType = true;
  8244. if (CXXRec) {
  8245. // If template type is not ODR-used its definition is only available
  8246. // in the template definition not its instantiation.
  8247. // FIXME: This logic doesn't work for types that depend on template
  8248. // parameter (PR58590).
  8249. if (!CXXRec->hasDefinition())
  8250. CXXRec = CXXRec->getTemplateInstantiationPattern();
  8251. if (!CXXRec || !CXXRec->hasDefinition() || !CXXRec->isStandardLayout())
  8252. IsStandardLayoutType = false;
  8253. }
  8254. if (!PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
  8255. !IsStandardLayoutType)
  8256. return InvalidKernelParam;
  8257. }
  8258. return PtrKernelParam;
  8259. }
  8260. // OpenCL v1.2 s6.9.k:
  8261. // Arguments to kernel functions in a program cannot be declared with the
  8262. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  8263. // uintptr_t or a struct and/or union that contain fields declared to be one
  8264. // of these built-in scalar types.
  8265. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  8266. return InvalidKernelParam;
  8267. if (PT->isImageType())
  8268. return PtrKernelParam;
  8269. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  8270. return InvalidKernelParam;
  8271. // OpenCL extension spec v1.2 s9.5:
  8272. // This extension adds support for half scalar and vector types as built-in
  8273. // types that can be used for arithmetic operations, conversions etc.
  8274. if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
  8275. PT->isHalfType())
  8276. return InvalidKernelParam;
  8277. // Look into an array argument to check if it has a forbidden type.
  8278. if (PT->isArrayType()) {
  8279. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  8280. // Call ourself to check an underlying type of an array. Since the
  8281. // getPointeeOrArrayElementType returns an innermost type which is not an
  8282. // array, this recursive call only happens once.
  8283. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  8284. }
  8285. // C++ for OpenCL v1.0 s2.4:
  8286. // Moreover the types used in parameters of the kernel functions must be:
  8287. // Trivial and standard-layout types C++17 [basic.types] (plain old data
  8288. // types) for parameters passed by value;
  8289. if (S.getLangOpts().OpenCLCPlusPlus &&
  8290. !S.getOpenCLOptions().isAvailableOption(
  8291. "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
  8292. !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
  8293. return InvalidKernelParam;
  8294. if (PT->isRecordType())
  8295. return RecordKernelParam;
  8296. return ValidKernelParam;
  8297. }
  8298. static void checkIsValidOpenCLKernelParameter(
  8299. Sema &S,
  8300. Declarator &D,
  8301. ParmVarDecl *Param,
  8302. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  8303. QualType PT = Param->getType();
  8304. // Cache the valid types we encounter to avoid rechecking structs that are
  8305. // used again
  8306. if (ValidTypes.count(PT.getTypePtr()))
  8307. return;
  8308. switch (getOpenCLKernelParameterType(S, PT)) {
  8309. case PtrPtrKernelParam:
  8310. // OpenCL v3.0 s6.11.a:
  8311. // A kernel function argument cannot be declared as a pointer to a pointer
  8312. // type. [...] This restriction only applies to OpenCL C 1.2 or below.
  8313. if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
  8314. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  8315. D.setInvalidType();
  8316. return;
  8317. }
  8318. ValidTypes.insert(PT.getTypePtr());
  8319. return;
  8320. case InvalidAddrSpacePtrKernelParam:
  8321. // OpenCL v1.0 s6.5:
  8322. // __kernel function arguments declared to be a pointer of a type can point
  8323. // to one of the following address spaces only : __global, __local or
  8324. // __constant.
  8325. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  8326. D.setInvalidType();
  8327. return;
  8328. // OpenCL v1.2 s6.9.k:
  8329. // Arguments to kernel functions in a program cannot be declared with the
  8330. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  8331. // uintptr_t or a struct and/or union that contain fields declared to be
  8332. // one of these built-in scalar types.
  8333. case InvalidKernelParam:
  8334. // OpenCL v1.2 s6.8 n:
  8335. // A kernel function argument cannot be declared
  8336. // of event_t type.
  8337. // Do not diagnose half type since it is diagnosed as invalid argument
  8338. // type for any function elsewhere.
  8339. if (!PT->isHalfType()) {
  8340. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  8341. // Explain what typedefs are involved.
  8342. const TypedefType *Typedef = nullptr;
  8343. while ((Typedef = PT->getAs<TypedefType>())) {
  8344. SourceLocation Loc = Typedef->getDecl()->getLocation();
  8345. // SourceLocation may be invalid for a built-in type.
  8346. if (Loc.isValid())
  8347. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  8348. PT = Typedef->desugar();
  8349. }
  8350. }
  8351. D.setInvalidType();
  8352. return;
  8353. case PtrKernelParam:
  8354. case ValidKernelParam:
  8355. ValidTypes.insert(PT.getTypePtr());
  8356. return;
  8357. case RecordKernelParam:
  8358. break;
  8359. }
  8360. // Track nested structs we will inspect
  8361. SmallVector<const Decl *, 4> VisitStack;
  8362. // Track where we are in the nested structs. Items will migrate from
  8363. // VisitStack to HistoryStack as we do the DFS for bad field.
  8364. SmallVector<const FieldDecl *, 4> HistoryStack;
  8365. HistoryStack.push_back(nullptr);
  8366. // At this point we already handled everything except of a RecordType or
  8367. // an ArrayType of a RecordType.
  8368. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  8369. const RecordType *RecTy =
  8370. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  8371. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  8372. VisitStack.push_back(RecTy->getDecl());
  8373. assert(VisitStack.back() && "First decl null?");
  8374. do {
  8375. const Decl *Next = VisitStack.pop_back_val();
  8376. if (!Next) {
  8377. assert(!HistoryStack.empty());
  8378. // Found a marker, we have gone up a level
  8379. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  8380. ValidTypes.insert(Hist->getType().getTypePtr());
  8381. continue;
  8382. }
  8383. // Adds everything except the original parameter declaration (which is not a
  8384. // field itself) to the history stack.
  8385. const RecordDecl *RD;
  8386. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  8387. HistoryStack.push_back(Field);
  8388. QualType FieldTy = Field->getType();
  8389. // Other field types (known to be valid or invalid) are handled while we
  8390. // walk around RecordDecl::fields().
  8391. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  8392. "Unexpected type.");
  8393. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  8394. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  8395. } else {
  8396. RD = cast<RecordDecl>(Next);
  8397. }
  8398. // Add a null marker so we know when we've gone back up a level
  8399. VisitStack.push_back(nullptr);
  8400. for (const auto *FD : RD->fields()) {
  8401. QualType QT = FD->getType();
  8402. if (ValidTypes.count(QT.getTypePtr()))
  8403. continue;
  8404. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  8405. if (ParamType == ValidKernelParam)
  8406. continue;
  8407. if (ParamType == RecordKernelParam) {
  8408. VisitStack.push_back(FD);
  8409. continue;
  8410. }
  8411. // OpenCL v1.2 s6.9.p:
  8412. // Arguments to kernel functions that are declared to be a struct or union
  8413. // do not allow OpenCL objects to be passed as elements of the struct or
  8414. // union.
  8415. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  8416. ParamType == InvalidAddrSpacePtrKernelParam) {
  8417. S.Diag(Param->getLocation(),
  8418. diag::err_record_with_pointers_kernel_param)
  8419. << PT->isUnionType()
  8420. << PT;
  8421. } else {
  8422. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  8423. }
  8424. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  8425. << OrigRecDecl->getDeclName();
  8426. // We have an error, now let's go back up through history and show where
  8427. // the offending field came from
  8428. for (ArrayRef<const FieldDecl *>::const_iterator
  8429. I = HistoryStack.begin() + 1,
  8430. E = HistoryStack.end();
  8431. I != E; ++I) {
  8432. const FieldDecl *OuterField = *I;
  8433. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  8434. << OuterField->getType();
  8435. }
  8436. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  8437. << QT->isPointerType()
  8438. << QT;
  8439. D.setInvalidType();
  8440. return;
  8441. }
  8442. } while (!VisitStack.empty());
  8443. }
  8444. /// Find the DeclContext in which a tag is implicitly declared if we see an
  8445. /// elaborated type specifier in the specified context, and lookup finds
  8446. /// nothing.
  8447. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  8448. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  8449. DC = DC->getParent();
  8450. return DC;
  8451. }
  8452. /// Find the Scope in which a tag is implicitly declared if we see an
  8453. /// elaborated type specifier in the specified context, and lookup finds
  8454. /// nothing.
  8455. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  8456. while (S->isClassScope() ||
  8457. (LangOpts.CPlusPlus &&
  8458. S->isFunctionPrototypeScope()) ||
  8459. ((S->getFlags() & Scope::DeclScope) == 0) ||
  8460. (S->getEntity() && S->getEntity()->isTransparentContext()))
  8461. S = S->getParent();
  8462. return S;
  8463. }
  8464. /// Determine whether a declaration matches a known function in namespace std.
  8465. static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD,
  8466. unsigned BuiltinID) {
  8467. switch (BuiltinID) {
  8468. case Builtin::BI__GetExceptionInfo:
  8469. // No type checking whatsoever.
  8470. return Ctx.getTargetInfo().getCXXABI().isMicrosoft();
  8471. case Builtin::BIaddressof:
  8472. case Builtin::BI__addressof:
  8473. case Builtin::BIforward:
  8474. case Builtin::BImove:
  8475. case Builtin::BImove_if_noexcept:
  8476. case Builtin::BIas_const: {
  8477. // Ensure that we don't treat the algorithm
  8478. // OutputIt std::move(InputIt, InputIt, OutputIt)
  8479. // as the builtin std::move.
  8480. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  8481. return FPT->getNumParams() == 1 && !FPT->isVariadic();
  8482. }
  8483. default:
  8484. return false;
  8485. }
  8486. }
  8487. NamedDecl*
  8488. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  8489. TypeSourceInfo *TInfo, LookupResult &Previous,
  8490. MultiTemplateParamsArg TemplateParamListsRef,
  8491. bool &AddToScope) {
  8492. QualType R = TInfo->getType();
  8493. assert(R->isFunctionType());
  8494. if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
  8495. Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
  8496. SmallVector<TemplateParameterList *, 4> TemplateParamLists;
  8497. llvm::append_range(TemplateParamLists, TemplateParamListsRef);
  8498. if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
  8499. if (!TemplateParamLists.empty() &&
  8500. Invented->getDepth() == TemplateParamLists.back()->getDepth())
  8501. TemplateParamLists.back() = Invented;
  8502. else
  8503. TemplateParamLists.push_back(Invented);
  8504. }
  8505. // TODO: consider using NameInfo for diagnostic.
  8506. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  8507. DeclarationName Name = NameInfo.getName();
  8508. StorageClass SC = getFunctionStorageClass(*this, D);
  8509. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  8510. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  8511. diag::err_invalid_thread)
  8512. << DeclSpec::getSpecifierName(TSCS);
  8513. if (D.isFirstDeclarationOfMember())
  8514. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  8515. D.getIdentifierLoc());
  8516. bool isFriend = false;
  8517. FunctionTemplateDecl *FunctionTemplate = nullptr;
  8518. bool isMemberSpecialization = false;
  8519. bool isFunctionTemplateSpecialization = false;
  8520. bool isDependentClassScopeExplicitSpecialization = false;
  8521. bool HasExplicitTemplateArgs = false;
  8522. TemplateArgumentListInfo TemplateArgs;
  8523. bool isVirtualOkay = false;
  8524. DeclContext *OriginalDC = DC;
  8525. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  8526. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  8527. isVirtualOkay);
  8528. if (!NewFD) return nullptr;
  8529. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  8530. NewFD->setTopLevelDeclInObjCContainer();
  8531. // Set the lexical context. If this is a function-scope declaration, or has a
  8532. // C++ scope specifier, or is the object of a friend declaration, the lexical
  8533. // context will be different from the semantic context.
  8534. NewFD->setLexicalDeclContext(CurContext);
  8535. if (IsLocalExternDecl)
  8536. NewFD->setLocalExternDecl();
  8537. if (getLangOpts().CPlusPlus) {
  8538. // The rules for implicit inlines changed in C++20 for methods and friends
  8539. // with an in-class definition (when such a definition is not attached to
  8540. // the global module). User-specified 'inline' overrides this (set when
  8541. // the function decl is created above).
  8542. // FIXME: We need a better way to separate C++ standard and clang modules.
  8543. bool ImplicitInlineCXX20 = !getLangOpts().CPlusPlusModules ||
  8544. !NewFD->getOwningModule() ||
  8545. NewFD->getOwningModule()->isGlobalModule() ||
  8546. NewFD->getOwningModule()->isHeaderLikeModule();
  8547. bool isInline = D.getDeclSpec().isInlineSpecified();
  8548. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  8549. bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
  8550. isFriend = D.getDeclSpec().isFriendSpecified();
  8551. if (isFriend && !isInline && D.isFunctionDefinition()) {
  8552. // Pre-C++20 [class.friend]p5
  8553. // A function can be defined in a friend declaration of a
  8554. // class . . . . Such a function is implicitly inline.
  8555. // Post C++20 [class.friend]p7
  8556. // Such a function is implicitly an inline function if it is attached
  8557. // to the global module.
  8558. NewFD->setImplicitlyInline(ImplicitInlineCXX20);
  8559. }
  8560. // If this is a method defined in an __interface, and is not a constructor
  8561. // or an overloaded operator, then set the pure flag (isVirtual will already
  8562. // return true).
  8563. if (const CXXRecordDecl *Parent =
  8564. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  8565. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  8566. NewFD->setPure(true);
  8567. // C++ [class.union]p2
  8568. // A union can have member functions, but not virtual functions.
  8569. if (isVirtual && Parent->isUnion()) {
  8570. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  8571. NewFD->setInvalidDecl();
  8572. }
  8573. if ((Parent->isClass() || Parent->isStruct()) &&
  8574. Parent->hasAttr<SYCLSpecialClassAttr>() &&
  8575. NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
  8576. NewFD->getName() == "__init" && D.isFunctionDefinition()) {
  8577. if (auto *Def = Parent->getDefinition())
  8578. Def->setInitMethod(true);
  8579. }
  8580. }
  8581. SetNestedNameSpecifier(*this, NewFD, D);
  8582. isMemberSpecialization = false;
  8583. isFunctionTemplateSpecialization = false;
  8584. if (D.isInvalidType())
  8585. NewFD->setInvalidDecl();
  8586. // Match up the template parameter lists with the scope specifier, then
  8587. // determine whether we have a template or a template specialization.
  8588. bool Invalid = false;
  8589. TemplateParameterList *TemplateParams =
  8590. MatchTemplateParametersToScopeSpecifier(
  8591. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  8592. D.getCXXScopeSpec(),
  8593. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  8594. ? D.getName().TemplateId
  8595. : nullptr,
  8596. TemplateParamLists, isFriend, isMemberSpecialization,
  8597. Invalid);
  8598. if (TemplateParams) {
  8599. // Check that we can declare a template here.
  8600. if (CheckTemplateDeclScope(S, TemplateParams))
  8601. NewFD->setInvalidDecl();
  8602. if (TemplateParams->size() > 0) {
  8603. // This is a function template
  8604. // A destructor cannot be a template.
  8605. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  8606. Diag(NewFD->getLocation(), diag::err_destructor_template);
  8607. NewFD->setInvalidDecl();
  8608. }
  8609. // If we're adding a template to a dependent context, we may need to
  8610. // rebuilding some of the types used within the template parameter list,
  8611. // now that we know what the current instantiation is.
  8612. if (DC->isDependentContext()) {
  8613. ContextRAII SavedContext(*this, DC);
  8614. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  8615. Invalid = true;
  8616. }
  8617. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  8618. NewFD->getLocation(),
  8619. Name, TemplateParams,
  8620. NewFD);
  8621. FunctionTemplate->setLexicalDeclContext(CurContext);
  8622. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  8623. // For source fidelity, store the other template param lists.
  8624. if (TemplateParamLists.size() > 1) {
  8625. NewFD->setTemplateParameterListsInfo(Context,
  8626. ArrayRef<TemplateParameterList *>(TemplateParamLists)
  8627. .drop_back(1));
  8628. }
  8629. } else {
  8630. // This is a function template specialization.
  8631. isFunctionTemplateSpecialization = true;
  8632. // For source fidelity, store all the template param lists.
  8633. if (TemplateParamLists.size() > 0)
  8634. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  8635. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  8636. if (isFriend) {
  8637. // We want to remove the "template<>", found here.
  8638. SourceRange RemoveRange = TemplateParams->getSourceRange();
  8639. // If we remove the template<> and the name is not a
  8640. // template-id, we're actually silently creating a problem:
  8641. // the friend declaration will refer to an untemplated decl,
  8642. // and clearly the user wants a template specialization. So
  8643. // we need to insert '<>' after the name.
  8644. SourceLocation InsertLoc;
  8645. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  8646. InsertLoc = D.getName().getSourceRange().getEnd();
  8647. InsertLoc = getLocForEndOfToken(InsertLoc);
  8648. }
  8649. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  8650. << Name << RemoveRange
  8651. << FixItHint::CreateRemoval(RemoveRange)
  8652. << FixItHint::CreateInsertion(InsertLoc, "<>");
  8653. Invalid = true;
  8654. }
  8655. }
  8656. } else {
  8657. // Check that we can declare a template here.
  8658. if (!TemplateParamLists.empty() && isMemberSpecialization &&
  8659. CheckTemplateDeclScope(S, TemplateParamLists.back()))
  8660. NewFD->setInvalidDecl();
  8661. // All template param lists were matched against the scope specifier:
  8662. // this is NOT (an explicit specialization of) a template.
  8663. if (TemplateParamLists.size() > 0)
  8664. // For source fidelity, store all the template param lists.
  8665. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  8666. }
  8667. if (Invalid) {
  8668. NewFD->setInvalidDecl();
  8669. if (FunctionTemplate)
  8670. FunctionTemplate->setInvalidDecl();
  8671. }
  8672. // C++ [dcl.fct.spec]p5:
  8673. // The virtual specifier shall only be used in declarations of
  8674. // nonstatic class member functions that appear within a
  8675. // member-specification of a class declaration; see 10.3.
  8676. //
  8677. if (isVirtual && !NewFD->isInvalidDecl()) {
  8678. if (!isVirtualOkay) {
  8679. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8680. diag::err_virtual_non_function);
  8681. } else if (!CurContext->isRecord()) {
  8682. // 'virtual' was specified outside of the class.
  8683. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8684. diag::err_virtual_out_of_class)
  8685. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  8686. } else if (NewFD->getDescribedFunctionTemplate()) {
  8687. // C++ [temp.mem]p3:
  8688. // A member function template shall not be virtual.
  8689. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  8690. diag::err_virtual_member_function_template)
  8691. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  8692. } else {
  8693. // Okay: Add virtual to the method.
  8694. NewFD->setVirtualAsWritten(true);
  8695. }
  8696. if (getLangOpts().CPlusPlus14 &&
  8697. NewFD->getReturnType()->isUndeducedType())
  8698. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  8699. }
  8700. if (getLangOpts().CPlusPlus14 &&
  8701. (NewFD->isDependentContext() ||
  8702. (isFriend && CurContext->isDependentContext())) &&
  8703. NewFD->getReturnType()->isUndeducedType()) {
  8704. // If the function template is referenced directly (for instance, as a
  8705. // member of the current instantiation), pretend it has a dependent type.
  8706. // This is not really justified by the standard, but is the only sane
  8707. // thing to do.
  8708. // FIXME: For a friend function, we have not marked the function as being
  8709. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  8710. const FunctionProtoType *FPT =
  8711. NewFD->getType()->castAs<FunctionProtoType>();
  8712. QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
  8713. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  8714. FPT->getExtProtoInfo()));
  8715. }
  8716. // C++ [dcl.fct.spec]p3:
  8717. // The inline specifier shall not appear on a block scope function
  8718. // declaration.
  8719. if (isInline && !NewFD->isInvalidDecl()) {
  8720. if (CurContext->isFunctionOrMethod()) {
  8721. // 'inline' is not allowed on block scope function declaration.
  8722. Diag(D.getDeclSpec().getInlineSpecLoc(),
  8723. diag::err_inline_declaration_block_scope) << Name
  8724. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  8725. }
  8726. }
  8727. // C++ [dcl.fct.spec]p6:
  8728. // The explicit specifier shall be used only in the declaration of a
  8729. // constructor or conversion function within its class definition;
  8730. // see 12.3.1 and 12.3.2.
  8731. if (hasExplicit && !NewFD->isInvalidDecl() &&
  8732. !isa<CXXDeductionGuideDecl>(NewFD)) {
  8733. if (!CurContext->isRecord()) {
  8734. // 'explicit' was specified outside of the class.
  8735. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  8736. diag::err_explicit_out_of_class)
  8737. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  8738. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  8739. !isa<CXXConversionDecl>(NewFD)) {
  8740. // 'explicit' was specified on a function that wasn't a constructor
  8741. // or conversion function.
  8742. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  8743. diag::err_explicit_non_ctor_or_conv_function)
  8744. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
  8745. }
  8746. }
  8747. ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
  8748. if (ConstexprKind != ConstexprSpecKind::Unspecified) {
  8749. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  8750. // are implicitly inline.
  8751. NewFD->setImplicitlyInline();
  8752. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  8753. // be either constructors or to return a literal type. Therefore,
  8754. // destructors cannot be declared constexpr.
  8755. if (isa<CXXDestructorDecl>(NewFD) &&
  8756. (!getLangOpts().CPlusPlus20 ||
  8757. ConstexprKind == ConstexprSpecKind::Consteval)) {
  8758. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
  8759. << static_cast<int>(ConstexprKind);
  8760. NewFD->setConstexprKind(getLangOpts().CPlusPlus20
  8761. ? ConstexprSpecKind::Unspecified
  8762. : ConstexprSpecKind::Constexpr);
  8763. }
  8764. // C++20 [dcl.constexpr]p2: An allocation function, or a
  8765. // deallocation function shall not be declared with the consteval
  8766. // specifier.
  8767. if (ConstexprKind == ConstexprSpecKind::Consteval &&
  8768. (NewFD->getOverloadedOperator() == OO_New ||
  8769. NewFD->getOverloadedOperator() == OO_Array_New ||
  8770. NewFD->getOverloadedOperator() == OO_Delete ||
  8771. NewFD->getOverloadedOperator() == OO_Array_Delete)) {
  8772. Diag(D.getDeclSpec().getConstexprSpecLoc(),
  8773. diag::err_invalid_consteval_decl_kind)
  8774. << NewFD;
  8775. NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
  8776. }
  8777. }
  8778. // If __module_private__ was specified, mark the function accordingly.
  8779. if (D.getDeclSpec().isModulePrivateSpecified()) {
  8780. if (isFunctionTemplateSpecialization) {
  8781. SourceLocation ModulePrivateLoc
  8782. = D.getDeclSpec().getModulePrivateSpecLoc();
  8783. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  8784. << 0
  8785. << FixItHint::CreateRemoval(ModulePrivateLoc);
  8786. } else {
  8787. NewFD->setModulePrivate();
  8788. if (FunctionTemplate)
  8789. FunctionTemplate->setModulePrivate();
  8790. }
  8791. }
  8792. if (isFriend) {
  8793. if (FunctionTemplate) {
  8794. FunctionTemplate->setObjectOfFriendDecl();
  8795. FunctionTemplate->setAccess(AS_public);
  8796. }
  8797. NewFD->setObjectOfFriendDecl();
  8798. NewFD->setAccess(AS_public);
  8799. }
  8800. // If a function is defined as defaulted or deleted, mark it as such now.
  8801. // We'll do the relevant checks on defaulted / deleted functions later.
  8802. switch (D.getFunctionDefinitionKind()) {
  8803. case FunctionDefinitionKind::Declaration:
  8804. case FunctionDefinitionKind::Definition:
  8805. break;
  8806. case FunctionDefinitionKind::Defaulted:
  8807. NewFD->setDefaulted();
  8808. break;
  8809. case FunctionDefinitionKind::Deleted:
  8810. NewFD->setDeletedAsWritten();
  8811. break;
  8812. }
  8813. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  8814. D.isFunctionDefinition() && !isInline) {
  8815. // Pre C++20 [class.mfct]p2:
  8816. // A member function may be defined (8.4) in its class definition, in
  8817. // which case it is an inline member function (7.1.2)
  8818. // Post C++20 [class.mfct]p1:
  8819. // If a member function is attached to the global module and is defined
  8820. // in its class definition, it is inline.
  8821. NewFD->setImplicitlyInline(ImplicitInlineCXX20);
  8822. }
  8823. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  8824. !CurContext->isRecord()) {
  8825. // C++ [class.static]p1:
  8826. // A data or function member of a class may be declared static
  8827. // in a class definition, in which case it is a static member of
  8828. // the class.
  8829. // Complain about the 'static' specifier if it's on an out-of-line
  8830. // member function definition.
  8831. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  8832. // member function template declaration and class member template
  8833. // declaration (MSVC versions before 2015), warn about this.
  8834. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  8835. ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
  8836. cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
  8837. (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
  8838. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  8839. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  8840. }
  8841. // C++11 [except.spec]p15:
  8842. // A deallocation function with no exception-specification is treated
  8843. // as if it were specified with noexcept(true).
  8844. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  8845. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  8846. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  8847. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  8848. NewFD->setType(Context.getFunctionType(
  8849. FPT->getReturnType(), FPT->getParamTypes(),
  8850. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  8851. // C++20 [dcl.inline]/7
  8852. // If an inline function or variable that is attached to a named module
  8853. // is declared in a definition domain, it shall be defined in that
  8854. // domain.
  8855. // So, if the current declaration does not have a definition, we must
  8856. // check at the end of the TU (or when the PMF starts) to see that we
  8857. // have a definition at that point.
  8858. if (isInline && !D.isFunctionDefinition() && getLangOpts().CPlusPlus20 &&
  8859. NewFD->hasOwningModule() &&
  8860. NewFD->getOwningModule()->isModulePurview()) {
  8861. PendingInlineFuncDecls.insert(NewFD);
  8862. }
  8863. }
  8864. // Filter out previous declarations that don't match the scope.
  8865. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  8866. D.getCXXScopeSpec().isNotEmpty() ||
  8867. isMemberSpecialization ||
  8868. isFunctionTemplateSpecialization);
  8869. // Handle GNU asm-label extension (encoded as an attribute).
  8870. if (Expr *E = (Expr*) D.getAsmLabel()) {
  8871. // The parser guarantees this is a string.
  8872. StringLiteral *SE = cast<StringLiteral>(E);
  8873. NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
  8874. /*IsLiteralLabel=*/true,
  8875. SE->getStrTokenLoc(0)));
  8876. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  8877. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  8878. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  8879. if (I != ExtnameUndeclaredIdentifiers.end()) {
  8880. if (isDeclExternC(NewFD)) {
  8881. NewFD->addAttr(I->second);
  8882. ExtnameUndeclaredIdentifiers.erase(I);
  8883. } else
  8884. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  8885. << /*Variable*/0 << NewFD;
  8886. }
  8887. }
  8888. // Copy the parameter declarations from the declarator D to the function
  8889. // declaration NewFD, if they are available. First scavenge them into Params.
  8890. SmallVector<ParmVarDecl*, 16> Params;
  8891. unsigned FTIIdx;
  8892. if (D.isFunctionDeclarator(FTIIdx)) {
  8893. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  8894. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  8895. // function that takes no arguments, not a function that takes a
  8896. // single void argument.
  8897. // We let through "const void" here because Sema::GetTypeForDeclarator
  8898. // already checks for that case.
  8899. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  8900. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  8901. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  8902. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  8903. Param->setDeclContext(NewFD);
  8904. Params.push_back(Param);
  8905. if (Param->isInvalidDecl())
  8906. NewFD->setInvalidDecl();
  8907. }
  8908. }
  8909. if (!getLangOpts().CPlusPlus) {
  8910. // In C, find all the tag declarations from the prototype and move them
  8911. // into the function DeclContext. Remove them from the surrounding tag
  8912. // injection context of the function, which is typically but not always
  8913. // the TU.
  8914. DeclContext *PrototypeTagContext =
  8915. getTagInjectionContext(NewFD->getLexicalDeclContext());
  8916. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  8917. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  8918. // We don't want to reparent enumerators. Look at their parent enum
  8919. // instead.
  8920. if (!TD) {
  8921. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  8922. TD = cast<EnumDecl>(ECD->getDeclContext());
  8923. }
  8924. if (!TD)
  8925. continue;
  8926. DeclContext *TagDC = TD->getLexicalDeclContext();
  8927. if (!TagDC->containsDecl(TD))
  8928. continue;
  8929. TagDC->removeDecl(TD);
  8930. TD->setDeclContext(NewFD);
  8931. NewFD->addDecl(TD);
  8932. // Preserve the lexical DeclContext if it is not the surrounding tag
  8933. // injection context of the FD. In this example, the semantic context of
  8934. // E will be f and the lexical context will be S, while both the
  8935. // semantic and lexical contexts of S will be f:
  8936. // void f(struct S { enum E { a } f; } s);
  8937. if (TagDC != PrototypeTagContext)
  8938. TD->setLexicalDeclContext(TagDC);
  8939. }
  8940. }
  8941. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  8942. // When we're declaring a function with a typedef, typeof, etc as in the
  8943. // following example, we'll need to synthesize (unnamed)
  8944. // parameters for use in the declaration.
  8945. //
  8946. // @code
  8947. // typedef void fn(int);
  8948. // fn f;
  8949. // @endcode
  8950. // Synthesize a parameter for each argument type.
  8951. for (const auto &AI : FT->param_types()) {
  8952. ParmVarDecl *Param =
  8953. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  8954. Param->setScopeInfo(0, Params.size());
  8955. Params.push_back(Param);
  8956. }
  8957. } else {
  8958. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  8959. "Should not need args for typedef of non-prototype fn");
  8960. }
  8961. // Finally, we know we have the right number of parameters, install them.
  8962. NewFD->setParams(Params);
  8963. if (D.getDeclSpec().isNoreturnSpecified())
  8964. NewFD->addAttr(C11NoReturnAttr::Create(Context,
  8965. D.getDeclSpec().getNoreturnSpecLoc(),
  8966. AttributeCommonInfo::AS_Keyword));
  8967. // Functions returning a variably modified type violate C99 6.7.5.2p2
  8968. // because all functions have linkage.
  8969. if (!NewFD->isInvalidDecl() &&
  8970. NewFD->getReturnType()->isVariablyModifiedType()) {
  8971. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  8972. NewFD->setInvalidDecl();
  8973. }
  8974. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  8975. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  8976. !NewFD->hasAttr<SectionAttr>())
  8977. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
  8978. Context, PragmaClangTextSection.SectionName,
  8979. PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
  8980. // Apply an implicit SectionAttr if #pragma code_seg is active.
  8981. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  8982. !NewFD->hasAttr<SectionAttr>()) {
  8983. NewFD->addAttr(SectionAttr::CreateImplicit(
  8984. Context, CodeSegStack.CurrentValue->getString(),
  8985. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  8986. SectionAttr::Declspec_allocate));
  8987. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  8988. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  8989. ASTContext::PSF_Read,
  8990. NewFD))
  8991. NewFD->dropAttr<SectionAttr>();
  8992. }
  8993. // Apply an implicit StrictGuardStackCheckAttr if #pragma strict_gs_check is
  8994. // active.
  8995. if (StrictGuardStackCheckStack.CurrentValue && D.isFunctionDefinition() &&
  8996. !NewFD->hasAttr<StrictGuardStackCheckAttr>())
  8997. NewFD->addAttr(StrictGuardStackCheckAttr::CreateImplicit(
  8998. Context, PragmaClangTextSection.PragmaLocation,
  8999. AttributeCommonInfo::AS_Pragma));
  9000. // Apply an implicit CodeSegAttr from class declspec or
  9001. // apply an implicit SectionAttr from #pragma code_seg if active.
  9002. if (!NewFD->hasAttr<CodeSegAttr>()) {
  9003. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  9004. D.isFunctionDefinition())) {
  9005. NewFD->addAttr(SAttr);
  9006. }
  9007. }
  9008. // Handle attributes.
  9009. ProcessDeclAttributes(S, NewFD, D);
  9010. const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
  9011. if (NewTVA && !NewTVA->isDefaultVersion() &&
  9012. !Context.getTargetInfo().hasFeature("fmv")) {
  9013. // Don't add to scope fmv functions declarations if fmv disabled
  9014. AddToScope = false;
  9015. return NewFD;
  9016. }
  9017. if (getLangOpts().OpenCL) {
  9018. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  9019. // type declaration will generate a compilation error.
  9020. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  9021. if (AddressSpace != LangAS::Default) {
  9022. Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
  9023. NewFD->setInvalidDecl();
  9024. }
  9025. }
  9026. if (getLangOpts().HLSL) {
  9027. auto &TargetInfo = getASTContext().getTargetInfo();
  9028. // Skip operator overload which not identifier.
  9029. // Also make sure NewFD is in translation-unit scope.
  9030. if (!NewFD->isInvalidDecl() && Name.isIdentifier() &&
  9031. NewFD->getName() == TargetInfo.getTargetOpts().HLSLEntry &&
  9032. S->getDepth() == 0) {
  9033. CheckHLSLEntryPoint(NewFD);
  9034. if (!NewFD->isInvalidDecl()) {
  9035. auto Env = TargetInfo.getTriple().getEnvironment();
  9036. AttributeCommonInfo AL(NewFD->getBeginLoc());
  9037. HLSLShaderAttr::ShaderType ShaderType =
  9038. static_cast<HLSLShaderAttr::ShaderType>(
  9039. hlsl::getStageFromEnvironment(Env));
  9040. // To share code with HLSLShaderAttr, add HLSLShaderAttr to entry
  9041. // function.
  9042. if (HLSLShaderAttr *Attr = mergeHLSLShaderAttr(NewFD, AL, ShaderType))
  9043. NewFD->addAttr(Attr);
  9044. }
  9045. }
  9046. // HLSL does not support specifying an address space on a function return
  9047. // type.
  9048. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  9049. if (AddressSpace != LangAS::Default) {
  9050. Diag(NewFD->getLocation(), diag::err_return_value_with_address_space);
  9051. NewFD->setInvalidDecl();
  9052. }
  9053. }
  9054. if (!getLangOpts().CPlusPlus) {
  9055. // Perform semantic checking on the function declaration.
  9056. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  9057. CheckMain(NewFD, D.getDeclSpec());
  9058. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  9059. CheckMSVCRTEntryPoint(NewFD);
  9060. if (!NewFD->isInvalidDecl())
  9061. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  9062. isMemberSpecialization,
  9063. D.isFunctionDefinition()));
  9064. else if (!Previous.empty())
  9065. // Recover gracefully from an invalid redeclaration.
  9066. D.setRedeclaration(true);
  9067. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  9068. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  9069. "previous declaration set still overloaded");
  9070. // Diagnose no-prototype function declarations with calling conventions that
  9071. // don't support variadic calls. Only do this in C and do it after merging
  9072. // possibly prototyped redeclarations.
  9073. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  9074. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  9075. CallingConv CC = FT->getExtInfo().getCC();
  9076. if (!supportsVariadicCall(CC)) {
  9077. // Windows system headers sometimes accidentally use stdcall without
  9078. // (void) parameters, so we relax this to a warning.
  9079. int DiagID =
  9080. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  9081. Diag(NewFD->getLocation(), DiagID)
  9082. << FunctionType::getNameForCallConv(CC);
  9083. }
  9084. }
  9085. if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
  9086. NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
  9087. checkNonTrivialCUnion(NewFD->getReturnType(),
  9088. NewFD->getReturnTypeSourceRange().getBegin(),
  9089. NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
  9090. } else {
  9091. // C++11 [replacement.functions]p3:
  9092. // The program's definitions shall not be specified as inline.
  9093. //
  9094. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  9095. //
  9096. // Suppress the diagnostic if the function is __attribute__((used)), since
  9097. // that forces an external definition to be emitted.
  9098. if (D.getDeclSpec().isInlineSpecified() &&
  9099. NewFD->isReplaceableGlobalAllocationFunction() &&
  9100. !NewFD->hasAttr<UsedAttr>())
  9101. Diag(D.getDeclSpec().getInlineSpecLoc(),
  9102. diag::ext_operator_new_delete_declared_inline)
  9103. << NewFD->getDeclName();
  9104. // If the declarator is a template-id, translate the parser's template
  9105. // argument list into our AST format.
  9106. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  9107. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  9108. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  9109. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  9110. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  9111. TemplateId->NumArgs);
  9112. translateTemplateArguments(TemplateArgsPtr,
  9113. TemplateArgs);
  9114. HasExplicitTemplateArgs = true;
  9115. if (NewFD->isInvalidDecl()) {
  9116. HasExplicitTemplateArgs = false;
  9117. } else if (FunctionTemplate) {
  9118. // Function template with explicit template arguments.
  9119. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  9120. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  9121. HasExplicitTemplateArgs = false;
  9122. } else {
  9123. assert((isFunctionTemplateSpecialization ||
  9124. D.getDeclSpec().isFriendSpecified()) &&
  9125. "should have a 'template<>' for this decl");
  9126. // "friend void foo<>(int);" is an implicit specialization decl.
  9127. isFunctionTemplateSpecialization = true;
  9128. }
  9129. } else if (isFriend && isFunctionTemplateSpecialization) {
  9130. // This combination is only possible in a recovery case; the user
  9131. // wrote something like:
  9132. // template <> friend void foo(int);
  9133. // which we're recovering from as if the user had written:
  9134. // friend void foo<>(int);
  9135. // Go ahead and fake up a template id.
  9136. HasExplicitTemplateArgs = true;
  9137. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  9138. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  9139. }
  9140. // We do not add HD attributes to specializations here because
  9141. // they may have different constexpr-ness compared to their
  9142. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  9143. // may end up with different effective targets. Instead, a
  9144. // specialization inherits its target attributes from its template
  9145. // in the CheckFunctionTemplateSpecialization() call below.
  9146. if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
  9147. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  9148. // If it's a friend (and only if it's a friend), it's possible
  9149. // that either the specialized function type or the specialized
  9150. // template is dependent, and therefore matching will fail. In
  9151. // this case, don't check the specialization yet.
  9152. if (isFunctionTemplateSpecialization && isFriend &&
  9153. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  9154. TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
  9155. TemplateArgs.arguments()))) {
  9156. assert(HasExplicitTemplateArgs &&
  9157. "friend function specialization without template args");
  9158. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  9159. Previous))
  9160. NewFD->setInvalidDecl();
  9161. } else if (isFunctionTemplateSpecialization) {
  9162. if (CurContext->isDependentContext() && CurContext->isRecord()
  9163. && !isFriend) {
  9164. isDependentClassScopeExplicitSpecialization = true;
  9165. } else if (!NewFD->isInvalidDecl() &&
  9166. CheckFunctionTemplateSpecialization(
  9167. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  9168. Previous))
  9169. NewFD->setInvalidDecl();
  9170. // C++ [dcl.stc]p1:
  9171. // A storage-class-specifier shall not be specified in an explicit
  9172. // specialization (14.7.3)
  9173. FunctionTemplateSpecializationInfo *Info =
  9174. NewFD->getTemplateSpecializationInfo();
  9175. if (Info && SC != SC_None) {
  9176. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  9177. Diag(NewFD->getLocation(),
  9178. diag::err_explicit_specialization_inconsistent_storage_class)
  9179. << SC
  9180. << FixItHint::CreateRemoval(
  9181. D.getDeclSpec().getStorageClassSpecLoc());
  9182. else
  9183. Diag(NewFD->getLocation(),
  9184. diag::ext_explicit_specialization_storage_class)
  9185. << FixItHint::CreateRemoval(
  9186. D.getDeclSpec().getStorageClassSpecLoc());
  9187. }
  9188. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  9189. if (CheckMemberSpecialization(NewFD, Previous))
  9190. NewFD->setInvalidDecl();
  9191. }
  9192. // Perform semantic checking on the function declaration.
  9193. if (!isDependentClassScopeExplicitSpecialization) {
  9194. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  9195. CheckMain(NewFD, D.getDeclSpec());
  9196. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  9197. CheckMSVCRTEntryPoint(NewFD);
  9198. if (!NewFD->isInvalidDecl())
  9199. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  9200. isMemberSpecialization,
  9201. D.isFunctionDefinition()));
  9202. else if (!Previous.empty())
  9203. // Recover gracefully from an invalid redeclaration.
  9204. D.setRedeclaration(true);
  9205. }
  9206. assert((NewFD->isInvalidDecl() || NewFD->isMultiVersion() ||
  9207. !D.isRedeclaration() ||
  9208. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  9209. "previous declaration set still overloaded");
  9210. NamedDecl *PrincipalDecl = (FunctionTemplate
  9211. ? cast<NamedDecl>(FunctionTemplate)
  9212. : NewFD);
  9213. if (isFriend && NewFD->getPreviousDecl()) {
  9214. AccessSpecifier Access = AS_public;
  9215. if (!NewFD->isInvalidDecl())
  9216. Access = NewFD->getPreviousDecl()->getAccess();
  9217. NewFD->setAccess(Access);
  9218. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  9219. }
  9220. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  9221. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  9222. PrincipalDecl->setNonMemberOperator();
  9223. // If we have a function template, check the template parameter
  9224. // list. This will check and merge default template arguments.
  9225. if (FunctionTemplate) {
  9226. FunctionTemplateDecl *PrevTemplate =
  9227. FunctionTemplate->getPreviousDecl();
  9228. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  9229. PrevTemplate ? PrevTemplate->getTemplateParameters()
  9230. : nullptr,
  9231. D.getDeclSpec().isFriendSpecified()
  9232. ? (D.isFunctionDefinition()
  9233. ? TPC_FriendFunctionTemplateDefinition
  9234. : TPC_FriendFunctionTemplate)
  9235. : (D.getCXXScopeSpec().isSet() &&
  9236. DC && DC->isRecord() &&
  9237. DC->isDependentContext())
  9238. ? TPC_ClassTemplateMember
  9239. : TPC_FunctionTemplate);
  9240. }
  9241. if (NewFD->isInvalidDecl()) {
  9242. // Ignore all the rest of this.
  9243. } else if (!D.isRedeclaration()) {
  9244. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  9245. AddToScope };
  9246. // Fake up an access specifier if it's supposed to be a class member.
  9247. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  9248. NewFD->setAccess(AS_public);
  9249. // Qualified decls generally require a previous declaration.
  9250. if (D.getCXXScopeSpec().isSet()) {
  9251. // ...with the major exception of templated-scope or
  9252. // dependent-scope friend declarations.
  9253. // TODO: we currently also suppress this check in dependent
  9254. // contexts because (1) the parameter depth will be off when
  9255. // matching friend templates and (2) we might actually be
  9256. // selecting a friend based on a dependent factor. But there
  9257. // are situations where these conditions don't apply and we
  9258. // can actually do this check immediately.
  9259. //
  9260. // Unless the scope is dependent, it's always an error if qualified
  9261. // redeclaration lookup found nothing at all. Diagnose that now;
  9262. // nothing will diagnose that error later.
  9263. if (isFriend &&
  9264. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  9265. (!Previous.empty() && CurContext->isDependentContext()))) {
  9266. // ignore these
  9267. } else if (NewFD->isCPUDispatchMultiVersion() ||
  9268. NewFD->isCPUSpecificMultiVersion()) {
  9269. // ignore this, we allow the redeclaration behavior here to create new
  9270. // versions of the function.
  9271. } else {
  9272. // The user tried to provide an out-of-line definition for a
  9273. // function that is a member of a class or namespace, but there
  9274. // was no such member function declared (C++ [class.mfct]p2,
  9275. // C++ [namespace.memdef]p2). For example:
  9276. //
  9277. // class X {
  9278. // void f() const;
  9279. // };
  9280. //
  9281. // void X::f() { } // ill-formed
  9282. //
  9283. // Complain about this problem, and attempt to suggest close
  9284. // matches (e.g., those that differ only in cv-qualifiers and
  9285. // whether the parameter types are references).
  9286. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  9287. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  9288. AddToScope = ExtraArgs.AddToScope;
  9289. return Result;
  9290. }
  9291. }
  9292. // Unqualified local friend declarations are required to resolve
  9293. // to something.
  9294. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  9295. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  9296. *this, Previous, NewFD, ExtraArgs, true, S)) {
  9297. AddToScope = ExtraArgs.AddToScope;
  9298. return Result;
  9299. }
  9300. }
  9301. } else if (!D.isFunctionDefinition() &&
  9302. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  9303. !isFriend && !isFunctionTemplateSpecialization &&
  9304. !isMemberSpecialization) {
  9305. // An out-of-line member function declaration must also be a
  9306. // definition (C++ [class.mfct]p2).
  9307. // Note that this is not the case for explicit specializations of
  9308. // function templates or member functions of class templates, per
  9309. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  9310. // extension for compatibility with old SWIG code which likes to
  9311. // generate them.
  9312. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  9313. << D.getCXXScopeSpec().getRange();
  9314. }
  9315. }
  9316. // If this is the first declaration of a library builtin function, add
  9317. // attributes as appropriate.
  9318. if (!D.isRedeclaration()) {
  9319. if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
  9320. if (unsigned BuiltinID = II->getBuiltinID()) {
  9321. bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID);
  9322. if (!InStdNamespace &&
  9323. NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
  9324. if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
  9325. // Validate the type matches unless this builtin is specified as
  9326. // matching regardless of its declared type.
  9327. if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
  9328. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  9329. } else {
  9330. ASTContext::GetBuiltinTypeError Error;
  9331. LookupNecessaryTypesForBuiltin(S, BuiltinID);
  9332. QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
  9333. if (!Error && !BuiltinType.isNull() &&
  9334. Context.hasSameFunctionTypeIgnoringExceptionSpec(
  9335. NewFD->getType(), BuiltinType))
  9336. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  9337. }
  9338. }
  9339. } else if (InStdNamespace && NewFD->isInStdNamespace() &&
  9340. isStdBuiltin(Context, NewFD, BuiltinID)) {
  9341. NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
  9342. }
  9343. }
  9344. }
  9345. }
  9346. ProcessPragmaWeak(S, NewFD);
  9347. checkAttributesAfterMerging(*this, *NewFD);
  9348. AddKnownFunctionAttributes(NewFD);
  9349. if (NewFD->hasAttr<OverloadableAttr>() &&
  9350. !NewFD->getType()->getAs<FunctionProtoType>()) {
  9351. Diag(NewFD->getLocation(),
  9352. diag::err_attribute_overloadable_no_prototype)
  9353. << NewFD;
  9354. NewFD->dropAttr<OverloadableAttr>();
  9355. }
  9356. // If there's a #pragma GCC visibility in scope, and this isn't a class
  9357. // member, set the visibility of this function.
  9358. if (!DC->isRecord() && NewFD->isExternallyVisible())
  9359. AddPushedVisibilityAttribute(NewFD);
  9360. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  9361. // marking the function.
  9362. AddCFAuditedAttribute(NewFD);
  9363. // If this is a function definition, check if we have to apply any
  9364. // attributes (i.e. optnone and no_builtin) due to a pragma.
  9365. if (D.isFunctionDefinition()) {
  9366. AddRangeBasedOptnone(NewFD);
  9367. AddImplicitMSFunctionNoBuiltinAttr(NewFD);
  9368. AddSectionMSAllocText(NewFD);
  9369. ModifyFnAttributesMSPragmaOptimize(NewFD);
  9370. }
  9371. // If this is the first declaration of an extern C variable, update
  9372. // the map of such variables.
  9373. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  9374. isIncompleteDeclExternC(*this, NewFD))
  9375. RegisterLocallyScopedExternCDecl(NewFD, S);
  9376. // Set this FunctionDecl's range up to the right paren.
  9377. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  9378. if (D.isRedeclaration() && !Previous.empty()) {
  9379. NamedDecl *Prev = Previous.getRepresentativeDecl();
  9380. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  9381. isMemberSpecialization ||
  9382. isFunctionTemplateSpecialization,
  9383. D.isFunctionDefinition());
  9384. }
  9385. if (getLangOpts().CUDA) {
  9386. IdentifierInfo *II = NewFD->getIdentifier();
  9387. if (II && II->isStr(getCudaConfigureFuncName()) &&
  9388. !NewFD->isInvalidDecl() &&
  9389. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  9390. if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
  9391. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  9392. << getCudaConfigureFuncName();
  9393. Context.setcudaConfigureCallDecl(NewFD);
  9394. }
  9395. // Variadic functions, other than a *declaration* of printf, are not allowed
  9396. // in device-side CUDA code, unless someone passed
  9397. // -fcuda-allow-variadic-functions.
  9398. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  9399. (NewFD->hasAttr<CUDADeviceAttr>() ||
  9400. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  9401. !(II && II->isStr("printf") && NewFD->isExternC() &&
  9402. !D.isFunctionDefinition())) {
  9403. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  9404. }
  9405. }
  9406. MarkUnusedFileScopedDecl(NewFD);
  9407. if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
  9408. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  9409. if (SC == SC_Static) {
  9410. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  9411. D.setInvalidType();
  9412. }
  9413. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  9414. if (!NewFD->getReturnType()->isVoidType()) {
  9415. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  9416. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  9417. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  9418. : FixItHint());
  9419. D.setInvalidType();
  9420. }
  9421. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  9422. for (auto *Param : NewFD->parameters())
  9423. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  9424. if (getLangOpts().OpenCLCPlusPlus) {
  9425. if (DC->isRecord()) {
  9426. Diag(D.getIdentifierLoc(), diag::err_method_kernel);
  9427. D.setInvalidType();
  9428. }
  9429. if (FunctionTemplate) {
  9430. Diag(D.getIdentifierLoc(), diag::err_template_kernel);
  9431. D.setInvalidType();
  9432. }
  9433. }
  9434. }
  9435. if (getLangOpts().CPlusPlus) {
  9436. // Precalculate whether this is a friend function template with a constraint
  9437. // that depends on an enclosing template, per [temp.friend]p9.
  9438. if (isFriend && FunctionTemplate &&
  9439. FriendConstraintsDependOnEnclosingTemplate(NewFD))
  9440. NewFD->setFriendConstraintRefersToEnclosingTemplate(true);
  9441. if (FunctionTemplate) {
  9442. if (NewFD->isInvalidDecl())
  9443. FunctionTemplate->setInvalidDecl();
  9444. return FunctionTemplate;
  9445. }
  9446. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  9447. CompleteMemberSpecialization(NewFD, Previous);
  9448. }
  9449. for (const ParmVarDecl *Param : NewFD->parameters()) {
  9450. QualType PT = Param->getType();
  9451. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  9452. // types.
  9453. if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
  9454. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  9455. QualType ElemTy = PipeTy->getElementType();
  9456. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  9457. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  9458. D.setInvalidType();
  9459. }
  9460. }
  9461. }
  9462. }
  9463. // Here we have an function template explicit specialization at class scope.
  9464. // The actual specialization will be postponed to template instatiation
  9465. // time via the ClassScopeFunctionSpecializationDecl node.
  9466. if (isDependentClassScopeExplicitSpecialization) {
  9467. ClassScopeFunctionSpecializationDecl *NewSpec =
  9468. ClassScopeFunctionSpecializationDecl::Create(
  9469. Context, CurContext, NewFD->getLocation(),
  9470. cast<CXXMethodDecl>(NewFD),
  9471. HasExplicitTemplateArgs, TemplateArgs);
  9472. CurContext->addDecl(NewSpec);
  9473. AddToScope = false;
  9474. }
  9475. // Diagnose availability attributes. Availability cannot be used on functions
  9476. // that are run during load/unload.
  9477. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  9478. if (NewFD->hasAttr<ConstructorAttr>()) {
  9479. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  9480. << 1;
  9481. NewFD->dropAttr<AvailabilityAttr>();
  9482. }
  9483. if (NewFD->hasAttr<DestructorAttr>()) {
  9484. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  9485. << 2;
  9486. NewFD->dropAttr<AvailabilityAttr>();
  9487. }
  9488. }
  9489. // Diagnose no_builtin attribute on function declaration that are not a
  9490. // definition.
  9491. // FIXME: We should really be doing this in
  9492. // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
  9493. // the FunctionDecl and at this point of the code
  9494. // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
  9495. // because Sema::ActOnStartOfFunctionDef has not been called yet.
  9496. if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
  9497. switch (D.getFunctionDefinitionKind()) {
  9498. case FunctionDefinitionKind::Defaulted:
  9499. case FunctionDefinitionKind::Deleted:
  9500. Diag(NBA->getLocation(),
  9501. diag::err_attribute_no_builtin_on_defaulted_deleted_function)
  9502. << NBA->getSpelling();
  9503. break;
  9504. case FunctionDefinitionKind::Declaration:
  9505. Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
  9506. << NBA->getSpelling();
  9507. break;
  9508. case FunctionDefinitionKind::Definition:
  9509. break;
  9510. }
  9511. return NewFD;
  9512. }
  9513. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  9514. /// when __declspec(code_seg) "is applied to a class, all member functions of
  9515. /// the class and nested classes -- this includes compiler-generated special
  9516. /// member functions -- are put in the specified segment."
  9517. /// The actual behavior is a little more complicated. The Microsoft compiler
  9518. /// won't check outer classes if there is an active value from #pragma code_seg.
  9519. /// The CodeSeg is always applied from the direct parent but only from outer
  9520. /// classes when the #pragma code_seg stack is empty. See:
  9521. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  9522. /// available since MS has removed the page.
  9523. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  9524. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  9525. if (!Method)
  9526. return nullptr;
  9527. const CXXRecordDecl *Parent = Method->getParent();
  9528. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  9529. Attr *NewAttr = SAttr->clone(S.getASTContext());
  9530. NewAttr->setImplicit(true);
  9531. return NewAttr;
  9532. }
  9533. // The Microsoft compiler won't check outer classes for the CodeSeg
  9534. // when the #pragma code_seg stack is active.
  9535. if (S.CodeSegStack.CurrentValue)
  9536. return nullptr;
  9537. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  9538. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  9539. Attr *NewAttr = SAttr->clone(S.getASTContext());
  9540. NewAttr->setImplicit(true);
  9541. return NewAttr;
  9542. }
  9543. }
  9544. return nullptr;
  9545. }
  9546. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  9547. /// containing class. Otherwise it will return implicit SectionAttr if the
  9548. /// function is a definition and there is an active value on CodeSegStack
  9549. /// (from the current #pragma code-seg value).
  9550. ///
  9551. /// \param FD Function being declared.
  9552. /// \param IsDefinition Whether it is a definition or just a declaration.
  9553. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  9554. /// nullptr if no attribute should be added.
  9555. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  9556. bool IsDefinition) {
  9557. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  9558. return A;
  9559. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  9560. CodeSegStack.CurrentValue)
  9561. return SectionAttr::CreateImplicit(
  9562. getASTContext(), CodeSegStack.CurrentValue->getString(),
  9563. CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
  9564. SectionAttr::Declspec_allocate);
  9565. return nullptr;
  9566. }
  9567. /// Determines if we can perform a correct type check for \p D as a
  9568. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  9569. /// best-effort check.
  9570. ///
  9571. /// \param NewD The new declaration.
  9572. /// \param OldD The old declaration.
  9573. /// \param NewT The portion of the type of the new declaration to check.
  9574. /// \param OldT The portion of the type of the old declaration to check.
  9575. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  9576. QualType NewT, QualType OldT) {
  9577. if (!NewD->getLexicalDeclContext()->isDependentContext())
  9578. return true;
  9579. // For dependently-typed local extern declarations and friends, we can't
  9580. // perform a correct type check in general until instantiation:
  9581. //
  9582. // int f();
  9583. // template<typename T> void g() { T f(); }
  9584. //
  9585. // (valid if g() is only instantiated with T = int).
  9586. if (NewT->isDependentType() &&
  9587. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  9588. return false;
  9589. // Similarly, if the previous declaration was a dependent local extern
  9590. // declaration, we don't really know its type yet.
  9591. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  9592. return false;
  9593. return true;
  9594. }
  9595. /// Checks if the new declaration declared in dependent context must be
  9596. /// put in the same redeclaration chain as the specified declaration.
  9597. ///
  9598. /// \param D Declaration that is checked.
  9599. /// \param PrevDecl Previous declaration found with proper lookup method for the
  9600. /// same declaration name.
  9601. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  9602. /// belongs to.
  9603. ///
  9604. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  9605. if (!D->getLexicalDeclContext()->isDependentContext())
  9606. return true;
  9607. // Don't chain dependent friend function definitions until instantiation, to
  9608. // permit cases like
  9609. //
  9610. // void func();
  9611. // template<typename T> class C1 { friend void func() {} };
  9612. // template<typename T> class C2 { friend void func() {} };
  9613. //
  9614. // ... which is valid if only one of C1 and C2 is ever instantiated.
  9615. //
  9616. // FIXME: This need only apply to function definitions. For now, we proxy
  9617. // this by checking for a file-scope function. We do not want this to apply
  9618. // to friend declarations nominating member functions, because that gets in
  9619. // the way of access checks.
  9620. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  9621. return false;
  9622. auto *VD = dyn_cast<ValueDecl>(D);
  9623. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  9624. return !VD || !PrevVD ||
  9625. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  9626. PrevVD->getType());
  9627. }
  9628. /// Check the target or target_version attribute of the function for
  9629. /// MultiVersion validity.
  9630. ///
  9631. /// Returns true if there was an error, false otherwise.
  9632. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  9633. const auto *TA = FD->getAttr<TargetAttr>();
  9634. const auto *TVA = FD->getAttr<TargetVersionAttr>();
  9635. assert(
  9636. (TA || TVA) &&
  9637. "MultiVersion candidate requires a target or target_version attribute");
  9638. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  9639. enum ErrType { Feature = 0, Architecture = 1 };
  9640. if (TA) {
  9641. ParsedTargetAttr ParseInfo =
  9642. S.getASTContext().getTargetInfo().parseTargetAttr(TA->getFeaturesStr());
  9643. if (!ParseInfo.CPU.empty() && !TargetInfo.validateCpuIs(ParseInfo.CPU)) {
  9644. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9645. << Architecture << ParseInfo.CPU;
  9646. return true;
  9647. }
  9648. for (const auto &Feat : ParseInfo.Features) {
  9649. auto BareFeat = StringRef{Feat}.substr(1);
  9650. if (Feat[0] == '-') {
  9651. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9652. << Feature << ("no-" + BareFeat).str();
  9653. return true;
  9654. }
  9655. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  9656. !TargetInfo.isValidFeatureName(BareFeat)) {
  9657. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9658. << Feature << BareFeat;
  9659. return true;
  9660. }
  9661. }
  9662. }
  9663. if (TVA) {
  9664. llvm::SmallVector<StringRef, 8> Feats;
  9665. TVA->getFeatures(Feats);
  9666. for (const auto &Feat : Feats) {
  9667. if (!TargetInfo.validateCpuSupports(Feat)) {
  9668. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  9669. << Feature << Feat;
  9670. return true;
  9671. }
  9672. }
  9673. }
  9674. return false;
  9675. }
  9676. // Provide a white-list of attributes that are allowed to be combined with
  9677. // multiversion functions.
  9678. static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
  9679. MultiVersionKind MVKind) {
  9680. // Note: this list/diagnosis must match the list in
  9681. // checkMultiversionAttributesAllSame.
  9682. switch (Kind) {
  9683. default:
  9684. return false;
  9685. case attr::Used:
  9686. return MVKind == MultiVersionKind::Target;
  9687. case attr::NonNull:
  9688. case attr::NoThrow:
  9689. return true;
  9690. }
  9691. }
  9692. static bool checkNonMultiVersionCompatAttributes(Sema &S,
  9693. const FunctionDecl *FD,
  9694. const FunctionDecl *CausedFD,
  9695. MultiVersionKind MVKind) {
  9696. const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
  9697. S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
  9698. << static_cast<unsigned>(MVKind) << A;
  9699. if (CausedFD)
  9700. S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
  9701. return true;
  9702. };
  9703. for (const Attr *A : FD->attrs()) {
  9704. switch (A->getKind()) {
  9705. case attr::CPUDispatch:
  9706. case attr::CPUSpecific:
  9707. if (MVKind != MultiVersionKind::CPUDispatch &&
  9708. MVKind != MultiVersionKind::CPUSpecific)
  9709. return Diagnose(S, A);
  9710. break;
  9711. case attr::Target:
  9712. if (MVKind != MultiVersionKind::Target)
  9713. return Diagnose(S, A);
  9714. break;
  9715. case attr::TargetVersion:
  9716. if (MVKind != MultiVersionKind::TargetVersion)
  9717. return Diagnose(S, A);
  9718. break;
  9719. case attr::TargetClones:
  9720. if (MVKind != MultiVersionKind::TargetClones)
  9721. return Diagnose(S, A);
  9722. break;
  9723. default:
  9724. if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
  9725. return Diagnose(S, A);
  9726. break;
  9727. }
  9728. }
  9729. return false;
  9730. }
  9731. bool Sema::areMultiversionVariantFunctionsCompatible(
  9732. const FunctionDecl *OldFD, const FunctionDecl *NewFD,
  9733. const PartialDiagnostic &NoProtoDiagID,
  9734. const PartialDiagnosticAt &NoteCausedDiagIDAt,
  9735. const PartialDiagnosticAt &NoSupportDiagIDAt,
  9736. const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
  9737. bool ConstexprSupported, bool CLinkageMayDiffer) {
  9738. enum DoesntSupport {
  9739. FuncTemplates = 0,
  9740. VirtFuncs = 1,
  9741. DeducedReturn = 2,
  9742. Constructors = 3,
  9743. Destructors = 4,
  9744. DeletedFuncs = 5,
  9745. DefaultedFuncs = 6,
  9746. ConstexprFuncs = 7,
  9747. ConstevalFuncs = 8,
  9748. Lambda = 9,
  9749. };
  9750. enum Different {
  9751. CallingConv = 0,
  9752. ReturnType = 1,
  9753. ConstexprSpec = 2,
  9754. InlineSpec = 3,
  9755. Linkage = 4,
  9756. LanguageLinkage = 5,
  9757. };
  9758. if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
  9759. !OldFD->getType()->getAs<FunctionProtoType>()) {
  9760. Diag(OldFD->getLocation(), NoProtoDiagID);
  9761. Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
  9762. return true;
  9763. }
  9764. if (NoProtoDiagID.getDiagID() != 0 &&
  9765. !NewFD->getType()->getAs<FunctionProtoType>())
  9766. return Diag(NewFD->getLocation(), NoProtoDiagID);
  9767. if (!TemplatesSupported &&
  9768. NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  9769. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9770. << FuncTemplates;
  9771. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  9772. if (NewCXXFD->isVirtual())
  9773. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9774. << VirtFuncs;
  9775. if (isa<CXXConstructorDecl>(NewCXXFD))
  9776. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9777. << Constructors;
  9778. if (isa<CXXDestructorDecl>(NewCXXFD))
  9779. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9780. << Destructors;
  9781. }
  9782. if (NewFD->isDeleted())
  9783. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9784. << DeletedFuncs;
  9785. if (NewFD->isDefaulted())
  9786. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9787. << DefaultedFuncs;
  9788. if (!ConstexprSupported && NewFD->isConstexpr())
  9789. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9790. << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
  9791. QualType NewQType = Context.getCanonicalType(NewFD->getType());
  9792. const auto *NewType = cast<FunctionType>(NewQType);
  9793. QualType NewReturnType = NewType->getReturnType();
  9794. if (NewReturnType->isUndeducedType())
  9795. return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
  9796. << DeducedReturn;
  9797. // Ensure the return type is identical.
  9798. if (OldFD) {
  9799. QualType OldQType = Context.getCanonicalType(OldFD->getType());
  9800. const auto *OldType = cast<FunctionType>(OldQType);
  9801. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  9802. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  9803. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  9804. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
  9805. QualType OldReturnType = OldType->getReturnType();
  9806. if (OldReturnType != NewReturnType)
  9807. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
  9808. if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
  9809. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
  9810. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  9811. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
  9812. if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
  9813. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
  9814. if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
  9815. return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
  9816. if (CheckEquivalentExceptionSpec(
  9817. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  9818. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  9819. return true;
  9820. }
  9821. return false;
  9822. }
  9823. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  9824. const FunctionDecl *NewFD,
  9825. bool CausesMV,
  9826. MultiVersionKind MVKind) {
  9827. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  9828. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  9829. if (OldFD)
  9830. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9831. return true;
  9832. }
  9833. bool IsCPUSpecificCPUDispatchMVKind =
  9834. MVKind == MultiVersionKind::CPUDispatch ||
  9835. MVKind == MultiVersionKind::CPUSpecific;
  9836. if (CausesMV && OldFD &&
  9837. checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
  9838. return true;
  9839. if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
  9840. return true;
  9841. // Only allow transition to MultiVersion if it hasn't been used.
  9842. if (OldFD && CausesMV && OldFD->isUsed(false))
  9843. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  9844. return S.areMultiversionVariantFunctionsCompatible(
  9845. OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
  9846. PartialDiagnosticAt(NewFD->getLocation(),
  9847. S.PDiag(diag::note_multiversioning_caused_here)),
  9848. PartialDiagnosticAt(NewFD->getLocation(),
  9849. S.PDiag(diag::err_multiversion_doesnt_support)
  9850. << static_cast<unsigned>(MVKind)),
  9851. PartialDiagnosticAt(NewFD->getLocation(),
  9852. S.PDiag(diag::err_multiversion_diff)),
  9853. /*TemplatesSupported=*/false,
  9854. /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
  9855. /*CLinkageMayDiffer=*/false);
  9856. }
  9857. /// Check the validity of a multiversion function declaration that is the
  9858. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  9859. ///
  9860. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  9861. ///
  9862. /// Returns true if there was an error, false otherwise.
  9863. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD) {
  9864. MultiVersionKind MVKind = FD->getMultiVersionKind();
  9865. assert(MVKind != MultiVersionKind::None &&
  9866. "Function lacks multiversion attribute");
  9867. const auto *TA = FD->getAttr<TargetAttr>();
  9868. const auto *TVA = FD->getAttr<TargetVersionAttr>();
  9869. // Target and target_version only causes MV if it is default, otherwise this
  9870. // is a normal function.
  9871. if ((TA && !TA->isDefaultVersion()) || (TVA && !TVA->isDefaultVersion()))
  9872. return false;
  9873. if ((TA || TVA) && CheckMultiVersionValue(S, FD)) {
  9874. FD->setInvalidDecl();
  9875. return true;
  9876. }
  9877. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
  9878. FD->setInvalidDecl();
  9879. return true;
  9880. }
  9881. FD->setIsMultiVersion();
  9882. return false;
  9883. }
  9884. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  9885. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  9886. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  9887. return true;
  9888. }
  9889. return false;
  9890. }
  9891. static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD,
  9892. FunctionDecl *NewFD,
  9893. bool &Redeclaration,
  9894. NamedDecl *&OldDecl,
  9895. LookupResult &Previous) {
  9896. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  9897. const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
  9898. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  9899. const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
  9900. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  9901. // to change, this is a simple redeclaration.
  9902. if ((NewTA && !NewTA->isDefaultVersion() &&
  9903. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) ||
  9904. (NewTVA && !NewTVA->isDefaultVersion() &&
  9905. (!OldTVA || OldTVA->getName() == NewTVA->getName())))
  9906. return false;
  9907. // Otherwise, this decl causes MultiVersioning.
  9908. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  9909. NewTVA ? MultiVersionKind::TargetVersion
  9910. : MultiVersionKind::Target)) {
  9911. NewFD->setInvalidDecl();
  9912. return true;
  9913. }
  9914. if (CheckMultiVersionValue(S, NewFD)) {
  9915. NewFD->setInvalidDecl();
  9916. return true;
  9917. }
  9918. // If this is 'default', permit the forward declaration.
  9919. if (!OldFD->isMultiVersion() &&
  9920. ((NewTA && NewTA->isDefaultVersion() && !OldTA) ||
  9921. (NewTVA && NewTVA->isDefaultVersion() && !OldTVA))) {
  9922. Redeclaration = true;
  9923. OldDecl = OldFD;
  9924. OldFD->setIsMultiVersion();
  9925. NewFD->setIsMultiVersion();
  9926. return false;
  9927. }
  9928. if (CheckMultiVersionValue(S, OldFD)) {
  9929. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  9930. NewFD->setInvalidDecl();
  9931. return true;
  9932. }
  9933. if (NewTA) {
  9934. ParsedTargetAttr OldParsed =
  9935. S.getASTContext().getTargetInfo().parseTargetAttr(
  9936. OldTA->getFeaturesStr());
  9937. llvm::sort(OldParsed.Features);
  9938. ParsedTargetAttr NewParsed =
  9939. S.getASTContext().getTargetInfo().parseTargetAttr(
  9940. NewTA->getFeaturesStr());
  9941. // Sort order doesn't matter, it just needs to be consistent.
  9942. llvm::sort(NewParsed.Features);
  9943. if (OldParsed == NewParsed) {
  9944. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  9945. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9946. NewFD->setInvalidDecl();
  9947. return true;
  9948. }
  9949. }
  9950. if (NewTVA) {
  9951. llvm::SmallVector<StringRef, 8> Feats;
  9952. OldTVA->getFeatures(Feats);
  9953. llvm::sort(Feats);
  9954. llvm::SmallVector<StringRef, 8> NewFeats;
  9955. NewTVA->getFeatures(NewFeats);
  9956. llvm::sort(NewFeats);
  9957. if (Feats == NewFeats) {
  9958. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  9959. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  9960. NewFD->setInvalidDecl();
  9961. return true;
  9962. }
  9963. }
  9964. for (const auto *FD : OldFD->redecls()) {
  9965. const auto *CurTA = FD->getAttr<TargetAttr>();
  9966. const auto *CurTVA = FD->getAttr<TargetVersionAttr>();
  9967. // We allow forward declarations before ANY multiversioning attributes, but
  9968. // nothing after the fact.
  9969. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  9970. ((NewTA && (!CurTA || CurTA->isInherited())) ||
  9971. (NewTVA && (!CurTVA || CurTVA->isInherited())))) {
  9972. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  9973. << (NewTA ? 0 : 2);
  9974. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  9975. NewFD->setInvalidDecl();
  9976. return true;
  9977. }
  9978. }
  9979. OldFD->setIsMultiVersion();
  9980. NewFD->setIsMultiVersion();
  9981. Redeclaration = false;
  9982. OldDecl = nullptr;
  9983. Previous.clear();
  9984. return false;
  9985. }
  9986. static bool MultiVersionTypesCompatible(MultiVersionKind Old,
  9987. MultiVersionKind New) {
  9988. if (Old == New || Old == MultiVersionKind::None ||
  9989. New == MultiVersionKind::None)
  9990. return true;
  9991. return (Old == MultiVersionKind::CPUDispatch &&
  9992. New == MultiVersionKind::CPUSpecific) ||
  9993. (Old == MultiVersionKind::CPUSpecific &&
  9994. New == MultiVersionKind::CPUDispatch);
  9995. }
  9996. /// Check the validity of a new function declaration being added to an existing
  9997. /// multiversioned declaration collection.
  9998. static bool CheckMultiVersionAdditionalDecl(
  9999. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  10000. MultiVersionKind NewMVKind, const CPUDispatchAttr *NewCPUDisp,
  10001. const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones,
  10002. bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
  10003. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  10004. const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
  10005. MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
  10006. // Disallow mixing of multiversioning types.
  10007. if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
  10008. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  10009. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  10010. NewFD->setInvalidDecl();
  10011. return true;
  10012. }
  10013. ParsedTargetAttr NewParsed;
  10014. if (NewTA) {
  10015. NewParsed = S.getASTContext().getTargetInfo().parseTargetAttr(
  10016. NewTA->getFeaturesStr());
  10017. llvm::sort(NewParsed.Features);
  10018. }
  10019. llvm::SmallVector<StringRef, 8> NewFeats;
  10020. if (NewTVA) {
  10021. NewTVA->getFeatures(NewFeats);
  10022. llvm::sort(NewFeats);
  10023. }
  10024. bool UseMemberUsingDeclRules =
  10025. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  10026. bool MayNeedOverloadableChecks =
  10027. AllowOverloadingOfFunction(Previous, S.Context, NewFD);
  10028. // Next, check ALL non-invalid non-overloads to see if this is a redeclaration
  10029. // of a previous member of the MultiVersion set.
  10030. for (NamedDecl *ND : Previous) {
  10031. FunctionDecl *CurFD = ND->getAsFunction();
  10032. if (!CurFD || CurFD->isInvalidDecl())
  10033. continue;
  10034. if (MayNeedOverloadableChecks &&
  10035. S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  10036. continue;
  10037. if (NewMVKind == MultiVersionKind::None &&
  10038. OldMVKind == MultiVersionKind::TargetVersion) {
  10039. NewFD->addAttr(TargetVersionAttr::CreateImplicit(
  10040. S.Context, "default", NewFD->getSourceRange(),
  10041. AttributeCommonInfo::AS_GNU));
  10042. NewFD->setIsMultiVersion();
  10043. NewMVKind = MultiVersionKind::TargetVersion;
  10044. if (!NewTVA) {
  10045. NewTVA = NewFD->getAttr<TargetVersionAttr>();
  10046. NewTVA->getFeatures(NewFeats);
  10047. llvm::sort(NewFeats);
  10048. }
  10049. }
  10050. switch (NewMVKind) {
  10051. case MultiVersionKind::None:
  10052. assert(OldMVKind == MultiVersionKind::TargetClones &&
  10053. "Only target_clones can be omitted in subsequent declarations");
  10054. break;
  10055. case MultiVersionKind::Target: {
  10056. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  10057. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  10058. NewFD->setIsMultiVersion();
  10059. Redeclaration = true;
  10060. OldDecl = ND;
  10061. return false;
  10062. }
  10063. ParsedTargetAttr CurParsed =
  10064. S.getASTContext().getTargetInfo().parseTargetAttr(
  10065. CurTA->getFeaturesStr());
  10066. llvm::sort(CurParsed.Features);
  10067. if (CurParsed == NewParsed) {
  10068. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  10069. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  10070. NewFD->setInvalidDecl();
  10071. return true;
  10072. }
  10073. break;
  10074. }
  10075. case MultiVersionKind::TargetVersion: {
  10076. const auto *CurTVA = CurFD->getAttr<TargetVersionAttr>();
  10077. if (CurTVA->getName() == NewTVA->getName()) {
  10078. NewFD->setIsMultiVersion();
  10079. Redeclaration = true;
  10080. OldDecl = ND;
  10081. return false;
  10082. }
  10083. llvm::SmallVector<StringRef, 8> CurFeats;
  10084. if (CurTVA) {
  10085. CurTVA->getFeatures(CurFeats);
  10086. llvm::sort(CurFeats);
  10087. }
  10088. if (CurFeats == NewFeats) {
  10089. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  10090. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  10091. NewFD->setInvalidDecl();
  10092. return true;
  10093. }
  10094. break;
  10095. }
  10096. case MultiVersionKind::TargetClones: {
  10097. const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
  10098. Redeclaration = true;
  10099. OldDecl = CurFD;
  10100. NewFD->setIsMultiVersion();
  10101. if (CurClones && NewClones &&
  10102. (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
  10103. !std::equal(CurClones->featuresStrs_begin(),
  10104. CurClones->featuresStrs_end(),
  10105. NewClones->featuresStrs_begin()))) {
  10106. S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
  10107. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  10108. NewFD->setInvalidDecl();
  10109. return true;
  10110. }
  10111. return false;
  10112. }
  10113. case MultiVersionKind::CPUSpecific:
  10114. case MultiVersionKind::CPUDispatch: {
  10115. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  10116. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  10117. // Handle CPUDispatch/CPUSpecific versions.
  10118. // Only 1 CPUDispatch function is allowed, this will make it go through
  10119. // the redeclaration errors.
  10120. if (NewMVKind == MultiVersionKind::CPUDispatch &&
  10121. CurFD->hasAttr<CPUDispatchAttr>()) {
  10122. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  10123. std::equal(
  10124. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  10125. NewCPUDisp->cpus_begin(),
  10126. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  10127. return Cur->getName() == New->getName();
  10128. })) {
  10129. NewFD->setIsMultiVersion();
  10130. Redeclaration = true;
  10131. OldDecl = ND;
  10132. return false;
  10133. }
  10134. // If the declarations don't match, this is an error condition.
  10135. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  10136. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  10137. NewFD->setInvalidDecl();
  10138. return true;
  10139. }
  10140. if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  10141. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  10142. std::equal(
  10143. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  10144. NewCPUSpec->cpus_begin(),
  10145. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  10146. return Cur->getName() == New->getName();
  10147. })) {
  10148. NewFD->setIsMultiVersion();
  10149. Redeclaration = true;
  10150. OldDecl = ND;
  10151. return false;
  10152. }
  10153. // Only 1 version of CPUSpecific is allowed for each CPU.
  10154. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  10155. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  10156. if (CurII == NewII) {
  10157. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  10158. << NewII;
  10159. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  10160. NewFD->setInvalidDecl();
  10161. return true;
  10162. }
  10163. }
  10164. }
  10165. }
  10166. break;
  10167. }
  10168. }
  10169. }
  10170. // Else, this is simply a non-redecl case. Checking the 'value' is only
  10171. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  10172. // handled in the attribute adding step.
  10173. if ((NewMVKind == MultiVersionKind::TargetVersion ||
  10174. NewMVKind == MultiVersionKind::Target) &&
  10175. CheckMultiVersionValue(S, NewFD)) {
  10176. NewFD->setInvalidDecl();
  10177. return true;
  10178. }
  10179. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  10180. !OldFD->isMultiVersion(), NewMVKind)) {
  10181. NewFD->setInvalidDecl();
  10182. return true;
  10183. }
  10184. // Permit forward declarations in the case where these two are compatible.
  10185. if (!OldFD->isMultiVersion()) {
  10186. OldFD->setIsMultiVersion();
  10187. NewFD->setIsMultiVersion();
  10188. Redeclaration = true;
  10189. OldDecl = OldFD;
  10190. return false;
  10191. }
  10192. NewFD->setIsMultiVersion();
  10193. Redeclaration = false;
  10194. OldDecl = nullptr;
  10195. Previous.clear();
  10196. return false;
  10197. }
  10198. /// Check the validity of a mulitversion function declaration.
  10199. /// Also sets the multiversion'ness' of the function itself.
  10200. ///
  10201. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  10202. ///
  10203. /// Returns true if there was an error, false otherwise.
  10204. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  10205. bool &Redeclaration, NamedDecl *&OldDecl,
  10206. LookupResult &Previous) {
  10207. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  10208. const auto *NewTVA = NewFD->getAttr<TargetVersionAttr>();
  10209. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  10210. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  10211. const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
  10212. MultiVersionKind MVKind = NewFD->getMultiVersionKind();
  10213. // Main isn't allowed to become a multiversion function, however it IS
  10214. // permitted to have 'main' be marked with the 'target' optimization hint,
  10215. // for 'target_version' only default is allowed.
  10216. if (NewFD->isMain()) {
  10217. if (MVKind != MultiVersionKind::None &&
  10218. !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion()) &&
  10219. !(MVKind == MultiVersionKind::TargetVersion &&
  10220. NewTVA->isDefaultVersion())) {
  10221. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  10222. NewFD->setInvalidDecl();
  10223. return true;
  10224. }
  10225. return false;
  10226. }
  10227. if (!OldDecl || !OldDecl->getAsFunction() ||
  10228. OldDecl->getDeclContext()->getRedeclContext() !=
  10229. NewFD->getDeclContext()->getRedeclContext()) {
  10230. // If there's no previous declaration, AND this isn't attempting to cause
  10231. // multiversioning, this isn't an error condition.
  10232. if (MVKind == MultiVersionKind::None)
  10233. return false;
  10234. return CheckMultiVersionFirstFunction(S, NewFD);
  10235. }
  10236. FunctionDecl *OldFD = OldDecl->getAsFunction();
  10237. if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) {
  10238. // No target_version attributes mean default
  10239. if (!NewTVA) {
  10240. const auto *OldTVA = OldFD->getAttr<TargetVersionAttr>();
  10241. if (OldTVA) {
  10242. NewFD->addAttr(TargetVersionAttr::CreateImplicit(
  10243. S.Context, "default", NewFD->getSourceRange(),
  10244. AttributeCommonInfo::AS_GNU));
  10245. NewFD->setIsMultiVersion();
  10246. OldFD->setIsMultiVersion();
  10247. OldDecl = OldFD;
  10248. Redeclaration = true;
  10249. return true;
  10250. }
  10251. }
  10252. return false;
  10253. }
  10254. // Multiversioned redeclarations aren't allowed to omit the attribute, except
  10255. // for target_clones and target_version.
  10256. if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
  10257. OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones &&
  10258. OldFD->getMultiVersionKind() != MultiVersionKind::TargetVersion) {
  10259. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  10260. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  10261. NewFD->setInvalidDecl();
  10262. return true;
  10263. }
  10264. if (!OldFD->isMultiVersion()) {
  10265. switch (MVKind) {
  10266. case MultiVersionKind::Target:
  10267. case MultiVersionKind::TargetVersion:
  10268. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, Redeclaration,
  10269. OldDecl, Previous);
  10270. case MultiVersionKind::TargetClones:
  10271. if (OldFD->isUsed(false)) {
  10272. NewFD->setInvalidDecl();
  10273. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  10274. }
  10275. OldFD->setIsMultiVersion();
  10276. break;
  10277. case MultiVersionKind::CPUDispatch:
  10278. case MultiVersionKind::CPUSpecific:
  10279. case MultiVersionKind::None:
  10280. break;
  10281. }
  10282. }
  10283. // At this point, we have a multiversion function decl (in OldFD) AND an
  10284. // appropriate attribute in the current function decl. Resolve that these are
  10285. // still compatible with previous declarations.
  10286. return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewCPUDisp,
  10287. NewCPUSpec, NewClones, Redeclaration,
  10288. OldDecl, Previous);
  10289. }
  10290. /// Perform semantic checking of a new function declaration.
  10291. ///
  10292. /// Performs semantic analysis of the new function declaration
  10293. /// NewFD. This routine performs all semantic checking that does not
  10294. /// require the actual declarator involved in the declaration, and is
  10295. /// used both for the declaration of functions as they are parsed
  10296. /// (called via ActOnDeclarator) and for the declaration of functions
  10297. /// that have been instantiated via C++ template instantiation (called
  10298. /// via InstantiateDecl).
  10299. ///
  10300. /// \param IsMemberSpecialization whether this new function declaration is
  10301. /// a member specialization (that replaces any definition provided by the
  10302. /// previous declaration).
  10303. ///
  10304. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  10305. ///
  10306. /// \returns true if the function declaration is a redeclaration.
  10307. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  10308. LookupResult &Previous,
  10309. bool IsMemberSpecialization,
  10310. bool DeclIsDefn) {
  10311. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  10312. "Variably modified return types are not handled here");
  10313. // Determine whether the type of this function should be merged with
  10314. // a previous visible declaration. This never happens for functions in C++,
  10315. // and always happens in C if the previous declaration was visible.
  10316. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  10317. !Previous.isShadowed();
  10318. bool Redeclaration = false;
  10319. NamedDecl *OldDecl = nullptr;
  10320. bool MayNeedOverloadableChecks = false;
  10321. // Merge or overload the declaration with an existing declaration of
  10322. // the same name, if appropriate.
  10323. if (!Previous.empty()) {
  10324. // Determine whether NewFD is an overload of PrevDecl or
  10325. // a declaration that requires merging. If it's an overload,
  10326. // there's no more work to do here; we'll just add the new
  10327. // function to the scope.
  10328. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  10329. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  10330. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  10331. Redeclaration = true;
  10332. OldDecl = Candidate;
  10333. }
  10334. } else {
  10335. MayNeedOverloadableChecks = true;
  10336. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  10337. /*NewIsUsingDecl*/ false)) {
  10338. case Ovl_Match:
  10339. Redeclaration = true;
  10340. break;
  10341. case Ovl_NonFunction:
  10342. Redeclaration = true;
  10343. break;
  10344. case Ovl_Overload:
  10345. Redeclaration = false;
  10346. break;
  10347. }
  10348. }
  10349. }
  10350. // Check for a previous extern "C" declaration with this name.
  10351. if (!Redeclaration &&
  10352. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  10353. if (!Previous.empty()) {
  10354. // This is an extern "C" declaration with the same name as a previous
  10355. // declaration, and thus redeclares that entity...
  10356. Redeclaration = true;
  10357. OldDecl = Previous.getFoundDecl();
  10358. MergeTypeWithPrevious = false;
  10359. // ... except in the presence of __attribute__((overloadable)).
  10360. if (OldDecl->hasAttr<OverloadableAttr>() ||
  10361. NewFD->hasAttr<OverloadableAttr>()) {
  10362. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  10363. MayNeedOverloadableChecks = true;
  10364. Redeclaration = false;
  10365. OldDecl = nullptr;
  10366. }
  10367. }
  10368. }
  10369. }
  10370. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
  10371. return Redeclaration;
  10372. // PPC MMA non-pointer types are not allowed as function return types.
  10373. if (Context.getTargetInfo().getTriple().isPPC64() &&
  10374. CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
  10375. NewFD->setInvalidDecl();
  10376. }
  10377. // C++11 [dcl.constexpr]p8:
  10378. // A constexpr specifier for a non-static member function that is not
  10379. // a constructor declares that member function to be const.
  10380. //
  10381. // This needs to be delayed until we know whether this is an out-of-line
  10382. // definition of a static member function.
  10383. //
  10384. // This rule is not present in C++1y, so we produce a backwards
  10385. // compatibility warning whenever it happens in C++11.
  10386. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  10387. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  10388. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  10389. !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
  10390. CXXMethodDecl *OldMD = nullptr;
  10391. if (OldDecl)
  10392. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  10393. if (!OldMD || !OldMD->isStatic()) {
  10394. const FunctionProtoType *FPT =
  10395. MD->getType()->castAs<FunctionProtoType>();
  10396. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  10397. EPI.TypeQuals.addConst();
  10398. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  10399. FPT->getParamTypes(), EPI));
  10400. // Warn that we did this, if we're not performing template instantiation.
  10401. // In that case, we'll have warned already when the template was defined.
  10402. if (!inTemplateInstantiation()) {
  10403. SourceLocation AddConstLoc;
  10404. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  10405. .IgnoreParens().getAs<FunctionTypeLoc>())
  10406. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  10407. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  10408. << FixItHint::CreateInsertion(AddConstLoc, " const");
  10409. }
  10410. }
  10411. }
  10412. if (Redeclaration) {
  10413. // NewFD and OldDecl represent declarations that need to be
  10414. // merged.
  10415. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious,
  10416. DeclIsDefn)) {
  10417. NewFD->setInvalidDecl();
  10418. return Redeclaration;
  10419. }
  10420. Previous.clear();
  10421. Previous.addDecl(OldDecl);
  10422. if (FunctionTemplateDecl *OldTemplateDecl =
  10423. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  10424. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  10425. FunctionTemplateDecl *NewTemplateDecl
  10426. = NewFD->getDescribedFunctionTemplate();
  10427. assert(NewTemplateDecl && "Template/non-template mismatch");
  10428. // The call to MergeFunctionDecl above may have created some state in
  10429. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  10430. // can add it as a redeclaration.
  10431. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  10432. NewFD->setPreviousDeclaration(OldFD);
  10433. if (NewFD->isCXXClassMember()) {
  10434. NewFD->setAccess(OldTemplateDecl->getAccess());
  10435. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  10436. }
  10437. // If this is an explicit specialization of a member that is a function
  10438. // template, mark it as a member specialization.
  10439. if (IsMemberSpecialization &&
  10440. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  10441. NewTemplateDecl->setMemberSpecialization();
  10442. assert(OldTemplateDecl->isMemberSpecialization());
  10443. // Explicit specializations of a member template do not inherit deleted
  10444. // status from the parent member template that they are specializing.
  10445. if (OldFD->isDeleted()) {
  10446. // FIXME: This assert will not hold in the presence of modules.
  10447. assert(OldFD->getCanonicalDecl() == OldFD);
  10448. // FIXME: We need an update record for this AST mutation.
  10449. OldFD->setDeletedAsWritten(false);
  10450. }
  10451. }
  10452. } else {
  10453. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  10454. auto *OldFD = cast<FunctionDecl>(OldDecl);
  10455. // This needs to happen first so that 'inline' propagates.
  10456. NewFD->setPreviousDeclaration(OldFD);
  10457. if (NewFD->isCXXClassMember())
  10458. NewFD->setAccess(OldFD->getAccess());
  10459. }
  10460. }
  10461. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  10462. !NewFD->getAttr<OverloadableAttr>()) {
  10463. assert((Previous.empty() ||
  10464. llvm::any_of(Previous,
  10465. [](const NamedDecl *ND) {
  10466. return ND->hasAttr<OverloadableAttr>();
  10467. })) &&
  10468. "Non-redecls shouldn't happen without overloadable present");
  10469. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  10470. const auto *FD = dyn_cast<FunctionDecl>(ND);
  10471. return FD && !FD->hasAttr<OverloadableAttr>();
  10472. });
  10473. if (OtherUnmarkedIter != Previous.end()) {
  10474. Diag(NewFD->getLocation(),
  10475. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  10476. Diag((*OtherUnmarkedIter)->getLocation(),
  10477. diag::note_attribute_overloadable_prev_overload)
  10478. << false;
  10479. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  10480. }
  10481. }
  10482. if (LangOpts.OpenMP)
  10483. ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
  10484. // Semantic checking for this function declaration (in isolation).
  10485. if (getLangOpts().CPlusPlus) {
  10486. // C++-specific checks.
  10487. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  10488. CheckConstructor(Constructor);
  10489. } else if (CXXDestructorDecl *Destructor =
  10490. dyn_cast<CXXDestructorDecl>(NewFD)) {
  10491. // We check here for invalid destructor names.
  10492. // If we have a friend destructor declaration that is dependent, we can't
  10493. // diagnose right away because cases like this are still valid:
  10494. // template <class T> struct A { friend T::X::~Y(); };
  10495. // struct B { struct Y { ~Y(); }; using X = Y; };
  10496. // template struct A<B>;
  10497. if (NewFD->getFriendObjectKind() == Decl::FriendObjectKind::FOK_None ||
  10498. !Destructor->getThisType()->isDependentType()) {
  10499. CXXRecordDecl *Record = Destructor->getParent();
  10500. QualType ClassType = Context.getTypeDeclType(Record);
  10501. DeclarationName Name = Context.DeclarationNames.getCXXDestructorName(
  10502. Context.getCanonicalType(ClassType));
  10503. if (NewFD->getDeclName() != Name) {
  10504. Diag(NewFD->getLocation(), diag::err_destructor_name);
  10505. NewFD->setInvalidDecl();
  10506. return Redeclaration;
  10507. }
  10508. }
  10509. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  10510. if (auto *TD = Guide->getDescribedFunctionTemplate())
  10511. CheckDeductionGuideTemplate(TD);
  10512. // A deduction guide is not on the list of entities that can be
  10513. // explicitly specialized.
  10514. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  10515. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  10516. << /*explicit specialization*/ 1;
  10517. }
  10518. // Find any virtual functions that this function overrides.
  10519. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  10520. if (!Method->isFunctionTemplateSpecialization() &&
  10521. !Method->getDescribedFunctionTemplate() &&
  10522. Method->isCanonicalDecl()) {
  10523. AddOverriddenMethods(Method->getParent(), Method);
  10524. }
  10525. if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
  10526. // C++2a [class.virtual]p6
  10527. // A virtual method shall not have a requires-clause.
  10528. Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
  10529. diag::err_constrained_virtual_method);
  10530. if (Method->isStatic())
  10531. checkThisInStaticMemberFunctionType(Method);
  10532. }
  10533. // C++20: dcl.decl.general p4:
  10534. // The optional requires-clause ([temp.pre]) in an init-declarator or
  10535. // member-declarator shall be present only if the declarator declares a
  10536. // templated function ([dcl.fct]).
  10537. if (Expr *TRC = NewFD->getTrailingRequiresClause()) {
  10538. if (!NewFD->isTemplated() && !NewFD->isTemplateInstantiation())
  10539. Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
  10540. }
  10541. if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
  10542. ActOnConversionDeclarator(Conversion);
  10543. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  10544. if (NewFD->isOverloadedOperator() &&
  10545. CheckOverloadedOperatorDeclaration(NewFD)) {
  10546. NewFD->setInvalidDecl();
  10547. return Redeclaration;
  10548. }
  10549. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  10550. if (NewFD->getLiteralIdentifier() &&
  10551. CheckLiteralOperatorDeclaration(NewFD)) {
  10552. NewFD->setInvalidDecl();
  10553. return Redeclaration;
  10554. }
  10555. // In C++, check default arguments now that we have merged decls. Unless
  10556. // the lexical context is the class, because in this case this is done
  10557. // during delayed parsing anyway.
  10558. if (!CurContext->isRecord())
  10559. CheckCXXDefaultArguments(NewFD);
  10560. // If this function is declared as being extern "C", then check to see if
  10561. // the function returns a UDT (class, struct, or union type) that is not C
  10562. // compatible, and if it does, warn the user.
  10563. // But, issue any diagnostic on the first declaration only.
  10564. if (Previous.empty() && NewFD->isExternC()) {
  10565. QualType R = NewFD->getReturnType();
  10566. if (R->isIncompleteType() && !R->isVoidType())
  10567. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  10568. << NewFD << R;
  10569. else if (!R.isPODType(Context) && !R->isVoidType() &&
  10570. !R->isObjCObjectPointerType())
  10571. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  10572. }
  10573. // C++1z [dcl.fct]p6:
  10574. // [...] whether the function has a non-throwing exception-specification
  10575. // [is] part of the function type
  10576. //
  10577. // This results in an ABI break between C++14 and C++17 for functions whose
  10578. // declared type includes an exception-specification in a parameter or
  10579. // return type. (Exception specifications on the function itself are OK in
  10580. // most cases, and exception specifications are not permitted in most other
  10581. // contexts where they could make it into a mangling.)
  10582. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  10583. auto HasNoexcept = [&](QualType T) -> bool {
  10584. // Strip off declarator chunks that could be between us and a function
  10585. // type. We don't need to look far, exception specifications are very
  10586. // restricted prior to C++17.
  10587. if (auto *RT = T->getAs<ReferenceType>())
  10588. T = RT->getPointeeType();
  10589. else if (T->isAnyPointerType())
  10590. T = T->getPointeeType();
  10591. else if (auto *MPT = T->getAs<MemberPointerType>())
  10592. T = MPT->getPointeeType();
  10593. if (auto *FPT = T->getAs<FunctionProtoType>())
  10594. if (FPT->isNothrow())
  10595. return true;
  10596. return false;
  10597. };
  10598. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  10599. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  10600. for (QualType T : FPT->param_types())
  10601. AnyNoexcept |= HasNoexcept(T);
  10602. if (AnyNoexcept)
  10603. Diag(NewFD->getLocation(),
  10604. diag::warn_cxx17_compat_exception_spec_in_signature)
  10605. << NewFD;
  10606. }
  10607. if (!Redeclaration && LangOpts.CUDA)
  10608. checkCUDATargetOverload(NewFD, Previous);
  10609. }
  10610. return Redeclaration;
  10611. }
  10612. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  10613. // C++11 [basic.start.main]p3:
  10614. // A program that [...] declares main to be inline, static or
  10615. // constexpr is ill-formed.
  10616. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  10617. // appear in a declaration of main.
  10618. // static main is not an error under C99, but we should warn about it.
  10619. // We accept _Noreturn main as an extension.
  10620. if (FD->getStorageClass() == SC_Static)
  10621. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  10622. ? diag::err_static_main : diag::warn_static_main)
  10623. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10624. if (FD->isInlineSpecified())
  10625. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  10626. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  10627. if (DS.isNoreturnSpecified()) {
  10628. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  10629. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  10630. Diag(NoreturnLoc, diag::ext_noreturn_main);
  10631. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  10632. << FixItHint::CreateRemoval(NoreturnRange);
  10633. }
  10634. if (FD->isConstexpr()) {
  10635. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  10636. << FD->isConsteval()
  10637. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  10638. FD->setConstexprKind(ConstexprSpecKind::Unspecified);
  10639. }
  10640. if (getLangOpts().OpenCL) {
  10641. Diag(FD->getLocation(), diag::err_opencl_no_main)
  10642. << FD->hasAttr<OpenCLKernelAttr>();
  10643. FD->setInvalidDecl();
  10644. return;
  10645. }
  10646. // Functions named main in hlsl are default entries, but don't have specific
  10647. // signatures they are required to conform to.
  10648. if (getLangOpts().HLSL)
  10649. return;
  10650. QualType T = FD->getType();
  10651. assert(T->isFunctionType() && "function decl is not of function type");
  10652. const FunctionType* FT = T->castAs<FunctionType>();
  10653. // Set default calling convention for main()
  10654. if (FT->getCallConv() != CC_C) {
  10655. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  10656. FD->setType(QualType(FT, 0));
  10657. T = Context.getCanonicalType(FD->getType());
  10658. }
  10659. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  10660. // In C with GNU extensions we allow main() to have non-integer return
  10661. // type, but we should warn about the extension, and we disable the
  10662. // implicit-return-zero rule.
  10663. // GCC in C mode accepts qualified 'int'.
  10664. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  10665. FD->setHasImplicitReturnZero(true);
  10666. else {
  10667. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  10668. SourceRange RTRange = FD->getReturnTypeSourceRange();
  10669. if (RTRange.isValid())
  10670. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  10671. << FixItHint::CreateReplacement(RTRange, "int");
  10672. }
  10673. } else {
  10674. // In C and C++, main magically returns 0 if you fall off the end;
  10675. // set the flag which tells us that.
  10676. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  10677. // All the standards say that main() should return 'int'.
  10678. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  10679. FD->setHasImplicitReturnZero(true);
  10680. else {
  10681. // Otherwise, this is just a flat-out error.
  10682. SourceRange RTRange = FD->getReturnTypeSourceRange();
  10683. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  10684. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  10685. : FixItHint());
  10686. FD->setInvalidDecl(true);
  10687. }
  10688. }
  10689. // Treat protoless main() as nullary.
  10690. if (isa<FunctionNoProtoType>(FT)) return;
  10691. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  10692. unsigned nparams = FTP->getNumParams();
  10693. assert(FD->getNumParams() == nparams);
  10694. bool HasExtraParameters = (nparams > 3);
  10695. if (FTP->isVariadic()) {
  10696. Diag(FD->getLocation(), diag::ext_variadic_main);
  10697. // FIXME: if we had information about the location of the ellipsis, we
  10698. // could add a FixIt hint to remove it as a parameter.
  10699. }
  10700. // Darwin passes an undocumented fourth argument of type char**. If
  10701. // other platforms start sprouting these, the logic below will start
  10702. // getting shifty.
  10703. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  10704. HasExtraParameters = false;
  10705. if (HasExtraParameters) {
  10706. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  10707. FD->setInvalidDecl(true);
  10708. nparams = 3;
  10709. }
  10710. // FIXME: a lot of the following diagnostics would be improved
  10711. // if we had some location information about types.
  10712. QualType CharPP =
  10713. Context.getPointerType(Context.getPointerType(Context.CharTy));
  10714. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  10715. for (unsigned i = 0; i < nparams; ++i) {
  10716. QualType AT = FTP->getParamType(i);
  10717. bool mismatch = true;
  10718. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  10719. mismatch = false;
  10720. else if (Expected[i] == CharPP) {
  10721. // As an extension, the following forms are okay:
  10722. // char const **
  10723. // char const * const *
  10724. // char * const *
  10725. QualifierCollector qs;
  10726. const PointerType* PT;
  10727. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  10728. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  10729. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  10730. Context.CharTy)) {
  10731. qs.removeConst();
  10732. mismatch = !qs.empty();
  10733. }
  10734. }
  10735. if (mismatch) {
  10736. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  10737. // TODO: suggest replacing given type with expected type
  10738. FD->setInvalidDecl(true);
  10739. }
  10740. }
  10741. if (nparams == 1 && !FD->isInvalidDecl()) {
  10742. Diag(FD->getLocation(), diag::warn_main_one_arg);
  10743. }
  10744. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  10745. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  10746. FD->setInvalidDecl();
  10747. }
  10748. }
  10749. static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
  10750. // Default calling convention for main and wmain is __cdecl
  10751. if (FD->getName() == "main" || FD->getName() == "wmain")
  10752. return false;
  10753. // Default calling convention for MinGW is __cdecl
  10754. const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
  10755. if (T.isWindowsGNUEnvironment())
  10756. return false;
  10757. // Default calling convention for WinMain, wWinMain and DllMain
  10758. // is __stdcall on 32 bit Windows
  10759. if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
  10760. return true;
  10761. return false;
  10762. }
  10763. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  10764. QualType T = FD->getType();
  10765. assert(T->isFunctionType() && "function decl is not of function type");
  10766. const FunctionType *FT = T->castAs<FunctionType>();
  10767. // Set an implicit return of 'zero' if the function can return some integral,
  10768. // enumeration, pointer or nullptr type.
  10769. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  10770. FT->getReturnType()->isAnyPointerType() ||
  10771. FT->getReturnType()->isNullPtrType())
  10772. // DllMain is exempt because a return value of zero means it failed.
  10773. if (FD->getName() != "DllMain")
  10774. FD->setHasImplicitReturnZero(true);
  10775. // Explicity specified calling conventions are applied to MSVC entry points
  10776. if (!hasExplicitCallingConv(T)) {
  10777. if (isDefaultStdCall(FD, *this)) {
  10778. if (FT->getCallConv() != CC_X86StdCall) {
  10779. FT = Context.adjustFunctionType(
  10780. FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
  10781. FD->setType(QualType(FT, 0));
  10782. }
  10783. } else if (FT->getCallConv() != CC_C) {
  10784. FT = Context.adjustFunctionType(FT,
  10785. FT->getExtInfo().withCallingConv(CC_C));
  10786. FD->setType(QualType(FT, 0));
  10787. }
  10788. }
  10789. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  10790. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  10791. FD->setInvalidDecl();
  10792. }
  10793. }
  10794. void Sema::CheckHLSLEntryPoint(FunctionDecl *FD) {
  10795. auto &TargetInfo = getASTContext().getTargetInfo();
  10796. auto const Triple = TargetInfo.getTriple();
  10797. switch (Triple.getEnvironment()) {
  10798. default:
  10799. // FIXME: check all shader profiles.
  10800. break;
  10801. case llvm::Triple::EnvironmentType::Compute:
  10802. if (!FD->hasAttr<HLSLNumThreadsAttr>()) {
  10803. Diag(FD->getLocation(), diag::err_hlsl_missing_numthreads)
  10804. << Triple.getEnvironmentName();
  10805. FD->setInvalidDecl();
  10806. }
  10807. break;
  10808. }
  10809. for (const auto *Param : FD->parameters()) {
  10810. if (!Param->hasAttr<HLSLAnnotationAttr>()) {
  10811. // FIXME: Handle struct parameters where annotations are on struct fields.
  10812. // See: https://github.com/llvm/llvm-project/issues/57875
  10813. Diag(FD->getLocation(), diag::err_hlsl_missing_semantic_annotation);
  10814. Diag(Param->getLocation(), diag::note_previous_decl) << Param;
  10815. FD->setInvalidDecl();
  10816. }
  10817. }
  10818. // FIXME: Verify return type semantic annotation.
  10819. }
  10820. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  10821. // FIXME: Need strict checking. In C89, we need to check for
  10822. // any assignment, increment, decrement, function-calls, or
  10823. // commas outside of a sizeof. In C99, it's the same list,
  10824. // except that the aforementioned are allowed in unevaluated
  10825. // expressions. Everything else falls under the
  10826. // "may accept other forms of constant expressions" exception.
  10827. //
  10828. // Regular C++ code will not end up here (exceptions: language extensions,
  10829. // OpenCL C++ etc), so the constant expression rules there don't matter.
  10830. if (Init->isValueDependent()) {
  10831. assert(Init->containsErrors() &&
  10832. "Dependent code should only occur in error-recovery path.");
  10833. return true;
  10834. }
  10835. const Expr *Culprit;
  10836. if (Init->isConstantInitializer(Context, false, &Culprit))
  10837. return false;
  10838. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  10839. << Culprit->getSourceRange();
  10840. return true;
  10841. }
  10842. namespace {
  10843. // Visits an initialization expression to see if OrigDecl is evaluated in
  10844. // its own initialization and throws a warning if it does.
  10845. class SelfReferenceChecker
  10846. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  10847. Sema &S;
  10848. Decl *OrigDecl;
  10849. bool isRecordType;
  10850. bool isPODType;
  10851. bool isReferenceType;
  10852. bool isInitList;
  10853. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  10854. public:
  10855. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  10856. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  10857. S(S), OrigDecl(OrigDecl) {
  10858. isPODType = false;
  10859. isRecordType = false;
  10860. isReferenceType = false;
  10861. isInitList = false;
  10862. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  10863. isPODType = VD->getType().isPODType(S.Context);
  10864. isRecordType = VD->getType()->isRecordType();
  10865. isReferenceType = VD->getType()->isReferenceType();
  10866. }
  10867. }
  10868. // For most expressions, just call the visitor. For initializer lists,
  10869. // track the index of the field being initialized since fields are
  10870. // initialized in order allowing use of previously initialized fields.
  10871. void CheckExpr(Expr *E) {
  10872. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  10873. if (!InitList) {
  10874. Visit(E);
  10875. return;
  10876. }
  10877. // Track and increment the index here.
  10878. isInitList = true;
  10879. InitFieldIndex.push_back(0);
  10880. for (auto *Child : InitList->children()) {
  10881. CheckExpr(cast<Expr>(Child));
  10882. ++InitFieldIndex.back();
  10883. }
  10884. InitFieldIndex.pop_back();
  10885. }
  10886. // Returns true if MemberExpr is checked and no further checking is needed.
  10887. // Returns false if additional checking is required.
  10888. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  10889. llvm::SmallVector<FieldDecl*, 4> Fields;
  10890. Expr *Base = E;
  10891. bool ReferenceField = false;
  10892. // Get the field members used.
  10893. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  10894. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  10895. if (!FD)
  10896. return false;
  10897. Fields.push_back(FD);
  10898. if (FD->getType()->isReferenceType())
  10899. ReferenceField = true;
  10900. Base = ME->getBase()->IgnoreParenImpCasts();
  10901. }
  10902. // Keep checking only if the base Decl is the same.
  10903. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  10904. if (!DRE || DRE->getDecl() != OrigDecl)
  10905. return false;
  10906. // A reference field can be bound to an unininitialized field.
  10907. if (CheckReference && !ReferenceField)
  10908. return true;
  10909. // Convert FieldDecls to their index number.
  10910. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  10911. for (const FieldDecl *I : llvm::reverse(Fields))
  10912. UsedFieldIndex.push_back(I->getFieldIndex());
  10913. // See if a warning is needed by checking the first difference in index
  10914. // numbers. If field being used has index less than the field being
  10915. // initialized, then the use is safe.
  10916. for (auto UsedIter = UsedFieldIndex.begin(),
  10917. UsedEnd = UsedFieldIndex.end(),
  10918. OrigIter = InitFieldIndex.begin(),
  10919. OrigEnd = InitFieldIndex.end();
  10920. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  10921. if (*UsedIter < *OrigIter)
  10922. return true;
  10923. if (*UsedIter > *OrigIter)
  10924. break;
  10925. }
  10926. // TODO: Add a different warning which will print the field names.
  10927. HandleDeclRefExpr(DRE);
  10928. return true;
  10929. }
  10930. // For most expressions, the cast is directly above the DeclRefExpr.
  10931. // For conditional operators, the cast can be outside the conditional
  10932. // operator if both expressions are DeclRefExpr's.
  10933. void HandleValue(Expr *E) {
  10934. E = E->IgnoreParens();
  10935. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  10936. HandleDeclRefExpr(DRE);
  10937. return;
  10938. }
  10939. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  10940. Visit(CO->getCond());
  10941. HandleValue(CO->getTrueExpr());
  10942. HandleValue(CO->getFalseExpr());
  10943. return;
  10944. }
  10945. if (BinaryConditionalOperator *BCO =
  10946. dyn_cast<BinaryConditionalOperator>(E)) {
  10947. Visit(BCO->getCond());
  10948. HandleValue(BCO->getFalseExpr());
  10949. return;
  10950. }
  10951. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  10952. HandleValue(OVE->getSourceExpr());
  10953. return;
  10954. }
  10955. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  10956. if (BO->getOpcode() == BO_Comma) {
  10957. Visit(BO->getLHS());
  10958. HandleValue(BO->getRHS());
  10959. return;
  10960. }
  10961. }
  10962. if (isa<MemberExpr>(E)) {
  10963. if (isInitList) {
  10964. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  10965. false /*CheckReference*/))
  10966. return;
  10967. }
  10968. Expr *Base = E->IgnoreParenImpCasts();
  10969. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  10970. // Check for static member variables and don't warn on them.
  10971. if (!isa<FieldDecl>(ME->getMemberDecl()))
  10972. return;
  10973. Base = ME->getBase()->IgnoreParenImpCasts();
  10974. }
  10975. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  10976. HandleDeclRefExpr(DRE);
  10977. return;
  10978. }
  10979. Visit(E);
  10980. }
  10981. // Reference types not handled in HandleValue are handled here since all
  10982. // uses of references are bad, not just r-value uses.
  10983. void VisitDeclRefExpr(DeclRefExpr *E) {
  10984. if (isReferenceType)
  10985. HandleDeclRefExpr(E);
  10986. }
  10987. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  10988. if (E->getCastKind() == CK_LValueToRValue) {
  10989. HandleValue(E->getSubExpr());
  10990. return;
  10991. }
  10992. Inherited::VisitImplicitCastExpr(E);
  10993. }
  10994. void VisitMemberExpr(MemberExpr *E) {
  10995. if (isInitList) {
  10996. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  10997. return;
  10998. }
  10999. // Don't warn on arrays since they can be treated as pointers.
  11000. if (E->getType()->canDecayToPointerType()) return;
  11001. // Warn when a non-static method call is followed by non-static member
  11002. // field accesses, which is followed by a DeclRefExpr.
  11003. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  11004. bool Warn = (MD && !MD->isStatic());
  11005. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  11006. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  11007. if (!isa<FieldDecl>(ME->getMemberDecl()))
  11008. Warn = false;
  11009. Base = ME->getBase()->IgnoreParenImpCasts();
  11010. }
  11011. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  11012. if (Warn)
  11013. HandleDeclRefExpr(DRE);
  11014. return;
  11015. }
  11016. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  11017. // Visit that expression.
  11018. Visit(Base);
  11019. }
  11020. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  11021. Expr *Callee = E->getCallee();
  11022. if (isa<UnresolvedLookupExpr>(Callee))
  11023. return Inherited::VisitCXXOperatorCallExpr(E);
  11024. Visit(Callee);
  11025. for (auto Arg: E->arguments())
  11026. HandleValue(Arg->IgnoreParenImpCasts());
  11027. }
  11028. void VisitUnaryOperator(UnaryOperator *E) {
  11029. // For POD record types, addresses of its own members are well-defined.
  11030. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  11031. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  11032. if (!isPODType)
  11033. HandleValue(E->getSubExpr());
  11034. return;
  11035. }
  11036. if (E->isIncrementDecrementOp()) {
  11037. HandleValue(E->getSubExpr());
  11038. return;
  11039. }
  11040. Inherited::VisitUnaryOperator(E);
  11041. }
  11042. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  11043. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  11044. if (E->getConstructor()->isCopyConstructor()) {
  11045. Expr *ArgExpr = E->getArg(0);
  11046. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  11047. if (ILE->getNumInits() == 1)
  11048. ArgExpr = ILE->getInit(0);
  11049. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  11050. if (ICE->getCastKind() == CK_NoOp)
  11051. ArgExpr = ICE->getSubExpr();
  11052. HandleValue(ArgExpr);
  11053. return;
  11054. }
  11055. Inherited::VisitCXXConstructExpr(E);
  11056. }
  11057. void VisitCallExpr(CallExpr *E) {
  11058. // Treat std::move as a use.
  11059. if (E->isCallToStdMove()) {
  11060. HandleValue(E->getArg(0));
  11061. return;
  11062. }
  11063. Inherited::VisitCallExpr(E);
  11064. }
  11065. void VisitBinaryOperator(BinaryOperator *E) {
  11066. if (E->isCompoundAssignmentOp()) {
  11067. HandleValue(E->getLHS());
  11068. Visit(E->getRHS());
  11069. return;
  11070. }
  11071. Inherited::VisitBinaryOperator(E);
  11072. }
  11073. // A custom visitor for BinaryConditionalOperator is needed because the
  11074. // regular visitor would check the condition and true expression separately
  11075. // but both point to the same place giving duplicate diagnostics.
  11076. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  11077. Visit(E->getCond());
  11078. Visit(E->getFalseExpr());
  11079. }
  11080. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  11081. Decl* ReferenceDecl = DRE->getDecl();
  11082. if (OrigDecl != ReferenceDecl) return;
  11083. unsigned diag;
  11084. if (isReferenceType) {
  11085. diag = diag::warn_uninit_self_reference_in_reference_init;
  11086. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  11087. diag = diag::warn_static_self_reference_in_init;
  11088. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  11089. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  11090. DRE->getDecl()->getType()->isRecordType()) {
  11091. diag = diag::warn_uninit_self_reference_in_init;
  11092. } else {
  11093. // Local variables will be handled by the CFG analysis.
  11094. return;
  11095. }
  11096. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  11097. S.PDiag(diag)
  11098. << DRE->getDecl() << OrigDecl->getLocation()
  11099. << DRE->getSourceRange());
  11100. }
  11101. };
  11102. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  11103. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  11104. bool DirectInit) {
  11105. // Parameters arguments are occassionially constructed with itself,
  11106. // for instance, in recursive functions. Skip them.
  11107. if (isa<ParmVarDecl>(OrigDecl))
  11108. return;
  11109. E = E->IgnoreParens();
  11110. // Skip checking T a = a where T is not a record or reference type.
  11111. // Doing so is a way to silence uninitialized warnings.
  11112. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  11113. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  11114. if (ICE->getCastKind() == CK_LValueToRValue)
  11115. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  11116. if (DRE->getDecl() == OrigDecl)
  11117. return;
  11118. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  11119. }
  11120. } // end anonymous namespace
  11121. namespace {
  11122. // Simple wrapper to add the name of a variable or (if no variable is
  11123. // available) a DeclarationName into a diagnostic.
  11124. struct VarDeclOrName {
  11125. VarDecl *VDecl;
  11126. DeclarationName Name;
  11127. friend const Sema::SemaDiagnosticBuilder &
  11128. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  11129. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  11130. }
  11131. };
  11132. } // end anonymous namespace
  11133. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  11134. DeclarationName Name, QualType Type,
  11135. TypeSourceInfo *TSI,
  11136. SourceRange Range, bool DirectInit,
  11137. Expr *Init) {
  11138. bool IsInitCapture = !VDecl;
  11139. assert((!VDecl || !VDecl->isInitCapture()) &&
  11140. "init captures are expected to be deduced prior to initialization");
  11141. VarDeclOrName VN{VDecl, Name};
  11142. DeducedType *Deduced = Type->getContainedDeducedType();
  11143. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  11144. // C++11 [dcl.spec.auto]p3
  11145. if (!Init) {
  11146. assert(VDecl && "no init for init capture deduction?");
  11147. // Except for class argument deduction, and then for an initializing
  11148. // declaration only, i.e. no static at class scope or extern.
  11149. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  11150. VDecl->hasExternalStorage() ||
  11151. VDecl->isStaticDataMember()) {
  11152. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  11153. << VDecl->getDeclName() << Type;
  11154. return QualType();
  11155. }
  11156. }
  11157. ArrayRef<Expr*> DeduceInits;
  11158. if (Init)
  11159. DeduceInits = Init;
  11160. if (DirectInit) {
  11161. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  11162. DeduceInits = PL->exprs();
  11163. }
  11164. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  11165. assert(VDecl && "non-auto type for init capture deduction?");
  11166. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  11167. InitializationKind Kind = InitializationKind::CreateForInit(
  11168. VDecl->getLocation(), DirectInit, Init);
  11169. // FIXME: Initialization should not be taking a mutable list of inits.
  11170. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  11171. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  11172. InitsCopy);
  11173. }
  11174. if (DirectInit) {
  11175. if (auto *IL = dyn_cast<InitListExpr>(Init))
  11176. DeduceInits = IL->inits();
  11177. }
  11178. // Deduction only works if we have exactly one source expression.
  11179. if (DeduceInits.empty()) {
  11180. // It isn't possible to write this directly, but it is possible to
  11181. // end up in this situation with "auto x(some_pack...);"
  11182. Diag(Init->getBeginLoc(), IsInitCapture
  11183. ? diag::err_init_capture_no_expression
  11184. : diag::err_auto_var_init_no_expression)
  11185. << VN << Type << Range;
  11186. return QualType();
  11187. }
  11188. if (DeduceInits.size() > 1) {
  11189. Diag(DeduceInits[1]->getBeginLoc(),
  11190. IsInitCapture ? diag::err_init_capture_multiple_expressions
  11191. : diag::err_auto_var_init_multiple_expressions)
  11192. << VN << Type << Range;
  11193. return QualType();
  11194. }
  11195. Expr *DeduceInit = DeduceInits[0];
  11196. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  11197. Diag(Init->getBeginLoc(), IsInitCapture
  11198. ? diag::err_init_capture_paren_braces
  11199. : diag::err_auto_var_init_paren_braces)
  11200. << isa<InitListExpr>(Init) << VN << Type << Range;
  11201. return QualType();
  11202. }
  11203. // Expressions default to 'id' when we're in a debugger.
  11204. bool DefaultedAnyToId = false;
  11205. if (getLangOpts().DebuggerCastResultToId &&
  11206. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  11207. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  11208. if (Result.isInvalid()) {
  11209. return QualType();
  11210. }
  11211. Init = Result.get();
  11212. DefaultedAnyToId = true;
  11213. }
  11214. // C++ [dcl.decomp]p1:
  11215. // If the assignment-expression [...] has array type A and no ref-qualifier
  11216. // is present, e has type cv A
  11217. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  11218. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  11219. DeduceInit->getType()->isConstantArrayType())
  11220. return Context.getQualifiedType(DeduceInit->getType(),
  11221. Type.getQualifiers());
  11222. QualType DeducedType;
  11223. TemplateDeductionInfo Info(DeduceInit->getExprLoc());
  11224. TemplateDeductionResult Result =
  11225. DeduceAutoType(TSI->getTypeLoc(), DeduceInit, DeducedType, Info);
  11226. if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed) {
  11227. if (!IsInitCapture)
  11228. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  11229. else if (isa<InitListExpr>(Init))
  11230. Diag(Range.getBegin(),
  11231. diag::err_init_capture_deduction_failure_from_init_list)
  11232. << VN
  11233. << (DeduceInit->getType().isNull() ? TSI->getType()
  11234. : DeduceInit->getType())
  11235. << DeduceInit->getSourceRange();
  11236. else
  11237. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  11238. << VN << TSI->getType()
  11239. << (DeduceInit->getType().isNull() ? TSI->getType()
  11240. : DeduceInit->getType())
  11241. << DeduceInit->getSourceRange();
  11242. }
  11243. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  11244. // 'id' instead of a specific object type prevents most of our usual
  11245. // checks.
  11246. // We only want to warn outside of template instantiations, though:
  11247. // inside a template, the 'id' could have come from a parameter.
  11248. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  11249. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  11250. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  11251. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  11252. }
  11253. return DeducedType;
  11254. }
  11255. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  11256. Expr *Init) {
  11257. assert(!Init || !Init->containsErrors());
  11258. QualType DeducedType = deduceVarTypeFromInitializer(
  11259. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  11260. VDecl->getSourceRange(), DirectInit, Init);
  11261. if (DeducedType.isNull()) {
  11262. VDecl->setInvalidDecl();
  11263. return true;
  11264. }
  11265. VDecl->setType(DeducedType);
  11266. assert(VDecl->isLinkageValid());
  11267. // In ARC, infer lifetime.
  11268. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  11269. VDecl->setInvalidDecl();
  11270. if (getLangOpts().OpenCL)
  11271. deduceOpenCLAddressSpace(VDecl);
  11272. // If this is a redeclaration, check that the type we just deduced matches
  11273. // the previously declared type.
  11274. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  11275. // We never need to merge the type, because we cannot form an incomplete
  11276. // array of auto, nor deduce such a type.
  11277. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  11278. }
  11279. // Check the deduced type is valid for a variable declaration.
  11280. CheckVariableDeclarationType(VDecl);
  11281. return VDecl->isInvalidDecl();
  11282. }
  11283. void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
  11284. SourceLocation Loc) {
  11285. if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
  11286. Init = EWC->getSubExpr();
  11287. if (auto *CE = dyn_cast<ConstantExpr>(Init))
  11288. Init = CE->getSubExpr();
  11289. QualType InitType = Init->getType();
  11290. assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  11291. InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
  11292. "shouldn't be called if type doesn't have a non-trivial C struct");
  11293. if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
  11294. for (auto *I : ILE->inits()) {
  11295. if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
  11296. !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
  11297. continue;
  11298. SourceLocation SL = I->getExprLoc();
  11299. checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
  11300. }
  11301. return;
  11302. }
  11303. if (isa<ImplicitValueInitExpr>(Init)) {
  11304. if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  11305. checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
  11306. NTCUK_Init);
  11307. } else {
  11308. // Assume all other explicit initializers involving copying some existing
  11309. // object.
  11310. // TODO: ignore any explicit initializers where we can guarantee
  11311. // copy-elision.
  11312. if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
  11313. checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
  11314. }
  11315. }
  11316. namespace {
  11317. bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
  11318. // Ignore unavailable fields. A field can be marked as unavailable explicitly
  11319. // in the source code or implicitly by the compiler if it is in a union
  11320. // defined in a system header and has non-trivial ObjC ownership
  11321. // qualifications. We don't want those fields to participate in determining
  11322. // whether the containing union is non-trivial.
  11323. return FD->hasAttr<UnavailableAttr>();
  11324. }
  11325. struct DiagNonTrivalCUnionDefaultInitializeVisitor
  11326. : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  11327. void> {
  11328. using Super =
  11329. DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
  11330. void>;
  11331. DiagNonTrivalCUnionDefaultInitializeVisitor(
  11332. QualType OrigTy, SourceLocation OrigLoc,
  11333. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  11334. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  11335. void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
  11336. const FieldDecl *FD, bool InNonTrivialUnion) {
  11337. if (const auto *AT = S.Context.getAsArrayType(QT))
  11338. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  11339. InNonTrivialUnion);
  11340. return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
  11341. }
  11342. void visitARCStrong(QualType QT, const FieldDecl *FD,
  11343. bool InNonTrivialUnion) {
  11344. if (InNonTrivialUnion)
  11345. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11346. << 1 << 0 << QT << FD->getName();
  11347. }
  11348. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11349. if (InNonTrivialUnion)
  11350. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11351. << 1 << 0 << QT << FD->getName();
  11352. }
  11353. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11354. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  11355. if (RD->isUnion()) {
  11356. if (OrigLoc.isValid()) {
  11357. bool IsUnion = false;
  11358. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  11359. IsUnion = OrigRD->isUnion();
  11360. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  11361. << 0 << OrigTy << IsUnion << UseContext;
  11362. // Reset OrigLoc so that this diagnostic is emitted only once.
  11363. OrigLoc = SourceLocation();
  11364. }
  11365. InNonTrivialUnion = true;
  11366. }
  11367. if (InNonTrivialUnion)
  11368. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  11369. << 0 << 0 << QT.getUnqualifiedType() << "";
  11370. for (const FieldDecl *FD : RD->fields())
  11371. if (!shouldIgnoreForRecordTriviality(FD))
  11372. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  11373. }
  11374. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  11375. // The non-trivial C union type or the struct/union type that contains a
  11376. // non-trivial C union.
  11377. QualType OrigTy;
  11378. SourceLocation OrigLoc;
  11379. Sema::NonTrivialCUnionContext UseContext;
  11380. Sema &S;
  11381. };
  11382. struct DiagNonTrivalCUnionDestructedTypeVisitor
  11383. : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
  11384. using Super =
  11385. DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
  11386. DiagNonTrivalCUnionDestructedTypeVisitor(
  11387. QualType OrigTy, SourceLocation OrigLoc,
  11388. Sema::NonTrivialCUnionContext UseContext, Sema &S)
  11389. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  11390. void visitWithKind(QualType::DestructionKind DK, QualType QT,
  11391. const FieldDecl *FD, bool InNonTrivialUnion) {
  11392. if (const auto *AT = S.Context.getAsArrayType(QT))
  11393. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  11394. InNonTrivialUnion);
  11395. return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
  11396. }
  11397. void visitARCStrong(QualType QT, const FieldDecl *FD,
  11398. bool InNonTrivialUnion) {
  11399. if (InNonTrivialUnion)
  11400. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11401. << 1 << 1 << QT << FD->getName();
  11402. }
  11403. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11404. if (InNonTrivialUnion)
  11405. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11406. << 1 << 1 << QT << FD->getName();
  11407. }
  11408. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11409. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  11410. if (RD->isUnion()) {
  11411. if (OrigLoc.isValid()) {
  11412. bool IsUnion = false;
  11413. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  11414. IsUnion = OrigRD->isUnion();
  11415. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  11416. << 1 << OrigTy << IsUnion << UseContext;
  11417. // Reset OrigLoc so that this diagnostic is emitted only once.
  11418. OrigLoc = SourceLocation();
  11419. }
  11420. InNonTrivialUnion = true;
  11421. }
  11422. if (InNonTrivialUnion)
  11423. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  11424. << 0 << 1 << QT.getUnqualifiedType() << "";
  11425. for (const FieldDecl *FD : RD->fields())
  11426. if (!shouldIgnoreForRecordTriviality(FD))
  11427. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  11428. }
  11429. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  11430. void visitCXXDestructor(QualType QT, const FieldDecl *FD,
  11431. bool InNonTrivialUnion) {}
  11432. // The non-trivial C union type or the struct/union type that contains a
  11433. // non-trivial C union.
  11434. QualType OrigTy;
  11435. SourceLocation OrigLoc;
  11436. Sema::NonTrivialCUnionContext UseContext;
  11437. Sema &S;
  11438. };
  11439. struct DiagNonTrivalCUnionCopyVisitor
  11440. : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
  11441. using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
  11442. DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
  11443. Sema::NonTrivialCUnionContext UseContext,
  11444. Sema &S)
  11445. : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
  11446. void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
  11447. const FieldDecl *FD, bool InNonTrivialUnion) {
  11448. if (const auto *AT = S.Context.getAsArrayType(QT))
  11449. return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
  11450. InNonTrivialUnion);
  11451. return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
  11452. }
  11453. void visitARCStrong(QualType QT, const FieldDecl *FD,
  11454. bool InNonTrivialUnion) {
  11455. if (InNonTrivialUnion)
  11456. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11457. << 1 << 2 << QT << FD->getName();
  11458. }
  11459. void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11460. if (InNonTrivialUnion)
  11461. S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
  11462. << 1 << 2 << QT << FD->getName();
  11463. }
  11464. void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
  11465. const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
  11466. if (RD->isUnion()) {
  11467. if (OrigLoc.isValid()) {
  11468. bool IsUnion = false;
  11469. if (auto *OrigRD = OrigTy->getAsRecordDecl())
  11470. IsUnion = OrigRD->isUnion();
  11471. S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
  11472. << 2 << OrigTy << IsUnion << UseContext;
  11473. // Reset OrigLoc so that this diagnostic is emitted only once.
  11474. OrigLoc = SourceLocation();
  11475. }
  11476. InNonTrivialUnion = true;
  11477. }
  11478. if (InNonTrivialUnion)
  11479. S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
  11480. << 0 << 2 << QT.getUnqualifiedType() << "";
  11481. for (const FieldDecl *FD : RD->fields())
  11482. if (!shouldIgnoreForRecordTriviality(FD))
  11483. asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
  11484. }
  11485. void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
  11486. const FieldDecl *FD, bool InNonTrivialUnion) {}
  11487. void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
  11488. void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
  11489. bool InNonTrivialUnion) {}
  11490. // The non-trivial C union type or the struct/union type that contains a
  11491. // non-trivial C union.
  11492. QualType OrigTy;
  11493. SourceLocation OrigLoc;
  11494. Sema::NonTrivialCUnionContext UseContext;
  11495. Sema &S;
  11496. };
  11497. } // namespace
  11498. void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
  11499. NonTrivialCUnionContext UseContext,
  11500. unsigned NonTrivialKind) {
  11501. assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  11502. QT.hasNonTrivialToPrimitiveDestructCUnion() ||
  11503. QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
  11504. "shouldn't be called if type doesn't have a non-trivial C union");
  11505. if ((NonTrivialKind & NTCUK_Init) &&
  11506. QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  11507. DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
  11508. .visit(QT, nullptr, false);
  11509. if ((NonTrivialKind & NTCUK_Destruct) &&
  11510. QT.hasNonTrivialToPrimitiveDestructCUnion())
  11511. DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
  11512. .visit(QT, nullptr, false);
  11513. if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
  11514. DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
  11515. .visit(QT, nullptr, false);
  11516. }
  11517. /// AddInitializerToDecl - Adds the initializer Init to the
  11518. /// declaration dcl. If DirectInit is true, this is C++ direct
  11519. /// initialization rather than copy initialization.
  11520. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  11521. // If there is no declaration, there was an error parsing it. Just ignore
  11522. // the initializer.
  11523. if (!RealDecl || RealDecl->isInvalidDecl()) {
  11524. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  11525. return;
  11526. }
  11527. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  11528. // Pure-specifiers are handled in ActOnPureSpecifier.
  11529. Diag(Method->getLocation(), diag::err_member_function_initialization)
  11530. << Method->getDeclName() << Init->getSourceRange();
  11531. Method->setInvalidDecl();
  11532. return;
  11533. }
  11534. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  11535. if (!VDecl) {
  11536. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  11537. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  11538. RealDecl->setInvalidDecl();
  11539. return;
  11540. }
  11541. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  11542. if (VDecl->getType()->isUndeducedType()) {
  11543. // Attempt typo correction early so that the type of the init expression can
  11544. // be deduced based on the chosen correction if the original init contains a
  11545. // TypoExpr.
  11546. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  11547. if (!Res.isUsable()) {
  11548. // There are unresolved typos in Init, just drop them.
  11549. // FIXME: improve the recovery strategy to preserve the Init.
  11550. RealDecl->setInvalidDecl();
  11551. return;
  11552. }
  11553. if (Res.get()->containsErrors()) {
  11554. // Invalidate the decl as we don't know the type for recovery-expr yet.
  11555. RealDecl->setInvalidDecl();
  11556. VDecl->setInit(Res.get());
  11557. return;
  11558. }
  11559. Init = Res.get();
  11560. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  11561. return;
  11562. }
  11563. // dllimport cannot be used on variable definitions.
  11564. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  11565. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  11566. VDecl->setInvalidDecl();
  11567. return;
  11568. }
  11569. // C99 6.7.8p5. If the declaration of an identifier has block scope, and
  11570. // the identifier has external or internal linkage, the declaration shall
  11571. // have no initializer for the identifier.
  11572. // C++14 [dcl.init]p5 is the same restriction for C++.
  11573. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  11574. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  11575. VDecl->setInvalidDecl();
  11576. return;
  11577. }
  11578. if (!VDecl->getType()->isDependentType()) {
  11579. // A definition must end up with a complete type, which means it must be
  11580. // complete with the restriction that an array type might be completed by
  11581. // the initializer; note that later code assumes this restriction.
  11582. QualType BaseDeclType = VDecl->getType();
  11583. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  11584. BaseDeclType = Array->getElementType();
  11585. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  11586. diag::err_typecheck_decl_incomplete_type)) {
  11587. RealDecl->setInvalidDecl();
  11588. return;
  11589. }
  11590. // The variable can not have an abstract class type.
  11591. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  11592. diag::err_abstract_type_in_decl,
  11593. AbstractVariableType))
  11594. VDecl->setInvalidDecl();
  11595. }
  11596. // C++ [module.import/6] external definitions are not permitted in header
  11597. // units.
  11598. if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
  11599. !VDecl->isInvalidDecl() && VDecl->isThisDeclarationADefinition() &&
  11600. VDecl->getFormalLinkage() == Linkage::ExternalLinkage &&
  11601. !VDecl->isInline() && !VDecl->isTemplated() &&
  11602. !isa<VarTemplateSpecializationDecl>(VDecl)) {
  11603. Diag(VDecl->getLocation(), diag::err_extern_def_in_header_unit);
  11604. VDecl->setInvalidDecl();
  11605. }
  11606. // If adding the initializer will turn this declaration into a definition,
  11607. // and we already have a definition for this variable, diagnose or otherwise
  11608. // handle the situation.
  11609. if (VarDecl *Def = VDecl->getDefinition())
  11610. if (Def != VDecl &&
  11611. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  11612. !VDecl->isThisDeclarationADemotedDefinition() &&
  11613. checkVarDeclRedefinition(Def, VDecl))
  11614. return;
  11615. if (getLangOpts().CPlusPlus) {
  11616. // C++ [class.static.data]p4
  11617. // If a static data member is of const integral or const
  11618. // enumeration type, its declaration in the class definition can
  11619. // specify a constant-initializer which shall be an integral
  11620. // constant expression (5.19). In that case, the member can appear
  11621. // in integral constant expressions. The member shall still be
  11622. // defined in a namespace scope if it is used in the program and the
  11623. // namespace scope definition shall not contain an initializer.
  11624. //
  11625. // We already performed a redefinition check above, but for static
  11626. // data members we also need to check whether there was an in-class
  11627. // declaration with an initializer.
  11628. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  11629. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  11630. << VDecl->getDeclName();
  11631. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  11632. diag::note_previous_initializer)
  11633. << 0;
  11634. return;
  11635. }
  11636. if (VDecl->hasLocalStorage())
  11637. setFunctionHasBranchProtectedScope();
  11638. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  11639. VDecl->setInvalidDecl();
  11640. return;
  11641. }
  11642. }
  11643. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  11644. // a kernel function cannot be initialized."
  11645. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  11646. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  11647. VDecl->setInvalidDecl();
  11648. return;
  11649. }
  11650. // The LoaderUninitialized attribute acts as a definition (of undef).
  11651. if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
  11652. Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
  11653. VDecl->setInvalidDecl();
  11654. return;
  11655. }
  11656. // Get the decls type and save a reference for later, since
  11657. // CheckInitializerTypes may change it.
  11658. QualType DclT = VDecl->getType(), SavT = DclT;
  11659. // Expressions default to 'id' when we're in a debugger
  11660. // and we are assigning it to a variable of Objective-C pointer type.
  11661. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  11662. Init->getType() == Context.UnknownAnyTy) {
  11663. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  11664. if (Result.isInvalid()) {
  11665. VDecl->setInvalidDecl();
  11666. return;
  11667. }
  11668. Init = Result.get();
  11669. }
  11670. // Perform the initialization.
  11671. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  11672. bool IsParenListInit = false;
  11673. if (!VDecl->isInvalidDecl()) {
  11674. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  11675. InitializationKind Kind = InitializationKind::CreateForInit(
  11676. VDecl->getLocation(), DirectInit, Init);
  11677. MultiExprArg Args = Init;
  11678. if (CXXDirectInit)
  11679. Args = MultiExprArg(CXXDirectInit->getExprs(),
  11680. CXXDirectInit->getNumExprs());
  11681. // Try to correct any TypoExprs in the initialization arguments.
  11682. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  11683. ExprResult Res = CorrectDelayedTyposInExpr(
  11684. Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
  11685. [this, Entity, Kind](Expr *E) {
  11686. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  11687. return Init.Failed() ? ExprError() : E;
  11688. });
  11689. if (Res.isInvalid()) {
  11690. VDecl->setInvalidDecl();
  11691. } else if (Res.get() != Args[Idx]) {
  11692. Args[Idx] = Res.get();
  11693. }
  11694. }
  11695. if (VDecl->isInvalidDecl())
  11696. return;
  11697. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  11698. /*TopLevelOfInitList=*/false,
  11699. /*TreatUnavailableAsInvalid=*/false);
  11700. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  11701. if (Result.isInvalid()) {
  11702. // If the provided initializer fails to initialize the var decl,
  11703. // we attach a recovery expr for better recovery.
  11704. auto RecoveryExpr =
  11705. CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
  11706. if (RecoveryExpr.get())
  11707. VDecl->setInit(RecoveryExpr.get());
  11708. return;
  11709. }
  11710. Init = Result.getAs<Expr>();
  11711. IsParenListInit = !InitSeq.steps().empty() &&
  11712. InitSeq.step_begin()->Kind ==
  11713. InitializationSequence::SK_ParenthesizedListInit;
  11714. }
  11715. // Check for self-references within variable initializers.
  11716. // Variables declared within a function/method body (except for references)
  11717. // are handled by a dataflow analysis.
  11718. // This is undefined behavior in C++, but valid in C.
  11719. if (getLangOpts().CPlusPlus)
  11720. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  11721. VDecl->getType()->isReferenceType())
  11722. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  11723. // If the type changed, it means we had an incomplete type that was
  11724. // completed by the initializer. For example:
  11725. // int ary[] = { 1, 3, 5 };
  11726. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  11727. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  11728. VDecl->setType(DclT);
  11729. if (!VDecl->isInvalidDecl()) {
  11730. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  11731. if (VDecl->hasAttr<BlocksAttr>())
  11732. checkRetainCycles(VDecl, Init);
  11733. // It is safe to assign a weak reference into a strong variable.
  11734. // Although this code can still have problems:
  11735. // id x = self.weakProp;
  11736. // id y = self.weakProp;
  11737. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  11738. // paths through the function. This should be revisited if
  11739. // -Wrepeated-use-of-weak is made flow-sensitive.
  11740. if (FunctionScopeInfo *FSI = getCurFunction())
  11741. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  11742. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  11743. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  11744. Init->getBeginLoc()))
  11745. FSI->markSafeWeakUse(Init);
  11746. }
  11747. // The initialization is usually a full-expression.
  11748. //
  11749. // FIXME: If this is a braced initialization of an aggregate, it is not
  11750. // an expression, and each individual field initializer is a separate
  11751. // full-expression. For instance, in:
  11752. //
  11753. // struct Temp { ~Temp(); };
  11754. // struct S { S(Temp); };
  11755. // struct T { S a, b; } t = { Temp(), Temp() }
  11756. //
  11757. // we should destroy the first Temp before constructing the second.
  11758. ExprResult Result =
  11759. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  11760. /*DiscardedValue*/ false, VDecl->isConstexpr());
  11761. if (Result.isInvalid()) {
  11762. VDecl->setInvalidDecl();
  11763. return;
  11764. }
  11765. Init = Result.get();
  11766. // Attach the initializer to the decl.
  11767. VDecl->setInit(Init);
  11768. if (VDecl->isLocalVarDecl()) {
  11769. // Don't check the initializer if the declaration is malformed.
  11770. if (VDecl->isInvalidDecl()) {
  11771. // do nothing
  11772. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  11773. // This is true even in C++ for OpenCL.
  11774. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  11775. CheckForConstantInitializer(Init, DclT);
  11776. // Otherwise, C++ does not restrict the initializer.
  11777. } else if (getLangOpts().CPlusPlus) {
  11778. // do nothing
  11779. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  11780. // static storage duration shall be constant expressions or string literals.
  11781. } else if (VDecl->getStorageClass() == SC_Static) {
  11782. CheckForConstantInitializer(Init, DclT);
  11783. // C89 is stricter than C99 for aggregate initializers.
  11784. // C89 6.5.7p3: All the expressions [...] in an initializer list
  11785. // for an object that has aggregate or union type shall be
  11786. // constant expressions.
  11787. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  11788. isa<InitListExpr>(Init)) {
  11789. const Expr *Culprit;
  11790. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  11791. Diag(Culprit->getExprLoc(),
  11792. diag::ext_aggregate_init_not_constant)
  11793. << Culprit->getSourceRange();
  11794. }
  11795. }
  11796. if (auto *E = dyn_cast<ExprWithCleanups>(Init))
  11797. if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
  11798. if (VDecl->hasLocalStorage())
  11799. BE->getBlockDecl()->setCanAvoidCopyToHeap();
  11800. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  11801. VDecl->getLexicalDeclContext()->isRecord()) {
  11802. // This is an in-class initialization for a static data member, e.g.,
  11803. //
  11804. // struct S {
  11805. // static const int value = 17;
  11806. // };
  11807. // C++ [class.mem]p4:
  11808. // A member-declarator can contain a constant-initializer only
  11809. // if it declares a static member (9.4) of const integral or
  11810. // const enumeration type, see 9.4.2.
  11811. //
  11812. // C++11 [class.static.data]p3:
  11813. // If a non-volatile non-inline const static data member is of integral
  11814. // or enumeration type, its declaration in the class definition can
  11815. // specify a brace-or-equal-initializer in which every initializer-clause
  11816. // that is an assignment-expression is a constant expression. A static
  11817. // data member of literal type can be declared in the class definition
  11818. // with the constexpr specifier; if so, its declaration shall specify a
  11819. // brace-or-equal-initializer in which every initializer-clause that is
  11820. // an assignment-expression is a constant expression.
  11821. // Do nothing on dependent types.
  11822. if (DclT->isDependentType()) {
  11823. // Allow any 'static constexpr' members, whether or not they are of literal
  11824. // type. We separately check that every constexpr variable is of literal
  11825. // type.
  11826. } else if (VDecl->isConstexpr()) {
  11827. // Require constness.
  11828. } else if (!DclT.isConstQualified()) {
  11829. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  11830. << Init->getSourceRange();
  11831. VDecl->setInvalidDecl();
  11832. // We allow integer constant expressions in all cases.
  11833. } else if (DclT->isIntegralOrEnumerationType()) {
  11834. // Check whether the expression is a constant expression.
  11835. SourceLocation Loc;
  11836. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  11837. // In C++11, a non-constexpr const static data member with an
  11838. // in-class initializer cannot be volatile.
  11839. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  11840. else if (Init->isValueDependent())
  11841. ; // Nothing to check.
  11842. else if (Init->isIntegerConstantExpr(Context, &Loc))
  11843. ; // Ok, it's an ICE!
  11844. else if (Init->getType()->isScopedEnumeralType() &&
  11845. Init->isCXX11ConstantExpr(Context))
  11846. ; // Ok, it is a scoped-enum constant expression.
  11847. else if (Init->isEvaluatable(Context)) {
  11848. // If we can constant fold the initializer through heroics, accept it,
  11849. // but report this as a use of an extension for -pedantic.
  11850. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  11851. << Init->getSourceRange();
  11852. } else {
  11853. // Otherwise, this is some crazy unknown case. Report the issue at the
  11854. // location provided by the isIntegerConstantExpr failed check.
  11855. Diag(Loc, diag::err_in_class_initializer_non_constant)
  11856. << Init->getSourceRange();
  11857. VDecl->setInvalidDecl();
  11858. }
  11859. // We allow foldable floating-point constants as an extension.
  11860. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  11861. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  11862. // it anyway and provide a fixit to add the 'constexpr'.
  11863. if (getLangOpts().CPlusPlus11) {
  11864. Diag(VDecl->getLocation(),
  11865. diag::ext_in_class_initializer_float_type_cxx11)
  11866. << DclT << Init->getSourceRange();
  11867. Diag(VDecl->getBeginLoc(),
  11868. diag::note_in_class_initializer_float_type_cxx11)
  11869. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  11870. } else {
  11871. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  11872. << DclT << Init->getSourceRange();
  11873. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  11874. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  11875. << Init->getSourceRange();
  11876. VDecl->setInvalidDecl();
  11877. }
  11878. }
  11879. // Suggest adding 'constexpr' in C++11 for literal types.
  11880. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  11881. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  11882. << DclT << Init->getSourceRange()
  11883. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  11884. VDecl->setConstexpr(true);
  11885. } else {
  11886. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  11887. << DclT << Init->getSourceRange();
  11888. VDecl->setInvalidDecl();
  11889. }
  11890. } else if (VDecl->isFileVarDecl()) {
  11891. // In C, extern is typically used to avoid tentative definitions when
  11892. // declaring variables in headers, but adding an intializer makes it a
  11893. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  11894. // In C++, extern is often used to give implictly static const variables
  11895. // external linkage, so don't warn in that case. If selectany is present,
  11896. // this might be header code intended for C and C++ inclusion, so apply the
  11897. // C++ rules.
  11898. if (VDecl->getStorageClass() == SC_Extern &&
  11899. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  11900. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  11901. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  11902. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  11903. Diag(VDecl->getLocation(), diag::warn_extern_init);
  11904. // In Microsoft C++ mode, a const variable defined in namespace scope has
  11905. // external linkage by default if the variable is declared with
  11906. // __declspec(dllexport).
  11907. if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  11908. getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
  11909. VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
  11910. VDecl->setStorageClass(SC_Extern);
  11911. // C99 6.7.8p4. All file scoped initializers need to be constant.
  11912. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  11913. CheckForConstantInitializer(Init, DclT);
  11914. }
  11915. QualType InitType = Init->getType();
  11916. if (!InitType.isNull() &&
  11917. (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  11918. InitType.hasNonTrivialToPrimitiveCopyCUnion()))
  11919. checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
  11920. // We will represent direct-initialization similarly to copy-initialization:
  11921. // int x(1); -as-> int x = 1;
  11922. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  11923. //
  11924. // Clients that want to distinguish between the two forms, can check for
  11925. // direct initializer using VarDecl::getInitStyle().
  11926. // A major benefit is that clients that don't particularly care about which
  11927. // exactly form was it (like the CodeGen) can handle both cases without
  11928. // special case code.
  11929. // C++ 8.5p11:
  11930. // The form of initialization (using parentheses or '=') is generally
  11931. // insignificant, but does matter when the entity being initialized has a
  11932. // class type.
  11933. if (CXXDirectInit) {
  11934. assert(DirectInit && "Call-style initializer must be direct init.");
  11935. VDecl->setInitStyle(IsParenListInit ? VarDecl::ParenListInit
  11936. : VarDecl::CallInit);
  11937. } else if (DirectInit) {
  11938. // This must be list-initialization. No other way is direct-initialization.
  11939. VDecl->setInitStyle(VarDecl::ListInit);
  11940. }
  11941. if (LangOpts.OpenMP &&
  11942. (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
  11943. VDecl->isFileVarDecl())
  11944. DeclsToCheckForDeferredDiags.insert(VDecl);
  11945. CheckCompleteVariableDeclaration(VDecl);
  11946. }
  11947. /// ActOnInitializerError - Given that there was an error parsing an
  11948. /// initializer for the given declaration, try to at least re-establish
  11949. /// invariants such as whether a variable's type is either dependent or
  11950. /// complete.
  11951. void Sema::ActOnInitializerError(Decl *D) {
  11952. // Our main concern here is re-establishing invariants like "a
  11953. // variable's type is either dependent or complete".
  11954. if (!D || D->isInvalidDecl()) return;
  11955. VarDecl *VD = dyn_cast<VarDecl>(D);
  11956. if (!VD) return;
  11957. // Bindings are not usable if we can't make sense of the initializer.
  11958. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  11959. for (auto *BD : DD->bindings())
  11960. BD->setInvalidDecl();
  11961. // Auto types are meaningless if we can't make sense of the initializer.
  11962. if (VD->getType()->isUndeducedType()) {
  11963. D->setInvalidDecl();
  11964. return;
  11965. }
  11966. QualType Ty = VD->getType();
  11967. if (Ty->isDependentType()) return;
  11968. // Require a complete type.
  11969. if (RequireCompleteType(VD->getLocation(),
  11970. Context.getBaseElementType(Ty),
  11971. diag::err_typecheck_decl_incomplete_type)) {
  11972. VD->setInvalidDecl();
  11973. return;
  11974. }
  11975. // Require a non-abstract type.
  11976. if (RequireNonAbstractType(VD->getLocation(), Ty,
  11977. diag::err_abstract_type_in_decl,
  11978. AbstractVariableType)) {
  11979. VD->setInvalidDecl();
  11980. return;
  11981. }
  11982. // Don't bother complaining about constructors or destructors,
  11983. // though.
  11984. }
  11985. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  11986. // If there is no declaration, there was an error parsing it. Just ignore it.
  11987. if (!RealDecl)
  11988. return;
  11989. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  11990. QualType Type = Var->getType();
  11991. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  11992. if (isa<DecompositionDecl>(RealDecl)) {
  11993. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  11994. Var->setInvalidDecl();
  11995. return;
  11996. }
  11997. if (Type->isUndeducedType() &&
  11998. DeduceVariableDeclarationType(Var, false, nullptr))
  11999. return;
  12000. // C++11 [class.static.data]p3: A static data member can be declared with
  12001. // the constexpr specifier; if so, its declaration shall specify
  12002. // a brace-or-equal-initializer.
  12003. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  12004. // the definition of a variable [...] or the declaration of a static data
  12005. // member.
  12006. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  12007. !Var->isThisDeclarationADemotedDefinition()) {
  12008. if (Var->isStaticDataMember()) {
  12009. // C++1z removes the relevant rule; the in-class declaration is always
  12010. // a definition there.
  12011. if (!getLangOpts().CPlusPlus17 &&
  12012. !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12013. Diag(Var->getLocation(),
  12014. diag::err_constexpr_static_mem_var_requires_init)
  12015. << Var;
  12016. Var->setInvalidDecl();
  12017. return;
  12018. }
  12019. } else {
  12020. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  12021. Var->setInvalidDecl();
  12022. return;
  12023. }
  12024. }
  12025. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  12026. // be initialized.
  12027. if (!Var->isInvalidDecl() &&
  12028. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  12029. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  12030. bool HasConstExprDefaultConstructor = false;
  12031. if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
  12032. for (auto *Ctor : RD->ctors()) {
  12033. if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
  12034. Ctor->getMethodQualifiers().getAddressSpace() ==
  12035. LangAS::opencl_constant) {
  12036. HasConstExprDefaultConstructor = true;
  12037. }
  12038. }
  12039. }
  12040. if (!HasConstExprDefaultConstructor) {
  12041. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  12042. Var->setInvalidDecl();
  12043. return;
  12044. }
  12045. }
  12046. if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
  12047. if (Var->getStorageClass() == SC_Extern) {
  12048. Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
  12049. << Var;
  12050. Var->setInvalidDecl();
  12051. return;
  12052. }
  12053. if (RequireCompleteType(Var->getLocation(), Var->getType(),
  12054. diag::err_typecheck_decl_incomplete_type)) {
  12055. Var->setInvalidDecl();
  12056. return;
  12057. }
  12058. if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
  12059. if (!RD->hasTrivialDefaultConstructor()) {
  12060. Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
  12061. Var->setInvalidDecl();
  12062. return;
  12063. }
  12064. }
  12065. // The declaration is unitialized, no need for further checks.
  12066. return;
  12067. }
  12068. VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
  12069. if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
  12070. Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
  12071. checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
  12072. NTCUC_DefaultInitializedObject, NTCUK_Init);
  12073. switch (DefKind) {
  12074. case VarDecl::Definition:
  12075. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  12076. break;
  12077. // We have an out-of-line definition of a static data member
  12078. // that has an in-class initializer, so we type-check this like
  12079. // a declaration.
  12080. //
  12081. [[fallthrough]];
  12082. case VarDecl::DeclarationOnly:
  12083. // It's only a declaration.
  12084. // Block scope. C99 6.7p7: If an identifier for an object is
  12085. // declared with no linkage (C99 6.2.2p6), the type for the
  12086. // object shall be complete.
  12087. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  12088. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  12089. RequireCompleteType(Var->getLocation(), Type,
  12090. diag::err_typecheck_decl_incomplete_type))
  12091. Var->setInvalidDecl();
  12092. // Make sure that the type is not abstract.
  12093. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  12094. RequireNonAbstractType(Var->getLocation(), Type,
  12095. diag::err_abstract_type_in_decl,
  12096. AbstractVariableType))
  12097. Var->setInvalidDecl();
  12098. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  12099. Var->getStorageClass() == SC_PrivateExtern) {
  12100. Diag(Var->getLocation(), diag::warn_private_extern);
  12101. Diag(Var->getLocation(), diag::note_private_extern);
  12102. }
  12103. if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
  12104. !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
  12105. ExternalDeclarations.push_back(Var);
  12106. return;
  12107. case VarDecl::TentativeDefinition:
  12108. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  12109. // object that has file scope without an initializer, and without a
  12110. // storage-class specifier or with the storage-class specifier "static",
  12111. // constitutes a tentative definition. Note: A tentative definition with
  12112. // external linkage is valid (C99 6.2.2p5).
  12113. if (!Var->isInvalidDecl()) {
  12114. if (const IncompleteArrayType *ArrayT
  12115. = Context.getAsIncompleteArrayType(Type)) {
  12116. if (RequireCompleteSizedType(
  12117. Var->getLocation(), ArrayT->getElementType(),
  12118. diag::err_array_incomplete_or_sizeless_type))
  12119. Var->setInvalidDecl();
  12120. } else if (Var->getStorageClass() == SC_Static) {
  12121. // C99 6.9.2p3: If the declaration of an identifier for an object is
  12122. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  12123. // declared type shall not be an incomplete type.
  12124. // NOTE: code such as the following
  12125. // static struct s;
  12126. // struct s { int a; };
  12127. // is accepted by gcc. Hence here we issue a warning instead of
  12128. // an error and we do not invalidate the static declaration.
  12129. // NOTE: to avoid multiple warnings, only check the first declaration.
  12130. if (Var->isFirstDecl())
  12131. RequireCompleteType(Var->getLocation(), Type,
  12132. diag::ext_typecheck_decl_incomplete_type);
  12133. }
  12134. }
  12135. // Record the tentative definition; we're done.
  12136. if (!Var->isInvalidDecl())
  12137. TentativeDefinitions.push_back(Var);
  12138. return;
  12139. }
  12140. // Provide a specific diagnostic for uninitialized variable
  12141. // definitions with incomplete array type.
  12142. if (Type->isIncompleteArrayType()) {
  12143. if (Var->isConstexpr())
  12144. Diag(Var->getLocation(), diag::err_constexpr_var_requires_const_init)
  12145. << Var;
  12146. else
  12147. Diag(Var->getLocation(),
  12148. diag::err_typecheck_incomplete_array_needs_initializer);
  12149. Var->setInvalidDecl();
  12150. return;
  12151. }
  12152. // Provide a specific diagnostic for uninitialized variable
  12153. // definitions with reference type.
  12154. if (Type->isReferenceType()) {
  12155. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  12156. << Var << SourceRange(Var->getLocation(), Var->getLocation());
  12157. return;
  12158. }
  12159. // Do not attempt to type-check the default initializer for a
  12160. // variable with dependent type.
  12161. if (Type->isDependentType())
  12162. return;
  12163. if (Var->isInvalidDecl())
  12164. return;
  12165. if (!Var->hasAttr<AliasAttr>()) {
  12166. if (RequireCompleteType(Var->getLocation(),
  12167. Context.getBaseElementType(Type),
  12168. diag::err_typecheck_decl_incomplete_type)) {
  12169. Var->setInvalidDecl();
  12170. return;
  12171. }
  12172. } else {
  12173. return;
  12174. }
  12175. // The variable can not have an abstract class type.
  12176. if (RequireNonAbstractType(Var->getLocation(), Type,
  12177. diag::err_abstract_type_in_decl,
  12178. AbstractVariableType)) {
  12179. Var->setInvalidDecl();
  12180. return;
  12181. }
  12182. // Check for jumps past the implicit initializer. C++0x
  12183. // clarifies that this applies to a "variable with automatic
  12184. // storage duration", not a "local variable".
  12185. // C++11 [stmt.dcl]p3
  12186. // A program that jumps from a point where a variable with automatic
  12187. // storage duration is not in scope to a point where it is in scope is
  12188. // ill-formed unless the variable has scalar type, class type with a
  12189. // trivial default constructor and a trivial destructor, a cv-qualified
  12190. // version of one of these types, or an array of one of the preceding
  12191. // types and is declared without an initializer.
  12192. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  12193. if (const RecordType *Record
  12194. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  12195. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  12196. // Mark the function (if we're in one) for further checking even if the
  12197. // looser rules of C++11 do not require such checks, so that we can
  12198. // diagnose incompatibilities with C++98.
  12199. if (!CXXRecord->isPOD())
  12200. setFunctionHasBranchProtectedScope();
  12201. }
  12202. }
  12203. // In OpenCL, we can't initialize objects in the __local address space,
  12204. // even implicitly, so don't synthesize an implicit initializer.
  12205. if (getLangOpts().OpenCL &&
  12206. Var->getType().getAddressSpace() == LangAS::opencl_local)
  12207. return;
  12208. // C++03 [dcl.init]p9:
  12209. // If no initializer is specified for an object, and the
  12210. // object is of (possibly cv-qualified) non-POD class type (or
  12211. // array thereof), the object shall be default-initialized; if
  12212. // the object is of const-qualified type, the underlying class
  12213. // type shall have a user-declared default
  12214. // constructor. Otherwise, if no initializer is specified for
  12215. // a non- static object, the object and its subobjects, if
  12216. // any, have an indeterminate initial value); if the object
  12217. // or any of its subobjects are of const-qualified type, the
  12218. // program is ill-formed.
  12219. // C++0x [dcl.init]p11:
  12220. // If no initializer is specified for an object, the object is
  12221. // default-initialized; [...].
  12222. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  12223. InitializationKind Kind
  12224. = InitializationKind::CreateDefault(Var->getLocation());
  12225. InitializationSequence InitSeq(*this, Entity, Kind, std::nullopt);
  12226. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, std::nullopt);
  12227. if (Init.get()) {
  12228. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  12229. // This is important for template substitution.
  12230. Var->setInitStyle(VarDecl::CallInit);
  12231. } else if (Init.isInvalid()) {
  12232. // If default-init fails, attach a recovery-expr initializer to track
  12233. // that initialization was attempted and failed.
  12234. auto RecoveryExpr =
  12235. CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
  12236. if (RecoveryExpr.get())
  12237. Var->setInit(RecoveryExpr.get());
  12238. }
  12239. CheckCompleteVariableDeclaration(Var);
  12240. }
  12241. }
  12242. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  12243. // If there is no declaration, there was an error parsing it. Ignore it.
  12244. if (!D)
  12245. return;
  12246. VarDecl *VD = dyn_cast<VarDecl>(D);
  12247. if (!VD) {
  12248. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  12249. D->setInvalidDecl();
  12250. return;
  12251. }
  12252. VD->setCXXForRangeDecl(true);
  12253. // for-range-declaration cannot be given a storage class specifier.
  12254. int Error = -1;
  12255. switch (VD->getStorageClass()) {
  12256. case SC_None:
  12257. break;
  12258. case SC_Extern:
  12259. Error = 0;
  12260. break;
  12261. case SC_Static:
  12262. Error = 1;
  12263. break;
  12264. case SC_PrivateExtern:
  12265. Error = 2;
  12266. break;
  12267. case SC_Auto:
  12268. Error = 3;
  12269. break;
  12270. case SC_Register:
  12271. Error = 4;
  12272. break;
  12273. }
  12274. // for-range-declaration cannot be given a storage class specifier con't.
  12275. switch (VD->getTSCSpec()) {
  12276. case TSCS_thread_local:
  12277. Error = 6;
  12278. break;
  12279. case TSCS___thread:
  12280. case TSCS__Thread_local:
  12281. case TSCS_unspecified:
  12282. break;
  12283. }
  12284. if (Error != -1) {
  12285. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  12286. << VD << Error;
  12287. D->setInvalidDecl();
  12288. }
  12289. }
  12290. StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  12291. IdentifierInfo *Ident,
  12292. ParsedAttributes &Attrs) {
  12293. // C++1y [stmt.iter]p1:
  12294. // A range-based for statement of the form
  12295. // for ( for-range-identifier : for-range-initializer ) statement
  12296. // is equivalent to
  12297. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  12298. DeclSpec DS(Attrs.getPool().getFactory());
  12299. const char *PrevSpec;
  12300. unsigned DiagID;
  12301. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  12302. getPrintingPolicy());
  12303. Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::ForInit);
  12304. D.SetIdentifier(Ident, IdentLoc);
  12305. D.takeAttributes(Attrs);
  12306. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  12307. IdentLoc);
  12308. Decl *Var = ActOnDeclarator(S, D);
  12309. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  12310. FinalizeDeclaration(Var);
  12311. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  12312. Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
  12313. : IdentLoc);
  12314. }
  12315. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  12316. if (var->isInvalidDecl()) return;
  12317. MaybeAddCUDAConstantAttr(var);
  12318. if (getLangOpts().OpenCL) {
  12319. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  12320. // initialiser
  12321. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  12322. !var->hasInit()) {
  12323. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  12324. << 1 /*Init*/;
  12325. var->setInvalidDecl();
  12326. return;
  12327. }
  12328. }
  12329. // In Objective-C, don't allow jumps past the implicit initialization of a
  12330. // local retaining variable.
  12331. if (getLangOpts().ObjC &&
  12332. var->hasLocalStorage()) {
  12333. switch (var->getType().getObjCLifetime()) {
  12334. case Qualifiers::OCL_None:
  12335. case Qualifiers::OCL_ExplicitNone:
  12336. case Qualifiers::OCL_Autoreleasing:
  12337. break;
  12338. case Qualifiers::OCL_Weak:
  12339. case Qualifiers::OCL_Strong:
  12340. setFunctionHasBranchProtectedScope();
  12341. break;
  12342. }
  12343. }
  12344. if (var->hasLocalStorage() &&
  12345. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  12346. setFunctionHasBranchProtectedScope();
  12347. // Warn about externally-visible variables being defined without a
  12348. // prior declaration. We only want to do this for global
  12349. // declarations, but we also specifically need to avoid doing it for
  12350. // class members because the linkage of an anonymous class can
  12351. // change if it's later given a typedef name.
  12352. if (var->isThisDeclarationADefinition() &&
  12353. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  12354. var->isExternallyVisible() && var->hasLinkage() &&
  12355. !var->isInline() && !var->getDescribedVarTemplate() &&
  12356. !isa<VarTemplatePartialSpecializationDecl>(var) &&
  12357. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  12358. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  12359. var->getLocation())) {
  12360. // Find a previous declaration that's not a definition.
  12361. VarDecl *prev = var->getPreviousDecl();
  12362. while (prev && prev->isThisDeclarationADefinition())
  12363. prev = prev->getPreviousDecl();
  12364. if (!prev) {
  12365. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  12366. Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
  12367. << /* variable */ 0;
  12368. }
  12369. }
  12370. // Cache the result of checking for constant initialization.
  12371. std::optional<bool> CacheHasConstInit;
  12372. const Expr *CacheCulprit = nullptr;
  12373. auto checkConstInit = [&]() mutable {
  12374. if (!CacheHasConstInit)
  12375. CacheHasConstInit = var->getInit()->isConstantInitializer(
  12376. Context, var->getType()->isReferenceType(), &CacheCulprit);
  12377. return *CacheHasConstInit;
  12378. };
  12379. if (var->getTLSKind() == VarDecl::TLS_Static) {
  12380. if (var->getType().isDestructedType()) {
  12381. // GNU C++98 edits for __thread, [basic.start.term]p3:
  12382. // The type of an object with thread storage duration shall not
  12383. // have a non-trivial destructor.
  12384. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  12385. if (getLangOpts().CPlusPlus11)
  12386. Diag(var->getLocation(), diag::note_use_thread_local);
  12387. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  12388. if (!checkConstInit()) {
  12389. // GNU C++98 edits for __thread, [basic.start.init]p4:
  12390. // An object of thread storage duration shall not require dynamic
  12391. // initialization.
  12392. // FIXME: Need strict checking here.
  12393. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  12394. << CacheCulprit->getSourceRange();
  12395. if (getLangOpts().CPlusPlus11)
  12396. Diag(var->getLocation(), diag::note_use_thread_local);
  12397. }
  12398. }
  12399. }
  12400. if (!var->getType()->isStructureType() && var->hasInit() &&
  12401. isa<InitListExpr>(var->getInit())) {
  12402. const auto *ILE = cast<InitListExpr>(var->getInit());
  12403. unsigned NumInits = ILE->getNumInits();
  12404. if (NumInits > 2)
  12405. for (unsigned I = 0; I < NumInits; ++I) {
  12406. const auto *Init = ILE->getInit(I);
  12407. if (!Init)
  12408. break;
  12409. const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
  12410. if (!SL)
  12411. break;
  12412. unsigned NumConcat = SL->getNumConcatenated();
  12413. // Diagnose missing comma in string array initialization.
  12414. // Do not warn when all the elements in the initializer are concatenated
  12415. // together. Do not warn for macros too.
  12416. if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
  12417. bool OnlyOneMissingComma = true;
  12418. for (unsigned J = I + 1; J < NumInits; ++J) {
  12419. const auto *Init = ILE->getInit(J);
  12420. if (!Init)
  12421. break;
  12422. const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
  12423. if (!SLJ || SLJ->getNumConcatenated() > 1) {
  12424. OnlyOneMissingComma = false;
  12425. break;
  12426. }
  12427. }
  12428. if (OnlyOneMissingComma) {
  12429. SmallVector<FixItHint, 1> Hints;
  12430. for (unsigned i = 0; i < NumConcat - 1; ++i)
  12431. Hints.push_back(FixItHint::CreateInsertion(
  12432. PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
  12433. Diag(SL->getStrTokenLoc(1),
  12434. diag::warn_concatenated_literal_array_init)
  12435. << Hints;
  12436. Diag(SL->getBeginLoc(),
  12437. diag::note_concatenated_string_literal_silence);
  12438. }
  12439. // In any case, stop now.
  12440. break;
  12441. }
  12442. }
  12443. }
  12444. QualType type = var->getType();
  12445. if (var->hasAttr<BlocksAttr>())
  12446. getCurFunction()->addByrefBlockVar(var);
  12447. Expr *Init = var->getInit();
  12448. bool GlobalStorage = var->hasGlobalStorage();
  12449. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  12450. QualType baseType = Context.getBaseElementType(type);
  12451. bool HasConstInit = true;
  12452. // Check whether the initializer is sufficiently constant.
  12453. if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
  12454. !Init->isValueDependent() &&
  12455. (GlobalStorage || var->isConstexpr() ||
  12456. var->mightBeUsableInConstantExpressions(Context))) {
  12457. // If this variable might have a constant initializer or might be usable in
  12458. // constant expressions, check whether or not it actually is now. We can't
  12459. // do this lazily, because the result might depend on things that change
  12460. // later, such as which constexpr functions happen to be defined.
  12461. SmallVector<PartialDiagnosticAt, 8> Notes;
  12462. if (!getLangOpts().CPlusPlus11) {
  12463. // Prior to C++11, in contexts where a constant initializer is required,
  12464. // the set of valid constant initializers is described by syntactic rules
  12465. // in [expr.const]p2-6.
  12466. // FIXME: Stricter checking for these rules would be useful for constinit /
  12467. // -Wglobal-constructors.
  12468. HasConstInit = checkConstInit();
  12469. // Compute and cache the constant value, and remember that we have a
  12470. // constant initializer.
  12471. if (HasConstInit) {
  12472. (void)var->checkForConstantInitialization(Notes);
  12473. Notes.clear();
  12474. } else if (CacheCulprit) {
  12475. Notes.emplace_back(CacheCulprit->getExprLoc(),
  12476. PDiag(diag::note_invalid_subexpr_in_const_expr));
  12477. Notes.back().second << CacheCulprit->getSourceRange();
  12478. }
  12479. } else {
  12480. // Evaluate the initializer to see if it's a constant initializer.
  12481. HasConstInit = var->checkForConstantInitialization(Notes);
  12482. }
  12483. if (HasConstInit) {
  12484. // FIXME: Consider replacing the initializer with a ConstantExpr.
  12485. } else if (var->isConstexpr()) {
  12486. SourceLocation DiagLoc = var->getLocation();
  12487. // If the note doesn't add any useful information other than a source
  12488. // location, fold it into the primary diagnostic.
  12489. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  12490. diag::note_invalid_subexpr_in_const_expr) {
  12491. DiagLoc = Notes[0].first;
  12492. Notes.clear();
  12493. }
  12494. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  12495. << var << Init->getSourceRange();
  12496. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  12497. Diag(Notes[I].first, Notes[I].second);
  12498. } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
  12499. auto *Attr = var->getAttr<ConstInitAttr>();
  12500. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  12501. << Init->getSourceRange();
  12502. Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
  12503. << Attr->getRange() << Attr->isConstinit();
  12504. for (auto &it : Notes)
  12505. Diag(it.first, it.second);
  12506. } else if (IsGlobal &&
  12507. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  12508. var->getLocation())) {
  12509. // Warn about globals which don't have a constant initializer. Don't
  12510. // warn about globals with a non-trivial destructor because we already
  12511. // warned about them.
  12512. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  12513. if (!(RD && !RD->hasTrivialDestructor())) {
  12514. // checkConstInit() here permits trivial default initialization even in
  12515. // C++11 onwards, where such an initializer is not a constant initializer
  12516. // but nonetheless doesn't require a global constructor.
  12517. if (!checkConstInit())
  12518. Diag(var->getLocation(), diag::warn_global_constructor)
  12519. << Init->getSourceRange();
  12520. }
  12521. }
  12522. }
  12523. // Apply section attributes and pragmas to global variables.
  12524. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  12525. !inTemplateInstantiation()) {
  12526. PragmaStack<StringLiteral *> *Stack = nullptr;
  12527. int SectionFlags = ASTContext::PSF_Read;
  12528. if (var->getType().isConstQualified()) {
  12529. if (HasConstInit)
  12530. Stack = &ConstSegStack;
  12531. else {
  12532. Stack = &BSSSegStack;
  12533. SectionFlags |= ASTContext::PSF_Write;
  12534. }
  12535. } else if (var->hasInit() && HasConstInit) {
  12536. Stack = &DataSegStack;
  12537. SectionFlags |= ASTContext::PSF_Write;
  12538. } else {
  12539. Stack = &BSSSegStack;
  12540. SectionFlags |= ASTContext::PSF_Write;
  12541. }
  12542. if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
  12543. if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
  12544. SectionFlags |= ASTContext::PSF_Implicit;
  12545. UnifySection(SA->getName(), SectionFlags, var);
  12546. } else if (Stack->CurrentValue) {
  12547. SectionFlags |= ASTContext::PSF_Implicit;
  12548. auto SectionName = Stack->CurrentValue->getString();
  12549. var->addAttr(SectionAttr::CreateImplicit(
  12550. Context, SectionName, Stack->CurrentPragmaLocation,
  12551. AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
  12552. if (UnifySection(SectionName, SectionFlags, var))
  12553. var->dropAttr<SectionAttr>();
  12554. }
  12555. // Apply the init_seg attribute if this has an initializer. If the
  12556. // initializer turns out to not be dynamic, we'll end up ignoring this
  12557. // attribute.
  12558. if (CurInitSeg && var->getInit())
  12559. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  12560. CurInitSegLoc,
  12561. AttributeCommonInfo::AS_Pragma));
  12562. }
  12563. // All the following checks are C++ only.
  12564. if (!getLangOpts().CPlusPlus) {
  12565. // If this variable must be emitted, add it as an initializer for the
  12566. // current module.
  12567. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  12568. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  12569. return;
  12570. }
  12571. // Require the destructor.
  12572. if (!type->isDependentType())
  12573. if (const RecordType *recordType = baseType->getAs<RecordType>())
  12574. FinalizeVarWithDestructor(var, recordType);
  12575. // If this variable must be emitted, add it as an initializer for the current
  12576. // module.
  12577. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  12578. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  12579. // Build the bindings if this is a structured binding declaration.
  12580. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  12581. CheckCompleteDecompositionDeclaration(DD);
  12582. }
  12583. /// Check if VD needs to be dllexport/dllimport due to being in a
  12584. /// dllexport/import function.
  12585. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  12586. assert(VD->isStaticLocal());
  12587. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  12588. // Find outermost function when VD is in lambda function.
  12589. while (FD && !getDLLAttr(FD) &&
  12590. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  12591. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  12592. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  12593. }
  12594. if (!FD)
  12595. return;
  12596. // Static locals inherit dll attributes from their function.
  12597. if (Attr *A = getDLLAttr(FD)) {
  12598. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  12599. NewAttr->setInherited(true);
  12600. VD->addAttr(NewAttr);
  12601. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  12602. auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
  12603. NewAttr->setInherited(true);
  12604. VD->addAttr(NewAttr);
  12605. // Export this function to enforce exporting this static variable even
  12606. // if it is not used in this compilation unit.
  12607. if (!FD->hasAttr<DLLExportAttr>())
  12608. FD->addAttr(NewAttr);
  12609. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  12610. auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
  12611. NewAttr->setInherited(true);
  12612. VD->addAttr(NewAttr);
  12613. }
  12614. }
  12615. void Sema::CheckThreadLocalForLargeAlignment(VarDecl *VD) {
  12616. assert(VD->getTLSKind());
  12617. // Perform TLS alignment check here after attributes attached to the variable
  12618. // which may affect the alignment have been processed. Only perform the check
  12619. // if the target has a maximum TLS alignment (zero means no constraints).
  12620. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  12621. // Protect the check so that it's not performed on dependent types and
  12622. // dependent alignments (we can't determine the alignment in that case).
  12623. if (!VD->hasDependentAlignment()) {
  12624. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  12625. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  12626. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  12627. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  12628. << (unsigned)MaxAlignChars.getQuantity();
  12629. }
  12630. }
  12631. }
  12632. }
  12633. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  12634. /// any semantic actions necessary after any initializer has been attached.
  12635. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  12636. // Note that we are no longer parsing the initializer for this declaration.
  12637. ParsingInitForAutoVars.erase(ThisDecl);
  12638. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  12639. if (!VD)
  12640. return;
  12641. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  12642. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  12643. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  12644. if (PragmaClangBSSSection.Valid)
  12645. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
  12646. Context, PragmaClangBSSSection.SectionName,
  12647. PragmaClangBSSSection.PragmaLocation,
  12648. AttributeCommonInfo::AS_Pragma));
  12649. if (PragmaClangDataSection.Valid)
  12650. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
  12651. Context, PragmaClangDataSection.SectionName,
  12652. PragmaClangDataSection.PragmaLocation,
  12653. AttributeCommonInfo::AS_Pragma));
  12654. if (PragmaClangRodataSection.Valid)
  12655. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
  12656. Context, PragmaClangRodataSection.SectionName,
  12657. PragmaClangRodataSection.PragmaLocation,
  12658. AttributeCommonInfo::AS_Pragma));
  12659. if (PragmaClangRelroSection.Valid)
  12660. VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
  12661. Context, PragmaClangRelroSection.SectionName,
  12662. PragmaClangRelroSection.PragmaLocation,
  12663. AttributeCommonInfo::AS_Pragma));
  12664. }
  12665. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  12666. for (auto *BD : DD->bindings()) {
  12667. FinalizeDeclaration(BD);
  12668. }
  12669. }
  12670. checkAttributesAfterMerging(*this, *VD);
  12671. if (VD->isStaticLocal())
  12672. CheckStaticLocalForDllExport(VD);
  12673. if (VD->getTLSKind())
  12674. CheckThreadLocalForLargeAlignment(VD);
  12675. // Perform check for initializers of device-side global variables.
  12676. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  12677. // 7.5). We must also apply the same checks to all __shared__
  12678. // variables whether they are local or not. CUDA also allows
  12679. // constant initializers for __constant__ and __device__ variables.
  12680. if (getLangOpts().CUDA)
  12681. checkAllowedCUDAInitializer(VD);
  12682. // Grab the dllimport or dllexport attribute off of the VarDecl.
  12683. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  12684. // Imported static data members cannot be defined out-of-line.
  12685. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  12686. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  12687. VD->isThisDeclarationADefinition()) {
  12688. // We allow definitions of dllimport class template static data members
  12689. // with a warning.
  12690. CXXRecordDecl *Context =
  12691. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  12692. bool IsClassTemplateMember =
  12693. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  12694. Context->getDescribedClassTemplate();
  12695. Diag(VD->getLocation(),
  12696. IsClassTemplateMember
  12697. ? diag::warn_attribute_dllimport_static_field_definition
  12698. : diag::err_attribute_dllimport_static_field_definition);
  12699. Diag(IA->getLocation(), diag::note_attribute);
  12700. if (!IsClassTemplateMember)
  12701. VD->setInvalidDecl();
  12702. }
  12703. }
  12704. // dllimport/dllexport variables cannot be thread local, their TLS index
  12705. // isn't exported with the variable.
  12706. if (DLLAttr && VD->getTLSKind()) {
  12707. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  12708. if (F && getDLLAttr(F)) {
  12709. assert(VD->isStaticLocal());
  12710. // But if this is a static local in a dlimport/dllexport function, the
  12711. // function will never be inlined, which means the var would never be
  12712. // imported, so having it marked import/export is safe.
  12713. } else {
  12714. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  12715. << DLLAttr;
  12716. VD->setInvalidDecl();
  12717. }
  12718. }
  12719. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  12720. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  12721. Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
  12722. << Attr;
  12723. VD->dropAttr<UsedAttr>();
  12724. }
  12725. }
  12726. if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
  12727. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  12728. Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
  12729. << Attr;
  12730. VD->dropAttr<RetainAttr>();
  12731. }
  12732. }
  12733. const DeclContext *DC = VD->getDeclContext();
  12734. // If there's a #pragma GCC visibility in scope, and this isn't a class
  12735. // member, set the visibility of this variable.
  12736. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  12737. AddPushedVisibilityAttribute(VD);
  12738. // FIXME: Warn on unused var template partial specializations.
  12739. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  12740. MarkUnusedFileScopedDecl(VD);
  12741. // Now we have parsed the initializer and can update the table of magic
  12742. // tag values.
  12743. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  12744. !VD->getType()->isIntegralOrEnumerationType())
  12745. return;
  12746. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  12747. const Expr *MagicValueExpr = VD->getInit();
  12748. if (!MagicValueExpr) {
  12749. continue;
  12750. }
  12751. std::optional<llvm::APSInt> MagicValueInt;
  12752. if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
  12753. Diag(I->getRange().getBegin(),
  12754. diag::err_type_tag_for_datatype_not_ice)
  12755. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  12756. continue;
  12757. }
  12758. if (MagicValueInt->getActiveBits() > 64) {
  12759. Diag(I->getRange().getBegin(),
  12760. diag::err_type_tag_for_datatype_too_large)
  12761. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  12762. continue;
  12763. }
  12764. uint64_t MagicValue = MagicValueInt->getZExtValue();
  12765. RegisterTypeTagForDatatype(I->getArgumentKind(),
  12766. MagicValue,
  12767. I->getMatchingCType(),
  12768. I->getLayoutCompatible(),
  12769. I->getMustBeNull());
  12770. }
  12771. }
  12772. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  12773. auto *VD = dyn_cast<VarDecl>(DD);
  12774. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  12775. }
  12776. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  12777. ArrayRef<Decl *> Group) {
  12778. SmallVector<Decl*, 8> Decls;
  12779. if (DS.isTypeSpecOwned())
  12780. Decls.push_back(DS.getRepAsDecl());
  12781. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  12782. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  12783. bool DiagnosedMultipleDecomps = false;
  12784. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  12785. bool DiagnosedNonDeducedAuto = false;
  12786. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  12787. if (Decl *D = Group[i]) {
  12788. // For declarators, there are some additional syntactic-ish checks we need
  12789. // to perform.
  12790. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  12791. if (!FirstDeclaratorInGroup)
  12792. FirstDeclaratorInGroup = DD;
  12793. if (!FirstDecompDeclaratorInGroup)
  12794. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  12795. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  12796. !hasDeducedAuto(DD))
  12797. FirstNonDeducedAutoInGroup = DD;
  12798. if (FirstDeclaratorInGroup != DD) {
  12799. // A decomposition declaration cannot be combined with any other
  12800. // declaration in the same group.
  12801. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  12802. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  12803. diag::err_decomp_decl_not_alone)
  12804. << FirstDeclaratorInGroup->getSourceRange()
  12805. << DD->getSourceRange();
  12806. DiagnosedMultipleDecomps = true;
  12807. }
  12808. // A declarator that uses 'auto' in any way other than to declare a
  12809. // variable with a deduced type cannot be combined with any other
  12810. // declarator in the same group.
  12811. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  12812. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  12813. diag::err_auto_non_deduced_not_alone)
  12814. << FirstNonDeducedAutoInGroup->getType()
  12815. ->hasAutoForTrailingReturnType()
  12816. << FirstDeclaratorInGroup->getSourceRange()
  12817. << DD->getSourceRange();
  12818. DiagnosedNonDeducedAuto = true;
  12819. }
  12820. }
  12821. }
  12822. Decls.push_back(D);
  12823. }
  12824. }
  12825. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  12826. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  12827. handleTagNumbering(Tag, S);
  12828. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  12829. getLangOpts().CPlusPlus)
  12830. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  12831. }
  12832. }
  12833. return BuildDeclaratorGroup(Decls);
  12834. }
  12835. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  12836. /// group, performing any necessary semantic checking.
  12837. Sema::DeclGroupPtrTy
  12838. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  12839. // C++14 [dcl.spec.auto]p7: (DR1347)
  12840. // If the type that replaces the placeholder type is not the same in each
  12841. // deduction, the program is ill-formed.
  12842. if (Group.size() > 1) {
  12843. QualType Deduced;
  12844. VarDecl *DeducedDecl = nullptr;
  12845. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  12846. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  12847. if (!D || D->isInvalidDecl())
  12848. break;
  12849. DeducedType *DT = D->getType()->getContainedDeducedType();
  12850. if (!DT || DT->getDeducedType().isNull())
  12851. continue;
  12852. if (Deduced.isNull()) {
  12853. Deduced = DT->getDeducedType();
  12854. DeducedDecl = D;
  12855. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  12856. auto *AT = dyn_cast<AutoType>(DT);
  12857. auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  12858. diag::err_auto_different_deductions)
  12859. << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
  12860. << DeducedDecl->getDeclName() << DT->getDeducedType()
  12861. << D->getDeclName();
  12862. if (DeducedDecl->hasInit())
  12863. Dia << DeducedDecl->getInit()->getSourceRange();
  12864. if (D->getInit())
  12865. Dia << D->getInit()->getSourceRange();
  12866. D->setInvalidDecl();
  12867. break;
  12868. }
  12869. }
  12870. }
  12871. ActOnDocumentableDecls(Group);
  12872. return DeclGroupPtrTy::make(
  12873. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  12874. }
  12875. void Sema::ActOnDocumentableDecl(Decl *D) {
  12876. ActOnDocumentableDecls(D);
  12877. }
  12878. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  12879. // Don't parse the comment if Doxygen diagnostics are ignored.
  12880. if (Group.empty() || !Group[0])
  12881. return;
  12882. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  12883. Group[0]->getLocation()) &&
  12884. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  12885. Group[0]->getLocation()))
  12886. return;
  12887. if (Group.size() >= 2) {
  12888. // This is a decl group. Normally it will contain only declarations
  12889. // produced from declarator list. But in case we have any definitions or
  12890. // additional declaration references:
  12891. // 'typedef struct S {} S;'
  12892. // 'typedef struct S *S;'
  12893. // 'struct S *pS;'
  12894. // FinalizeDeclaratorGroup adds these as separate declarations.
  12895. Decl *MaybeTagDecl = Group[0];
  12896. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  12897. Group = Group.slice(1);
  12898. }
  12899. }
  12900. // FIMXE: We assume every Decl in the group is in the same file.
  12901. // This is false when preprocessor constructs the group from decls in
  12902. // different files (e. g. macros or #include).
  12903. Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
  12904. }
  12905. /// Common checks for a parameter-declaration that should apply to both function
  12906. /// parameters and non-type template parameters.
  12907. void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
  12908. // Check that there are no default arguments inside the type of this
  12909. // parameter.
  12910. if (getLangOpts().CPlusPlus)
  12911. CheckExtraCXXDefaultArguments(D);
  12912. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  12913. if (D.getCXXScopeSpec().isSet()) {
  12914. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  12915. << D.getCXXScopeSpec().getRange();
  12916. }
  12917. // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
  12918. // simple identifier except [...irrelevant cases...].
  12919. switch (D.getName().getKind()) {
  12920. case UnqualifiedIdKind::IK_Identifier:
  12921. break;
  12922. case UnqualifiedIdKind::IK_OperatorFunctionId:
  12923. case UnqualifiedIdKind::IK_ConversionFunctionId:
  12924. case UnqualifiedIdKind::IK_LiteralOperatorId:
  12925. case UnqualifiedIdKind::IK_ConstructorName:
  12926. case UnqualifiedIdKind::IK_DestructorName:
  12927. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  12928. case UnqualifiedIdKind::IK_DeductionGuideName:
  12929. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  12930. << GetNameForDeclarator(D).getName();
  12931. break;
  12932. case UnqualifiedIdKind::IK_TemplateId:
  12933. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  12934. // GetNameForDeclarator would not produce a useful name in this case.
  12935. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
  12936. break;
  12937. }
  12938. }
  12939. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  12940. /// to introduce parameters into function prototype scope.
  12941. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  12942. const DeclSpec &DS = D.getDeclSpec();
  12943. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  12944. // C++03 [dcl.stc]p2 also permits 'auto'.
  12945. StorageClass SC = SC_None;
  12946. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  12947. SC = SC_Register;
  12948. // In C++11, the 'register' storage class specifier is deprecated.
  12949. // In C++17, it is not allowed, but we tolerate it as an extension.
  12950. if (getLangOpts().CPlusPlus11) {
  12951. Diag(DS.getStorageClassSpecLoc(),
  12952. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  12953. : diag::warn_deprecated_register)
  12954. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  12955. }
  12956. } else if (getLangOpts().CPlusPlus &&
  12957. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  12958. SC = SC_Auto;
  12959. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  12960. Diag(DS.getStorageClassSpecLoc(),
  12961. diag::err_invalid_storage_class_in_func_decl);
  12962. D.getMutableDeclSpec().ClearStorageClassSpecs();
  12963. }
  12964. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  12965. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  12966. << DeclSpec::getSpecifierName(TSCS);
  12967. if (DS.isInlineSpecified())
  12968. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  12969. << getLangOpts().CPlusPlus17;
  12970. if (DS.hasConstexprSpecifier())
  12971. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  12972. << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
  12973. DiagnoseFunctionSpecifiers(DS);
  12974. CheckFunctionOrTemplateParamDeclarator(S, D);
  12975. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  12976. QualType parmDeclType = TInfo->getType();
  12977. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  12978. IdentifierInfo *II = D.getIdentifier();
  12979. if (II) {
  12980. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  12981. ForVisibleRedeclaration);
  12982. LookupName(R, S);
  12983. if (R.isSingleResult()) {
  12984. NamedDecl *PrevDecl = R.getFoundDecl();
  12985. if (PrevDecl->isTemplateParameter()) {
  12986. // Maybe we will complain about the shadowed template parameter.
  12987. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  12988. // Just pretend that we didn't see the previous declaration.
  12989. PrevDecl = nullptr;
  12990. } else if (S->isDeclScope(PrevDecl)) {
  12991. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  12992. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  12993. // Recover by removing the name
  12994. II = nullptr;
  12995. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  12996. D.setInvalidType(true);
  12997. }
  12998. }
  12999. }
  13000. // Temporarily put parameter variables in the translation unit, not
  13001. // the enclosing context. This prevents them from accidentally
  13002. // looking like class members in C++.
  13003. ParmVarDecl *New =
  13004. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  13005. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  13006. if (D.isInvalidType())
  13007. New->setInvalidDecl();
  13008. assert(S->isFunctionPrototypeScope());
  13009. assert(S->getFunctionPrototypeDepth() >= 1);
  13010. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  13011. S->getNextFunctionPrototypeIndex());
  13012. // Add the parameter declaration into this scope.
  13013. S->AddDecl(New);
  13014. if (II)
  13015. IdResolver.AddDecl(New);
  13016. ProcessDeclAttributes(S, New, D);
  13017. if (D.getDeclSpec().isModulePrivateSpecified())
  13018. Diag(New->getLocation(), diag::err_module_private_local)
  13019. << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  13020. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  13021. if (New->hasAttr<BlocksAttr>()) {
  13022. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  13023. }
  13024. if (getLangOpts().OpenCL)
  13025. deduceOpenCLAddressSpace(New);
  13026. return New;
  13027. }
  13028. /// Synthesizes a variable for a parameter arising from a
  13029. /// typedef.
  13030. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  13031. SourceLocation Loc,
  13032. QualType T) {
  13033. /* FIXME: setting StartLoc == Loc.
  13034. Would it be worth to modify callers so as to provide proper source
  13035. location for the unnamed parameters, embedding the parameter's type? */
  13036. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  13037. T, Context.getTrivialTypeSourceInfo(T, Loc),
  13038. SC_None, nullptr);
  13039. Param->setImplicit();
  13040. return Param;
  13041. }
  13042. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  13043. // Don't diagnose unused-parameter errors in template instantiations; we
  13044. // will already have done so in the template itself.
  13045. if (inTemplateInstantiation())
  13046. return;
  13047. for (const ParmVarDecl *Parameter : Parameters) {
  13048. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  13049. !Parameter->hasAttr<UnusedAttr>()) {
  13050. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  13051. << Parameter->getDeclName();
  13052. }
  13053. }
  13054. }
  13055. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  13056. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  13057. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  13058. return;
  13059. // Warn if the return value is pass-by-value and larger than the specified
  13060. // threshold.
  13061. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  13062. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  13063. if (Size > LangOpts.NumLargeByValueCopy)
  13064. Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
  13065. }
  13066. // Warn if any parameter is pass-by-value and larger than the specified
  13067. // threshold.
  13068. for (const ParmVarDecl *Parameter : Parameters) {
  13069. QualType T = Parameter->getType();
  13070. if (T->isDependentType() || !T.isPODType(Context))
  13071. continue;
  13072. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  13073. if (Size > LangOpts.NumLargeByValueCopy)
  13074. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  13075. << Parameter << Size;
  13076. }
  13077. }
  13078. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  13079. SourceLocation NameLoc, IdentifierInfo *Name,
  13080. QualType T, TypeSourceInfo *TSInfo,
  13081. StorageClass SC) {
  13082. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  13083. if (getLangOpts().ObjCAutoRefCount &&
  13084. T.getObjCLifetime() == Qualifiers::OCL_None &&
  13085. T->isObjCLifetimeType()) {
  13086. Qualifiers::ObjCLifetime lifetime;
  13087. // Special cases for arrays:
  13088. // - if it's const, use __unsafe_unretained
  13089. // - otherwise, it's an error
  13090. if (T->isArrayType()) {
  13091. if (!T.isConstQualified()) {
  13092. if (DelayedDiagnostics.shouldDelayDiagnostics())
  13093. DelayedDiagnostics.add(
  13094. sema::DelayedDiagnostic::makeForbiddenType(
  13095. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  13096. else
  13097. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  13098. << TSInfo->getTypeLoc().getSourceRange();
  13099. }
  13100. lifetime = Qualifiers::OCL_ExplicitNone;
  13101. } else {
  13102. lifetime = T->getObjCARCImplicitLifetime();
  13103. }
  13104. T = Context.getLifetimeQualifiedType(T, lifetime);
  13105. }
  13106. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  13107. Context.getAdjustedParameterType(T),
  13108. TSInfo, SC, nullptr);
  13109. // Make a note if we created a new pack in the scope of a lambda, so that
  13110. // we know that references to that pack must also be expanded within the
  13111. // lambda scope.
  13112. if (New->isParameterPack())
  13113. if (auto *LSI = getEnclosingLambda())
  13114. LSI->LocalPacks.push_back(New);
  13115. if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
  13116. New->getType().hasNonTrivialToPrimitiveCopyCUnion())
  13117. checkNonTrivialCUnion(New->getType(), New->getLocation(),
  13118. NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
  13119. // Parameters can not be abstract class types.
  13120. // For record types, this is done by the AbstractClassUsageDiagnoser once
  13121. // the class has been completely parsed.
  13122. if (!CurContext->isRecord() &&
  13123. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  13124. AbstractParamType))
  13125. New->setInvalidDecl();
  13126. // Parameter declarators cannot be interface types. All ObjC objects are
  13127. // passed by reference.
  13128. if (T->isObjCObjectType()) {
  13129. SourceLocation TypeEndLoc =
  13130. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  13131. Diag(NameLoc,
  13132. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  13133. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  13134. T = Context.getObjCObjectPointerType(T);
  13135. New->setType(T);
  13136. }
  13137. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  13138. // duration shall not be qualified by an address-space qualifier."
  13139. // Since all parameters have automatic store duration, they can not have
  13140. // an address space.
  13141. if (T.getAddressSpace() != LangAS::Default &&
  13142. // OpenCL allows function arguments declared to be an array of a type
  13143. // to be qualified with an address space.
  13144. !(getLangOpts().OpenCL &&
  13145. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  13146. Diag(NameLoc, diag::err_arg_with_address_space);
  13147. New->setInvalidDecl();
  13148. }
  13149. // PPC MMA non-pointer types are not allowed as function argument types.
  13150. if (Context.getTargetInfo().getTriple().isPPC64() &&
  13151. CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
  13152. New->setInvalidDecl();
  13153. }
  13154. return New;
  13155. }
  13156. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  13157. SourceLocation LocAfterDecls) {
  13158. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  13159. // C99 6.9.1p6 "If a declarator includes an identifier list, each declaration
  13160. // in the declaration list shall have at least one declarator, those
  13161. // declarators shall only declare identifiers from the identifier list, and
  13162. // every identifier in the identifier list shall be declared.
  13163. //
  13164. // C89 3.7.1p5 "If a declarator includes an identifier list, only the
  13165. // identifiers it names shall be declared in the declaration list."
  13166. //
  13167. // This is why we only diagnose in C99 and later. Note, the other conditions
  13168. // listed are checked elsewhere.
  13169. if (!FTI.hasPrototype) {
  13170. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  13171. --i;
  13172. if (FTI.Params[i].Param == nullptr) {
  13173. if (getLangOpts().C99) {
  13174. SmallString<256> Code;
  13175. llvm::raw_svector_ostream(Code)
  13176. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  13177. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  13178. << FTI.Params[i].Ident
  13179. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  13180. }
  13181. // Implicitly declare the argument as type 'int' for lack of a better
  13182. // type.
  13183. AttributeFactory attrs;
  13184. DeclSpec DS(attrs);
  13185. const char* PrevSpec; // unused
  13186. unsigned DiagID; // unused
  13187. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  13188. DiagID, Context.getPrintingPolicy());
  13189. // Use the identifier location for the type source range.
  13190. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  13191. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  13192. Declarator ParamD(DS, ParsedAttributesView::none(),
  13193. DeclaratorContext::KNRTypeList);
  13194. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  13195. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  13196. }
  13197. }
  13198. }
  13199. }
  13200. Decl *
  13201. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  13202. MultiTemplateParamsArg TemplateParameterLists,
  13203. SkipBodyInfo *SkipBody, FnBodyKind BodyKind) {
  13204. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  13205. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  13206. Scope *ParentScope = FnBodyScope->getParent();
  13207. // Check if we are in an `omp begin/end declare variant` scope. If we are, and
  13208. // we define a non-templated function definition, we will create a declaration
  13209. // instead (=BaseFD), and emit the definition with a mangled name afterwards.
  13210. // The base function declaration will have the equivalent of an `omp declare
  13211. // variant` annotation which specifies the mangled definition as a
  13212. // specialization function under the OpenMP context defined as part of the
  13213. // `omp begin declare variant`.
  13214. SmallVector<FunctionDecl *, 4> Bases;
  13215. if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
  13216. ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
  13217. ParentScope, D, TemplateParameterLists, Bases);
  13218. D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
  13219. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  13220. Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind);
  13221. if (!Bases.empty())
  13222. ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
  13223. return Dcl;
  13224. }
  13225. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  13226. Consumer.HandleInlineFunctionDefinition(D);
  13227. }
  13228. static bool FindPossiblePrototype(const FunctionDecl *FD,
  13229. const FunctionDecl *&PossiblePrototype) {
  13230. for (const FunctionDecl *Prev = FD->getPreviousDecl(); Prev;
  13231. Prev = Prev->getPreviousDecl()) {
  13232. // Ignore any declarations that occur in function or method
  13233. // scope, because they aren't visible from the header.
  13234. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  13235. continue;
  13236. PossiblePrototype = Prev;
  13237. return Prev->getType()->isFunctionProtoType();
  13238. }
  13239. return false;
  13240. }
  13241. static bool
  13242. ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  13243. const FunctionDecl *&PossiblePrototype) {
  13244. // Don't warn about invalid declarations.
  13245. if (FD->isInvalidDecl())
  13246. return false;
  13247. // Or declarations that aren't global.
  13248. if (!FD->isGlobal())
  13249. return false;
  13250. // Don't warn about C++ member functions.
  13251. if (isa<CXXMethodDecl>(FD))
  13252. return false;
  13253. // Don't warn about 'main'.
  13254. if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
  13255. if (IdentifierInfo *II = FD->getIdentifier())
  13256. if (II->isStr("main") || II->isStr("efi_main"))
  13257. return false;
  13258. // Don't warn about inline functions.
  13259. if (FD->isInlined())
  13260. return false;
  13261. // Don't warn about function templates.
  13262. if (FD->getDescribedFunctionTemplate())
  13263. return false;
  13264. // Don't warn about function template specializations.
  13265. if (FD->isFunctionTemplateSpecialization())
  13266. return false;
  13267. // Don't warn for OpenCL kernels.
  13268. if (FD->hasAttr<OpenCLKernelAttr>())
  13269. return false;
  13270. // Don't warn on explicitly deleted functions.
  13271. if (FD->isDeleted())
  13272. return false;
  13273. // Don't warn on implicitly local functions (such as having local-typed
  13274. // parameters).
  13275. if (!FD->isExternallyVisible())
  13276. return false;
  13277. // If we were able to find a potential prototype, don't warn.
  13278. if (FindPossiblePrototype(FD, PossiblePrototype))
  13279. return false;
  13280. return true;
  13281. }
  13282. void
  13283. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  13284. const FunctionDecl *EffectiveDefinition,
  13285. SkipBodyInfo *SkipBody) {
  13286. const FunctionDecl *Definition = EffectiveDefinition;
  13287. if (!Definition &&
  13288. !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
  13289. return;
  13290. if (Definition->getFriendObjectKind() != Decl::FOK_None) {
  13291. if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
  13292. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  13293. // A merged copy of the same function, instantiated as a member of
  13294. // the same class, is OK.
  13295. if (declaresSameEntity(OrigFD, OrigDef) &&
  13296. declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
  13297. cast<Decl>(FD->getLexicalDeclContext())))
  13298. return;
  13299. }
  13300. }
  13301. }
  13302. if (canRedefineFunction(Definition, getLangOpts()))
  13303. return;
  13304. // Don't emit an error when this is redefinition of a typo-corrected
  13305. // definition.
  13306. if (TypoCorrectedFunctionDefinitions.count(Definition))
  13307. return;
  13308. // If we don't have a visible definition of the function, and it's inline or
  13309. // a template, skip the new definition.
  13310. if (SkipBody && !hasVisibleDefinition(Definition) &&
  13311. (Definition->getFormalLinkage() == InternalLinkage ||
  13312. Definition->isInlined() ||
  13313. Definition->getDescribedFunctionTemplate() ||
  13314. Definition->getNumTemplateParameterLists())) {
  13315. SkipBody->ShouldSkip = true;
  13316. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  13317. if (auto *TD = Definition->getDescribedFunctionTemplate())
  13318. makeMergedDefinitionVisible(TD);
  13319. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  13320. return;
  13321. }
  13322. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  13323. Definition->getStorageClass() == SC_Extern)
  13324. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  13325. << FD << getLangOpts().CPlusPlus;
  13326. else
  13327. Diag(FD->getLocation(), diag::err_redefinition) << FD;
  13328. Diag(Definition->getLocation(), diag::note_previous_definition);
  13329. FD->setInvalidDecl();
  13330. }
  13331. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  13332. Sema &S) {
  13333. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  13334. LambdaScopeInfo *LSI = S.PushLambdaScope();
  13335. LSI->CallOperator = CallOperator;
  13336. LSI->Lambda = LambdaClass;
  13337. LSI->ReturnType = CallOperator->getReturnType();
  13338. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  13339. if (LCD == LCD_None)
  13340. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  13341. else if (LCD == LCD_ByCopy)
  13342. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  13343. else if (LCD == LCD_ByRef)
  13344. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  13345. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  13346. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  13347. LSI->Mutable = !CallOperator->isConst();
  13348. // Add the captures to the LSI so they can be noted as already
  13349. // captured within tryCaptureVar.
  13350. auto I = LambdaClass->field_begin();
  13351. for (const auto &C : LambdaClass->captures()) {
  13352. if (C.capturesVariable()) {
  13353. ValueDecl *VD = C.getCapturedVar();
  13354. if (VD->isInitCapture())
  13355. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  13356. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  13357. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  13358. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  13359. /*EllipsisLoc*/C.isPackExpansion()
  13360. ? C.getEllipsisLoc() : SourceLocation(),
  13361. I->getType(), /*Invalid*/false);
  13362. } else if (C.capturesThis()) {
  13363. LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
  13364. C.getCaptureKind() == LCK_StarThis);
  13365. } else {
  13366. LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
  13367. I->getType());
  13368. }
  13369. ++I;
  13370. }
  13371. }
  13372. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  13373. SkipBodyInfo *SkipBody,
  13374. FnBodyKind BodyKind) {
  13375. if (!D) {
  13376. // Parsing the function declaration failed in some way. Push on a fake scope
  13377. // anyway so we can try to parse the function body.
  13378. PushFunctionScope();
  13379. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  13380. return D;
  13381. }
  13382. FunctionDecl *FD = nullptr;
  13383. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  13384. FD = FunTmpl->getTemplatedDecl();
  13385. else
  13386. FD = cast<FunctionDecl>(D);
  13387. // Do not push if it is a lambda because one is already pushed when building
  13388. // the lambda in ActOnStartOfLambdaDefinition().
  13389. if (!isLambdaCallOperator(FD))
  13390. // [expr.const]/p14.1
  13391. // An expression or conversion is in an immediate function context if it is
  13392. // potentially evaluated and either: its innermost enclosing non-block scope
  13393. // is a function parameter scope of an immediate function.
  13394. PushExpressionEvaluationContext(
  13395. FD->isConsteval() ? ExpressionEvaluationContext::ImmediateFunctionContext
  13396. : ExprEvalContexts.back().Context);
  13397. // Check for defining attributes before the check for redefinition.
  13398. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  13399. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  13400. FD->dropAttr<AliasAttr>();
  13401. FD->setInvalidDecl();
  13402. }
  13403. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  13404. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  13405. FD->dropAttr<IFuncAttr>();
  13406. FD->setInvalidDecl();
  13407. }
  13408. if (const auto *Attr = FD->getAttr<TargetVersionAttr>()) {
  13409. if (!Context.getTargetInfo().hasFeature("fmv") &&
  13410. !Attr->isDefaultVersion()) {
  13411. // If function multi versioning disabled skip parsing function body
  13412. // defined with non-default target_version attribute
  13413. if (SkipBody)
  13414. SkipBody->ShouldSkip = true;
  13415. return nullptr;
  13416. }
  13417. }
  13418. if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
  13419. if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  13420. Ctor->isDefaultConstructor() &&
  13421. Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  13422. // If this is an MS ABI dllexport default constructor, instantiate any
  13423. // default arguments.
  13424. InstantiateDefaultCtorDefaultArgs(Ctor);
  13425. }
  13426. }
  13427. // See if this is a redefinition. If 'will have body' (or similar) is already
  13428. // set, then these checks were already performed when it was set.
  13429. if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
  13430. !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
  13431. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  13432. // If we're skipping the body, we're done. Don't enter the scope.
  13433. if (SkipBody && SkipBody->ShouldSkip)
  13434. return D;
  13435. }
  13436. // Mark this function as "will have a body eventually". This lets users to
  13437. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  13438. // this function.
  13439. FD->setWillHaveBody();
  13440. // If we are instantiating a generic lambda call operator, push
  13441. // a LambdaScopeInfo onto the function stack. But use the information
  13442. // that's already been calculated (ActOnLambdaExpr) to prime the current
  13443. // LambdaScopeInfo.
  13444. // When the template operator is being specialized, the LambdaScopeInfo,
  13445. // has to be properly restored so that tryCaptureVariable doesn't try
  13446. // and capture any new variables. In addition when calculating potential
  13447. // captures during transformation of nested lambdas, it is necessary to
  13448. // have the LSI properly restored.
  13449. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  13450. assert(inTemplateInstantiation() &&
  13451. "There should be an active template instantiation on the stack "
  13452. "when instantiating a generic lambda!");
  13453. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  13454. } else {
  13455. // Enter a new function scope
  13456. PushFunctionScope();
  13457. }
  13458. // Builtin functions cannot be defined.
  13459. if (unsigned BuiltinID = FD->getBuiltinID()) {
  13460. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  13461. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  13462. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  13463. FD->setInvalidDecl();
  13464. }
  13465. }
  13466. // The return type of a function definition must be complete (C99 6.9.1p3),
  13467. // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2)
  13468. QualType ResultType = FD->getReturnType();
  13469. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  13470. !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete &&
  13471. RequireCompleteType(FD->getLocation(), ResultType,
  13472. diag::err_func_def_incomplete_result))
  13473. FD->setInvalidDecl();
  13474. if (FnBodyScope)
  13475. PushDeclContext(FnBodyScope, FD);
  13476. // Check the validity of our function parameters
  13477. if (BodyKind != FnBodyKind::Delete)
  13478. CheckParmsForFunctionDef(FD->parameters(),
  13479. /*CheckParameterNames=*/true);
  13480. // Add non-parameter declarations already in the function to the current
  13481. // scope.
  13482. if (FnBodyScope) {
  13483. for (Decl *NPD : FD->decls()) {
  13484. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  13485. if (!NonParmDecl)
  13486. continue;
  13487. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  13488. "parameters should not be in newly created FD yet");
  13489. // If the decl has a name, make it accessible in the current scope.
  13490. if (NonParmDecl->getDeclName())
  13491. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  13492. // Similarly, dive into enums and fish their constants out, making them
  13493. // accessible in this scope.
  13494. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  13495. for (auto *EI : ED->enumerators())
  13496. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  13497. }
  13498. }
  13499. }
  13500. // Introduce our parameters into the function scope
  13501. for (auto *Param : FD->parameters()) {
  13502. Param->setOwningFunction(FD);
  13503. // If this has an identifier, add it to the scope stack.
  13504. if (Param->getIdentifier() && FnBodyScope) {
  13505. CheckShadow(FnBodyScope, Param);
  13506. PushOnScopeChains(Param, FnBodyScope);
  13507. }
  13508. }
  13509. // C++ [module.import/6] external definitions are not permitted in header
  13510. // units. Deleted and Defaulted functions are implicitly inline (but the
  13511. // inline state is not set at this point, so check the BodyKind explicitly).
  13512. // FIXME: Consider an alternate location for the test where the inlined()
  13513. // state is complete.
  13514. if (getLangOpts().CPlusPlusModules && currentModuleIsHeaderUnit() &&
  13515. !FD->isInvalidDecl() && !FD->isInlined() &&
  13516. BodyKind != FnBodyKind::Delete && BodyKind != FnBodyKind::Default &&
  13517. FD->getFormalLinkage() == Linkage::ExternalLinkage &&
  13518. !FD->isTemplated() && !FD->isTemplateInstantiation()) {
  13519. assert(FD->isThisDeclarationADefinition());
  13520. Diag(FD->getLocation(), diag::err_extern_def_in_header_unit);
  13521. FD->setInvalidDecl();
  13522. }
  13523. // Ensure that the function's exception specification is instantiated.
  13524. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  13525. ResolveExceptionSpec(D->getLocation(), FPT);
  13526. // dllimport cannot be applied to non-inline function definitions.
  13527. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  13528. !FD->isTemplateInstantiation()) {
  13529. assert(!FD->hasAttr<DLLExportAttr>());
  13530. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  13531. FD->setInvalidDecl();
  13532. return D;
  13533. }
  13534. // We want to attach documentation to original Decl (which might be
  13535. // a function template).
  13536. ActOnDocumentableDecl(D);
  13537. if (getCurLexicalContext()->isObjCContainer() &&
  13538. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  13539. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  13540. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  13541. return D;
  13542. }
  13543. /// Given the set of return statements within a function body,
  13544. /// compute the variables that are subject to the named return value
  13545. /// optimization.
  13546. ///
  13547. /// Each of the variables that is subject to the named return value
  13548. /// optimization will be marked as NRVO variables in the AST, and any
  13549. /// return statement that has a marked NRVO variable as its NRVO candidate can
  13550. /// use the named return value optimization.
  13551. ///
  13552. /// This function applies a very simplistic algorithm for NRVO: if every return
  13553. /// statement in the scope of a variable has the same NRVO candidate, that
  13554. /// candidate is an NRVO variable.
  13555. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  13556. ReturnStmt **Returns = Scope->Returns.data();
  13557. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  13558. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  13559. if (!NRVOCandidate->isNRVOVariable())
  13560. Returns[I]->setNRVOCandidate(nullptr);
  13561. }
  13562. }
  13563. }
  13564. bool Sema::canDelayFunctionBody(const Declarator &D) {
  13565. // We can't delay parsing the body of a constexpr function template (yet).
  13566. if (D.getDeclSpec().hasConstexprSpecifier())
  13567. return false;
  13568. // We can't delay parsing the body of a function template with a deduced
  13569. // return type (yet).
  13570. if (D.getDeclSpec().hasAutoTypeSpec()) {
  13571. // If the placeholder introduces a non-deduced trailing return type,
  13572. // we can still delay parsing it.
  13573. if (D.getNumTypeObjects()) {
  13574. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  13575. if (Outer.Kind == DeclaratorChunk::Function &&
  13576. Outer.Fun.hasTrailingReturnType()) {
  13577. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  13578. return Ty.isNull() || !Ty->isUndeducedType();
  13579. }
  13580. }
  13581. return false;
  13582. }
  13583. return true;
  13584. }
  13585. bool Sema::canSkipFunctionBody(Decl *D) {
  13586. // We cannot skip the body of a function (or function template) which is
  13587. // constexpr, since we may need to evaluate its body in order to parse the
  13588. // rest of the file.
  13589. // We cannot skip the body of a function with an undeduced return type,
  13590. // because any callers of that function need to know the type.
  13591. if (const FunctionDecl *FD = D->getAsFunction()) {
  13592. if (FD->isConstexpr())
  13593. return false;
  13594. // We can't simply call Type::isUndeducedType here, because inside template
  13595. // auto can be deduced to a dependent type, which is not considered
  13596. // "undeduced".
  13597. if (FD->getReturnType()->getContainedDeducedType())
  13598. return false;
  13599. }
  13600. return Consumer.shouldSkipFunctionBody(D);
  13601. }
  13602. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  13603. if (!Decl)
  13604. return nullptr;
  13605. if (FunctionDecl *FD = Decl->getAsFunction())
  13606. FD->setHasSkippedBody();
  13607. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  13608. MD->setHasSkippedBody();
  13609. return Decl;
  13610. }
  13611. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  13612. return ActOnFinishFunctionBody(D, BodyArg, false);
  13613. }
  13614. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  13615. /// body.
  13616. class ExitFunctionBodyRAII {
  13617. public:
  13618. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  13619. ~ExitFunctionBodyRAII() {
  13620. if (!IsLambda)
  13621. S.PopExpressionEvaluationContext();
  13622. }
  13623. private:
  13624. Sema &S;
  13625. bool IsLambda = false;
  13626. };
  13627. static void diagnoseImplicitlyRetainedSelf(Sema &S) {
  13628. llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
  13629. auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
  13630. if (EscapeInfo.count(BD))
  13631. return EscapeInfo[BD];
  13632. bool R = false;
  13633. const BlockDecl *CurBD = BD;
  13634. do {
  13635. R = !CurBD->doesNotEscape();
  13636. if (R)
  13637. break;
  13638. CurBD = CurBD->getParent()->getInnermostBlockDecl();
  13639. } while (CurBD);
  13640. return EscapeInfo[BD] = R;
  13641. };
  13642. // If the location where 'self' is implicitly retained is inside a escaping
  13643. // block, emit a diagnostic.
  13644. for (const std::pair<SourceLocation, const BlockDecl *> &P :
  13645. S.ImplicitlyRetainedSelfLocs)
  13646. if (IsOrNestedInEscapingBlock(P.second))
  13647. S.Diag(P.first, diag::warn_implicitly_retains_self)
  13648. << FixItHint::CreateInsertion(P.first, "self->");
  13649. }
  13650. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  13651. bool IsInstantiation) {
  13652. FunctionScopeInfo *FSI = getCurFunction();
  13653. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  13654. if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
  13655. FD->addAttr(StrictFPAttr::CreateImplicit(Context));
  13656. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  13657. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  13658. if (getLangOpts().Coroutines && FSI->isCoroutine())
  13659. CheckCompletedCoroutineBody(FD, Body);
  13660. {
  13661. // Do not call PopExpressionEvaluationContext() if it is a lambda because
  13662. // one is already popped when finishing the lambda in BuildLambdaExpr().
  13663. // This is meant to pop the context added in ActOnStartOfFunctionDef().
  13664. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  13665. if (FD) {
  13666. FD->setBody(Body);
  13667. FD->setWillHaveBody(false);
  13668. if (getLangOpts().CPlusPlus14) {
  13669. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  13670. FD->getReturnType()->isUndeducedType()) {
  13671. // For a function with a deduced result type to return void,
  13672. // the result type as written must be 'auto' or 'decltype(auto)',
  13673. // possibly cv-qualified or constrained, but not ref-qualified.
  13674. if (!FD->getReturnType()->getAs<AutoType>()) {
  13675. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  13676. << FD->getReturnType();
  13677. FD->setInvalidDecl();
  13678. } else {
  13679. // Falling off the end of the function is the same as 'return;'.
  13680. Expr *Dummy = nullptr;
  13681. if (DeduceFunctionTypeFromReturnExpr(
  13682. FD, dcl->getLocation(), Dummy,
  13683. FD->getReturnType()->getAs<AutoType>()))
  13684. FD->setInvalidDecl();
  13685. }
  13686. }
  13687. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  13688. // In C++11, we don't use 'auto' deduction rules for lambda call
  13689. // operators because we don't support return type deduction.
  13690. auto *LSI = getCurLambda();
  13691. if (LSI->HasImplicitReturnType) {
  13692. deduceClosureReturnType(*LSI);
  13693. // C++11 [expr.prim.lambda]p4:
  13694. // [...] if there are no return statements in the compound-statement
  13695. // [the deduced type is] the type void
  13696. QualType RetType =
  13697. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  13698. // Update the return type to the deduced type.
  13699. const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
  13700. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  13701. Proto->getExtProtoInfo()));
  13702. }
  13703. }
  13704. // If the function implicitly returns zero (like 'main') or is naked,
  13705. // don't complain about missing return statements.
  13706. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  13707. WP.disableCheckFallThrough();
  13708. // MSVC permits the use of pure specifier (=0) on function definition,
  13709. // defined at class scope, warn about this non-standard construct.
  13710. if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
  13711. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  13712. if (!FD->isInvalidDecl()) {
  13713. // Don't diagnose unused parameters of defaulted, deleted or naked
  13714. // functions.
  13715. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
  13716. !FD->hasAttr<NakedAttr>())
  13717. DiagnoseUnusedParameters(FD->parameters());
  13718. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  13719. FD->getReturnType(), FD);
  13720. // If this is a structor, we need a vtable.
  13721. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  13722. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  13723. else if (CXXDestructorDecl *Destructor =
  13724. dyn_cast<CXXDestructorDecl>(FD))
  13725. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  13726. // Try to apply the named return value optimization. We have to check
  13727. // if we can do this here because lambdas keep return statements around
  13728. // to deduce an implicit return type.
  13729. if (FD->getReturnType()->isRecordType() &&
  13730. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  13731. computeNRVO(Body, FSI);
  13732. }
  13733. // GNU warning -Wmissing-prototypes:
  13734. // Warn if a global function is defined without a previous
  13735. // prototype declaration. This warning is issued even if the
  13736. // definition itself provides a prototype. The aim is to detect
  13737. // global functions that fail to be declared in header files.
  13738. const FunctionDecl *PossiblePrototype = nullptr;
  13739. if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
  13740. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  13741. if (PossiblePrototype) {
  13742. // We found a declaration that is not a prototype,
  13743. // but that could be a zero-parameter prototype
  13744. if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
  13745. TypeLoc TL = TI->getTypeLoc();
  13746. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  13747. Diag(PossiblePrototype->getLocation(),
  13748. diag::note_declaration_not_a_prototype)
  13749. << (FD->getNumParams() != 0)
  13750. << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
  13751. FTL.getRParenLoc(), "void")
  13752. : FixItHint{});
  13753. }
  13754. } else {
  13755. // Returns true if the token beginning at this Loc is `const`.
  13756. auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
  13757. const LangOptions &LangOpts) {
  13758. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  13759. if (LocInfo.first.isInvalid())
  13760. return false;
  13761. bool Invalid = false;
  13762. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  13763. if (Invalid)
  13764. return false;
  13765. if (LocInfo.second > Buffer.size())
  13766. return false;
  13767. const char *LexStart = Buffer.data() + LocInfo.second;
  13768. StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
  13769. return StartTok.consume_front("const") &&
  13770. (StartTok.empty() || isWhitespace(StartTok[0]) ||
  13771. StartTok.startswith("/*") || StartTok.startswith("//"));
  13772. };
  13773. auto findBeginLoc = [&]() {
  13774. // If the return type has `const` qualifier, we want to insert
  13775. // `static` before `const` (and not before the typename).
  13776. if ((FD->getReturnType()->isAnyPointerType() &&
  13777. FD->getReturnType()->getPointeeType().isConstQualified()) ||
  13778. FD->getReturnType().isConstQualified()) {
  13779. // But only do this if we can determine where the `const` is.
  13780. if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
  13781. getLangOpts()))
  13782. return FD->getBeginLoc();
  13783. }
  13784. return FD->getTypeSpecStartLoc();
  13785. };
  13786. Diag(FD->getTypeSpecStartLoc(),
  13787. diag::note_static_for_internal_linkage)
  13788. << /* function */ 1
  13789. << (FD->getStorageClass() == SC_None
  13790. ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
  13791. : FixItHint{});
  13792. }
  13793. }
  13794. // We might not have found a prototype because we didn't wish to warn on
  13795. // the lack of a missing prototype. Try again without the checks for
  13796. // whether we want to warn on the missing prototype.
  13797. if (!PossiblePrototype)
  13798. (void)FindPossiblePrototype(FD, PossiblePrototype);
  13799. // If the function being defined does not have a prototype, then we may
  13800. // need to diagnose it as changing behavior in C2x because we now know
  13801. // whether the function accepts arguments or not. This only handles the
  13802. // case where the definition has no prototype but does have parameters
  13803. // and either there is no previous potential prototype, or the previous
  13804. // potential prototype also has no actual prototype. This handles cases
  13805. // like:
  13806. // void f(); void f(a) int a; {}
  13807. // void g(a) int a; {}
  13808. // See MergeFunctionDecl() for other cases of the behavior change
  13809. // diagnostic. See GetFullTypeForDeclarator() for handling of a function
  13810. // type without a prototype.
  13811. if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 &&
  13812. (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() &&
  13813. !PossiblePrototype->isImplicit()))) {
  13814. // The function definition has parameters, so this will change behavior
  13815. // in C2x. If there is a possible prototype, it comes before the
  13816. // function definition.
  13817. // FIXME: The declaration may have already been diagnosed as being
  13818. // deprecated in GetFullTypeForDeclarator() if it had no arguments, but
  13819. // there's no way to test for the "changes behavior" condition in
  13820. // SemaType.cpp when forming the declaration's function type. So, we do
  13821. // this awkward dance instead.
  13822. //
  13823. // If we have a possible prototype and it declares a function with a
  13824. // prototype, we don't want to diagnose it; if we have a possible
  13825. // prototype and it has no prototype, it may have already been
  13826. // diagnosed in SemaType.cpp as deprecated depending on whether
  13827. // -Wstrict-prototypes is enabled. If we already warned about it being
  13828. // deprecated, add a note that it also changes behavior. If we didn't
  13829. // warn about it being deprecated (because the diagnostic is not
  13830. // enabled), warn now that it is deprecated and changes behavior.
  13831. // This K&R C function definition definitely changes behavior in C2x,
  13832. // so diagnose it.
  13833. Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior)
  13834. << /*definition*/ 1 << /* not supported in C2x */ 0;
  13835. // If we have a possible prototype for the function which is a user-
  13836. // visible declaration, we already tested that it has no prototype.
  13837. // This will change behavior in C2x. This gets a warning rather than a
  13838. // note because it's the same behavior-changing problem as with the
  13839. // definition.
  13840. if (PossiblePrototype)
  13841. Diag(PossiblePrototype->getLocation(),
  13842. diag::warn_non_prototype_changes_behavior)
  13843. << /*declaration*/ 0 << /* conflicting */ 1 << /*subsequent*/ 1
  13844. << /*definition*/ 1;
  13845. }
  13846. // Warn on CPUDispatch with an actual body.
  13847. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  13848. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  13849. if (!CmpndBody->body_empty())
  13850. Diag(CmpndBody->body_front()->getBeginLoc(),
  13851. diag::warn_dispatch_body_ignored);
  13852. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  13853. const CXXMethodDecl *KeyFunction;
  13854. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  13855. MD->isVirtual() &&
  13856. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  13857. MD == KeyFunction->getCanonicalDecl()) {
  13858. // Update the key-function state if necessary for this ABI.
  13859. if (FD->isInlined() &&
  13860. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  13861. Context.setNonKeyFunction(MD);
  13862. // If the newly-chosen key function is already defined, then we
  13863. // need to mark the vtable as used retroactively.
  13864. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  13865. const FunctionDecl *Definition;
  13866. if (KeyFunction && KeyFunction->isDefined(Definition))
  13867. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  13868. } else {
  13869. // We just defined they key function; mark the vtable as used.
  13870. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  13871. }
  13872. }
  13873. }
  13874. assert(
  13875. (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  13876. "Function parsing confused");
  13877. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  13878. assert(MD == getCurMethodDecl() && "Method parsing confused");
  13879. MD->setBody(Body);
  13880. if (!MD->isInvalidDecl()) {
  13881. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  13882. MD->getReturnType(), MD);
  13883. if (Body)
  13884. computeNRVO(Body, FSI);
  13885. }
  13886. if (FSI->ObjCShouldCallSuper) {
  13887. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  13888. << MD->getSelector().getAsString();
  13889. FSI->ObjCShouldCallSuper = false;
  13890. }
  13891. if (FSI->ObjCWarnForNoDesignatedInitChain) {
  13892. const ObjCMethodDecl *InitMethod = nullptr;
  13893. bool isDesignated =
  13894. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  13895. assert(isDesignated && InitMethod);
  13896. (void)isDesignated;
  13897. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  13898. auto IFace = MD->getClassInterface();
  13899. if (!IFace)
  13900. return false;
  13901. auto SuperD = IFace->getSuperClass();
  13902. if (!SuperD)
  13903. return false;
  13904. return SuperD->getIdentifier() ==
  13905. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  13906. };
  13907. // Don't issue this warning for unavailable inits or direct subclasses
  13908. // of NSObject.
  13909. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  13910. Diag(MD->getLocation(),
  13911. diag::warn_objc_designated_init_missing_super_call);
  13912. Diag(InitMethod->getLocation(),
  13913. diag::note_objc_designated_init_marked_here);
  13914. }
  13915. FSI->ObjCWarnForNoDesignatedInitChain = false;
  13916. }
  13917. if (FSI->ObjCWarnForNoInitDelegation) {
  13918. // Don't issue this warning for unavaialable inits.
  13919. if (!MD->isUnavailable())
  13920. Diag(MD->getLocation(),
  13921. diag::warn_objc_secondary_init_missing_init_call);
  13922. FSI->ObjCWarnForNoInitDelegation = false;
  13923. }
  13924. diagnoseImplicitlyRetainedSelf(*this);
  13925. } else {
  13926. // Parsing the function declaration failed in some way. Pop the fake scope
  13927. // we pushed on.
  13928. PopFunctionScopeInfo(ActivePolicy, dcl);
  13929. return nullptr;
  13930. }
  13931. if (Body && FSI->HasPotentialAvailabilityViolations)
  13932. DiagnoseUnguardedAvailabilityViolations(dcl);
  13933. assert(!FSI->ObjCShouldCallSuper &&
  13934. "This should only be set for ObjC methods, which should have been "
  13935. "handled in the block above.");
  13936. // Verify and clean out per-function state.
  13937. if (Body && (!FD || !FD->isDefaulted())) {
  13938. // C++ constructors that have function-try-blocks can't have return
  13939. // statements in the handlers of that block. (C++ [except.handle]p14)
  13940. // Verify this.
  13941. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  13942. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  13943. // Verify that gotos and switch cases don't jump into scopes illegally.
  13944. if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
  13945. DiagnoseInvalidJumps(Body);
  13946. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  13947. if (!Destructor->getParent()->isDependentType())
  13948. CheckDestructor(Destructor);
  13949. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  13950. Destructor->getParent());
  13951. }
  13952. // If any errors have occurred, clear out any temporaries that may have
  13953. // been leftover. This ensures that these temporaries won't be picked up
  13954. // for deletion in some later function.
  13955. if (hasUncompilableErrorOccurred() ||
  13956. getDiagnostics().getSuppressAllDiagnostics()) {
  13957. DiscardCleanupsInEvaluationContext();
  13958. }
  13959. if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
  13960. // Since the body is valid, issue any analysis-based warnings that are
  13961. // enabled.
  13962. ActivePolicy = &WP;
  13963. }
  13964. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  13965. !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
  13966. FD->setInvalidDecl();
  13967. if (FD && FD->hasAttr<NakedAttr>()) {
  13968. for (const Stmt *S : Body->children()) {
  13969. // Allow local register variables without initializer as they don't
  13970. // require prologue.
  13971. bool RegisterVariables = false;
  13972. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  13973. for (const auto *Decl : DS->decls()) {
  13974. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  13975. RegisterVariables =
  13976. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  13977. if (!RegisterVariables)
  13978. break;
  13979. }
  13980. }
  13981. }
  13982. if (RegisterVariables)
  13983. continue;
  13984. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  13985. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  13986. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  13987. FD->setInvalidDecl();
  13988. break;
  13989. }
  13990. }
  13991. }
  13992. assert(ExprCleanupObjects.size() ==
  13993. ExprEvalContexts.back().NumCleanupObjects &&
  13994. "Leftover temporaries in function");
  13995. assert(!Cleanup.exprNeedsCleanups() &&
  13996. "Unaccounted cleanups in function");
  13997. assert(MaybeODRUseExprs.empty() &&
  13998. "Leftover expressions for odr-use checking");
  13999. }
  14000. } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
  14001. // the declaration context below. Otherwise, we're unable to transform
  14002. // 'this' expressions when transforming immediate context functions.
  14003. if (!IsInstantiation)
  14004. PopDeclContext();
  14005. PopFunctionScopeInfo(ActivePolicy, dcl);
  14006. // If any errors have occurred, clear out any temporaries that may have
  14007. // been leftover. This ensures that these temporaries won't be picked up for
  14008. // deletion in some later function.
  14009. if (hasUncompilableErrorOccurred()) {
  14010. DiscardCleanupsInEvaluationContext();
  14011. }
  14012. if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
  14013. !LangOpts.OMPTargetTriples.empty())) ||
  14014. LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
  14015. auto ES = getEmissionStatus(FD);
  14016. if (ES == Sema::FunctionEmissionStatus::Emitted ||
  14017. ES == Sema::FunctionEmissionStatus::Unknown)
  14018. DeclsToCheckForDeferredDiags.insert(FD);
  14019. }
  14020. if (FD && !FD->isDeleted())
  14021. checkTypeSupport(FD->getType(), FD->getLocation(), FD);
  14022. return dcl;
  14023. }
  14024. /// When we finish delayed parsing of an attribute, we must attach it to the
  14025. /// relevant Decl.
  14026. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  14027. ParsedAttributes &Attrs) {
  14028. // Always attach attributes to the underlying decl.
  14029. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  14030. D = TD->getTemplatedDecl();
  14031. ProcessDeclAttributeList(S, D, Attrs);
  14032. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  14033. if (Method->isStatic())
  14034. checkThisInStaticMemberFunctionAttributes(Method);
  14035. }
  14036. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  14037. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  14038. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  14039. IdentifierInfo &II, Scope *S) {
  14040. // It is not valid to implicitly define a function in C2x.
  14041. assert(LangOpts.implicitFunctionsAllowed() &&
  14042. "Implicit function declarations aren't allowed in this language mode");
  14043. // Find the scope in which the identifier is injected and the corresponding
  14044. // DeclContext.
  14045. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  14046. // In that case, we inject the declaration into the translation unit scope
  14047. // instead.
  14048. Scope *BlockScope = S;
  14049. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  14050. BlockScope = BlockScope->getParent();
  14051. Scope *ContextScope = BlockScope;
  14052. while (!ContextScope->getEntity())
  14053. ContextScope = ContextScope->getParent();
  14054. ContextRAII SavedContext(*this, ContextScope->getEntity());
  14055. // Before we produce a declaration for an implicitly defined
  14056. // function, see whether there was a locally-scoped declaration of
  14057. // this name as a function or variable. If so, use that
  14058. // (non-visible) declaration, and complain about it.
  14059. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  14060. if (ExternCPrev) {
  14061. // We still need to inject the function into the enclosing block scope so
  14062. // that later (non-call) uses can see it.
  14063. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  14064. // C89 footnote 38:
  14065. // If in fact it is not defined as having type "function returning int",
  14066. // the behavior is undefined.
  14067. if (!isa<FunctionDecl>(ExternCPrev) ||
  14068. !Context.typesAreCompatible(
  14069. cast<FunctionDecl>(ExternCPrev)->getType(),
  14070. Context.getFunctionNoProtoType(Context.IntTy))) {
  14071. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  14072. << ExternCPrev << !getLangOpts().C99;
  14073. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  14074. return ExternCPrev;
  14075. }
  14076. }
  14077. // Extension in C99 (defaults to error). Legal in C89, but warn about it.
  14078. unsigned diag_id;
  14079. if (II.getName().startswith("__builtin_"))
  14080. diag_id = diag::warn_builtin_unknown;
  14081. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  14082. else if (getLangOpts().C99)
  14083. diag_id = diag::ext_implicit_function_decl_c99;
  14084. else
  14085. diag_id = diag::warn_implicit_function_decl;
  14086. TypoCorrection Corrected;
  14087. // Because typo correction is expensive, only do it if the implicit
  14088. // function declaration is going to be treated as an error.
  14089. //
  14090. // Perform the correction before issuing the main diagnostic, as some
  14091. // consumers use typo-correction callbacks to enhance the main diagnostic.
  14092. if (S && !ExternCPrev &&
  14093. (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
  14094. DeclFilterCCC<FunctionDecl> CCC{};
  14095. Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
  14096. S, nullptr, CCC, CTK_NonError);
  14097. }
  14098. Diag(Loc, diag_id) << &II;
  14099. if (Corrected) {
  14100. // If the correction is going to suggest an implicitly defined function,
  14101. // skip the correction as not being a particularly good idea.
  14102. bool Diagnose = true;
  14103. if (const auto *D = Corrected.getCorrectionDecl())
  14104. Diagnose = !D->isImplicit();
  14105. if (Diagnose)
  14106. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  14107. /*ErrorRecovery*/ false);
  14108. }
  14109. // If we found a prior declaration of this function, don't bother building
  14110. // another one. We've already pushed that one into scope, so there's nothing
  14111. // more to do.
  14112. if (ExternCPrev)
  14113. return ExternCPrev;
  14114. // Set a Declarator for the implicit definition: int foo();
  14115. const char *Dummy;
  14116. AttributeFactory attrFactory;
  14117. DeclSpec DS(attrFactory);
  14118. unsigned DiagID;
  14119. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  14120. Context.getPrintingPolicy());
  14121. (void)Error; // Silence warning.
  14122. assert(!Error && "Error setting up implicit decl!");
  14123. SourceLocation NoLoc;
  14124. Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::Block);
  14125. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  14126. /*IsAmbiguous=*/false,
  14127. /*LParenLoc=*/NoLoc,
  14128. /*Params=*/nullptr,
  14129. /*NumParams=*/0,
  14130. /*EllipsisLoc=*/NoLoc,
  14131. /*RParenLoc=*/NoLoc,
  14132. /*RefQualifierIsLvalueRef=*/true,
  14133. /*RefQualifierLoc=*/NoLoc,
  14134. /*MutableLoc=*/NoLoc, EST_None,
  14135. /*ESpecRange=*/SourceRange(),
  14136. /*Exceptions=*/nullptr,
  14137. /*ExceptionRanges=*/nullptr,
  14138. /*NumExceptions=*/0,
  14139. /*NoexceptExpr=*/nullptr,
  14140. /*ExceptionSpecTokens=*/nullptr,
  14141. /*DeclsInPrototype=*/std::nullopt,
  14142. Loc, Loc, D),
  14143. std::move(DS.getAttributes()), SourceLocation());
  14144. D.SetIdentifier(&II, Loc);
  14145. // Insert this function into the enclosing block scope.
  14146. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  14147. FD->setImplicit();
  14148. AddKnownFunctionAttributes(FD);
  14149. return FD;
  14150. }
  14151. /// If this function is a C++ replaceable global allocation function
  14152. /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
  14153. /// adds any function attributes that we know a priori based on the standard.
  14154. ///
  14155. /// We need to check for duplicate attributes both here and where user-written
  14156. /// attributes are applied to declarations.
  14157. void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
  14158. FunctionDecl *FD) {
  14159. if (FD->isInvalidDecl())
  14160. return;
  14161. if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
  14162. FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
  14163. return;
  14164. std::optional<unsigned> AlignmentParam;
  14165. bool IsNothrow = false;
  14166. if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
  14167. return;
  14168. // C++2a [basic.stc.dynamic.allocation]p4:
  14169. // An allocation function that has a non-throwing exception specification
  14170. // indicates failure by returning a null pointer value. Any other allocation
  14171. // function never returns a null pointer value and indicates failure only by
  14172. // throwing an exception [...]
  14173. if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
  14174. FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
  14175. // C++2a [basic.stc.dynamic.allocation]p2:
  14176. // An allocation function attempts to allocate the requested amount of
  14177. // storage. [...] If the request succeeds, the value returned by a
  14178. // replaceable allocation function is a [...] pointer value p0 different
  14179. // from any previously returned value p1 [...]
  14180. //
  14181. // However, this particular information is being added in codegen,
  14182. // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
  14183. // C++2a [basic.stc.dynamic.allocation]p2:
  14184. // An allocation function attempts to allocate the requested amount of
  14185. // storage. If it is successful, it returns the address of the start of a
  14186. // block of storage whose length in bytes is at least as large as the
  14187. // requested size.
  14188. if (!FD->hasAttr<AllocSizeAttr>()) {
  14189. FD->addAttr(AllocSizeAttr::CreateImplicit(
  14190. Context, /*ElemSizeParam=*/ParamIdx(1, FD),
  14191. /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
  14192. }
  14193. // C++2a [basic.stc.dynamic.allocation]p3:
  14194. // For an allocation function [...], the pointer returned on a successful
  14195. // call shall represent the address of storage that is aligned as follows:
  14196. // (3.1) If the allocation function takes an argument of type
  14197. // std​::​align_­val_­t, the storage will have the alignment
  14198. // specified by the value of this argument.
  14199. if (AlignmentParam && !FD->hasAttr<AllocAlignAttr>()) {
  14200. FD->addAttr(AllocAlignAttr::CreateImplicit(
  14201. Context, ParamIdx(*AlignmentParam, FD), FD->getLocation()));
  14202. }
  14203. // FIXME:
  14204. // C++2a [basic.stc.dynamic.allocation]p3:
  14205. // For an allocation function [...], the pointer returned on a successful
  14206. // call shall represent the address of storage that is aligned as follows:
  14207. // (3.2) Otherwise, if the allocation function is named operator new[],
  14208. // the storage is aligned for any object that does not have
  14209. // new-extended alignment ([basic.align]) and is no larger than the
  14210. // requested size.
  14211. // (3.3) Otherwise, the storage is aligned for any object that does not
  14212. // have new-extended alignment and is of the requested size.
  14213. }
  14214. /// Adds any function attributes that we know a priori based on
  14215. /// the declaration of this function.
  14216. ///
  14217. /// These attributes can apply both to implicitly-declared builtins
  14218. /// (like __builtin___printf_chk) or to library-declared functions
  14219. /// like NSLog or printf.
  14220. ///
  14221. /// We need to check for duplicate attributes both here and where user-written
  14222. /// attributes are applied to declarations.
  14223. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  14224. if (FD->isInvalidDecl())
  14225. return;
  14226. // If this is a built-in function, map its builtin attributes to
  14227. // actual attributes.
  14228. if (unsigned BuiltinID = FD->getBuiltinID()) {
  14229. // Handle printf-formatting attributes.
  14230. unsigned FormatIdx;
  14231. bool HasVAListArg;
  14232. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  14233. if (!FD->hasAttr<FormatAttr>()) {
  14234. const char *fmt = "printf";
  14235. unsigned int NumParams = FD->getNumParams();
  14236. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  14237. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  14238. fmt = "NSString";
  14239. FD->addAttr(FormatAttr::CreateImplicit(Context,
  14240. &Context.Idents.get(fmt),
  14241. FormatIdx+1,
  14242. HasVAListArg ? 0 : FormatIdx+2,
  14243. FD->getLocation()));
  14244. }
  14245. }
  14246. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  14247. HasVAListArg)) {
  14248. if (!FD->hasAttr<FormatAttr>())
  14249. FD->addAttr(FormatAttr::CreateImplicit(Context,
  14250. &Context.Idents.get("scanf"),
  14251. FormatIdx+1,
  14252. HasVAListArg ? 0 : FormatIdx+2,
  14253. FD->getLocation()));
  14254. }
  14255. // Handle automatically recognized callbacks.
  14256. SmallVector<int, 4> Encoding;
  14257. if (!FD->hasAttr<CallbackAttr>() &&
  14258. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  14259. FD->addAttr(CallbackAttr::CreateImplicit(
  14260. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  14261. // Mark const if we don't care about errno and/or floating point exceptions
  14262. // that are the only thing preventing the function from being const. This
  14263. // allows IRgen to use LLVM intrinsics for such functions.
  14264. bool NoExceptions =
  14265. getLangOpts().getDefaultExceptionMode() == LangOptions::FPE_Ignore;
  14266. bool ConstWithoutErrnoAndExceptions =
  14267. Context.BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
  14268. bool ConstWithoutExceptions =
  14269. Context.BuiltinInfo.isConstWithoutExceptions(BuiltinID);
  14270. if (!FD->hasAttr<ConstAttr>() &&
  14271. (ConstWithoutErrnoAndExceptions || ConstWithoutExceptions) &&
  14272. (!ConstWithoutErrnoAndExceptions ||
  14273. (!getLangOpts().MathErrno && NoExceptions)) &&
  14274. (!ConstWithoutExceptions || NoExceptions))
  14275. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  14276. // We make "fma" on GNU or Windows const because we know it does not set
  14277. // errno in those environments even though it could set errno based on the
  14278. // C standard.
  14279. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  14280. if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
  14281. !FD->hasAttr<ConstAttr>()) {
  14282. switch (BuiltinID) {
  14283. case Builtin::BI__builtin_fma:
  14284. case Builtin::BI__builtin_fmaf:
  14285. case Builtin::BI__builtin_fmal:
  14286. case Builtin::BIfma:
  14287. case Builtin::BIfmaf:
  14288. case Builtin::BIfmal:
  14289. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  14290. break;
  14291. default:
  14292. break;
  14293. }
  14294. }
  14295. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  14296. !FD->hasAttr<ReturnsTwiceAttr>())
  14297. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  14298. FD->getLocation()));
  14299. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  14300. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  14301. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  14302. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  14303. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  14304. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  14305. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  14306. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  14307. // Add the appropriate attribute, depending on the CUDA compilation mode
  14308. // and which target the builtin belongs to. For example, during host
  14309. // compilation, aux builtins are __device__, while the rest are __host__.
  14310. if (getLangOpts().CUDAIsDevice !=
  14311. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  14312. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  14313. else
  14314. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  14315. }
  14316. // Add known guaranteed alignment for allocation functions.
  14317. switch (BuiltinID) {
  14318. case Builtin::BImemalign:
  14319. case Builtin::BIaligned_alloc:
  14320. if (!FD->hasAttr<AllocAlignAttr>())
  14321. FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
  14322. FD->getLocation()));
  14323. break;
  14324. default:
  14325. break;
  14326. }
  14327. // Add allocsize attribute for allocation functions.
  14328. switch (BuiltinID) {
  14329. case Builtin::BIcalloc:
  14330. FD->addAttr(AllocSizeAttr::CreateImplicit(
  14331. Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
  14332. break;
  14333. case Builtin::BImemalign:
  14334. case Builtin::BIaligned_alloc:
  14335. case Builtin::BIrealloc:
  14336. FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
  14337. ParamIdx(), FD->getLocation()));
  14338. break;
  14339. case Builtin::BImalloc:
  14340. FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
  14341. ParamIdx(), FD->getLocation()));
  14342. break;
  14343. default:
  14344. break;
  14345. }
  14346. // Add lifetime attribute to std::move, std::fowrard et al.
  14347. switch (BuiltinID) {
  14348. case Builtin::BIaddressof:
  14349. case Builtin::BI__addressof:
  14350. case Builtin::BI__builtin_addressof:
  14351. case Builtin::BIas_const:
  14352. case Builtin::BIforward:
  14353. case Builtin::BImove:
  14354. case Builtin::BImove_if_noexcept:
  14355. if (ParmVarDecl *P = FD->getParamDecl(0u);
  14356. !P->hasAttr<LifetimeBoundAttr>())
  14357. P->addAttr(
  14358. LifetimeBoundAttr::CreateImplicit(Context, FD->getLocation()));
  14359. break;
  14360. default:
  14361. break;
  14362. }
  14363. }
  14364. AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
  14365. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  14366. // throw, add an implicit nothrow attribute to any extern "C" function we come
  14367. // across.
  14368. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  14369. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  14370. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  14371. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  14372. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  14373. }
  14374. IdentifierInfo *Name = FD->getIdentifier();
  14375. if (!Name)
  14376. return;
  14377. if ((!getLangOpts().CPlusPlus &&
  14378. FD->getDeclContext()->isTranslationUnit()) ||
  14379. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  14380. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  14381. LinkageSpecDecl::lang_c)) {
  14382. // Okay: this could be a libc/libm/Objective-C function we know
  14383. // about.
  14384. } else
  14385. return;
  14386. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  14387. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  14388. // target-specific builtins, perhaps?
  14389. if (!FD->hasAttr<FormatAttr>())
  14390. FD->addAttr(FormatAttr::CreateImplicit(Context,
  14391. &Context.Idents.get("printf"), 2,
  14392. Name->isStr("vasprintf") ? 0 : 3,
  14393. FD->getLocation()));
  14394. }
  14395. if (Name->isStr("__CFStringMakeConstantString")) {
  14396. // We already have a __builtin___CFStringMakeConstantString,
  14397. // but builds that use -fno-constant-cfstrings don't go through that.
  14398. if (!FD->hasAttr<FormatArgAttr>())
  14399. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  14400. FD->getLocation()));
  14401. }
  14402. }
  14403. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  14404. TypeSourceInfo *TInfo) {
  14405. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  14406. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  14407. if (!TInfo) {
  14408. assert(D.isInvalidType() && "no declarator info for valid type");
  14409. TInfo = Context.getTrivialTypeSourceInfo(T);
  14410. }
  14411. // Scope manipulation handled by caller.
  14412. TypedefDecl *NewTD =
  14413. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  14414. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  14415. // Bail out immediately if we have an invalid declaration.
  14416. if (D.isInvalidType()) {
  14417. NewTD->setInvalidDecl();
  14418. return NewTD;
  14419. }
  14420. if (D.getDeclSpec().isModulePrivateSpecified()) {
  14421. if (CurContext->isFunctionOrMethod())
  14422. Diag(NewTD->getLocation(), diag::err_module_private_local)
  14423. << 2 << NewTD
  14424. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  14425. << FixItHint::CreateRemoval(
  14426. D.getDeclSpec().getModulePrivateSpecLoc());
  14427. else
  14428. NewTD->setModulePrivate();
  14429. }
  14430. // C++ [dcl.typedef]p8:
  14431. // If the typedef declaration defines an unnamed class (or
  14432. // enum), the first typedef-name declared by the declaration
  14433. // to be that class type (or enum type) is used to denote the
  14434. // class type (or enum type) for linkage purposes only.
  14435. // We need to check whether the type was declared in the declaration.
  14436. switch (D.getDeclSpec().getTypeSpecType()) {
  14437. case TST_enum:
  14438. case TST_struct:
  14439. case TST_interface:
  14440. case TST_union:
  14441. case TST_class: {
  14442. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  14443. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  14444. break;
  14445. }
  14446. default:
  14447. break;
  14448. }
  14449. return NewTD;
  14450. }
  14451. /// Check that this is a valid underlying type for an enum declaration.
  14452. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  14453. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  14454. QualType T = TI->getType();
  14455. if (T->isDependentType())
  14456. return false;
  14457. // This doesn't use 'isIntegralType' despite the error message mentioning
  14458. // integral type because isIntegralType would also allow enum types in C.
  14459. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  14460. if (BT->isInteger())
  14461. return false;
  14462. if (T->isBitIntType())
  14463. return false;
  14464. return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  14465. }
  14466. /// Check whether this is a valid redeclaration of a previous enumeration.
  14467. /// \return true if the redeclaration was invalid.
  14468. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  14469. QualType EnumUnderlyingTy, bool IsFixed,
  14470. const EnumDecl *Prev) {
  14471. if (IsScoped != Prev->isScoped()) {
  14472. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  14473. << Prev->isScoped();
  14474. Diag(Prev->getLocation(), diag::note_previous_declaration);
  14475. return true;
  14476. }
  14477. if (IsFixed && Prev->isFixed()) {
  14478. if (!EnumUnderlyingTy->isDependentType() &&
  14479. !Prev->getIntegerType()->isDependentType() &&
  14480. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  14481. Prev->getIntegerType())) {
  14482. // TODO: Highlight the underlying type of the redeclaration.
  14483. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  14484. << EnumUnderlyingTy << Prev->getIntegerType();
  14485. Diag(Prev->getLocation(), diag::note_previous_declaration)
  14486. << Prev->getIntegerTypeRange();
  14487. return true;
  14488. }
  14489. } else if (IsFixed != Prev->isFixed()) {
  14490. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  14491. << Prev->isFixed();
  14492. Diag(Prev->getLocation(), diag::note_previous_declaration);
  14493. return true;
  14494. }
  14495. return false;
  14496. }
  14497. /// Get diagnostic %select index for tag kind for
  14498. /// redeclaration diagnostic message.
  14499. /// WARNING: Indexes apply to particular diagnostics only!
  14500. ///
  14501. /// \returns diagnostic %select index.
  14502. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  14503. switch (Tag) {
  14504. case TTK_Struct: return 0;
  14505. case TTK_Interface: return 1;
  14506. case TTK_Class: return 2;
  14507. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  14508. }
  14509. }
  14510. /// Determine if tag kind is a class-key compatible with
  14511. /// class for redeclaration (class, struct, or __interface).
  14512. ///
  14513. /// \returns true iff the tag kind is compatible.
  14514. static bool isClassCompatTagKind(TagTypeKind Tag)
  14515. {
  14516. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  14517. }
  14518. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  14519. TagTypeKind TTK) {
  14520. if (isa<TypedefDecl>(PrevDecl))
  14521. return NTK_Typedef;
  14522. else if (isa<TypeAliasDecl>(PrevDecl))
  14523. return NTK_TypeAlias;
  14524. else if (isa<ClassTemplateDecl>(PrevDecl))
  14525. return NTK_Template;
  14526. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  14527. return NTK_TypeAliasTemplate;
  14528. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  14529. return NTK_TemplateTemplateArgument;
  14530. switch (TTK) {
  14531. case TTK_Struct:
  14532. case TTK_Interface:
  14533. case TTK_Class:
  14534. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  14535. case TTK_Union:
  14536. return NTK_NonUnion;
  14537. case TTK_Enum:
  14538. return NTK_NonEnum;
  14539. }
  14540. llvm_unreachable("invalid TTK");
  14541. }
  14542. /// Determine whether a tag with a given kind is acceptable
  14543. /// as a redeclaration of the given tag declaration.
  14544. ///
  14545. /// \returns true if the new tag kind is acceptable, false otherwise.
  14546. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  14547. TagTypeKind NewTag, bool isDefinition,
  14548. SourceLocation NewTagLoc,
  14549. const IdentifierInfo *Name) {
  14550. // C++ [dcl.type.elab]p3:
  14551. // The class-key or enum keyword present in the
  14552. // elaborated-type-specifier shall agree in kind with the
  14553. // declaration to which the name in the elaborated-type-specifier
  14554. // refers. This rule also applies to the form of
  14555. // elaborated-type-specifier that declares a class-name or
  14556. // friend class since it can be construed as referring to the
  14557. // definition of the class. Thus, in any
  14558. // elaborated-type-specifier, the enum keyword shall be used to
  14559. // refer to an enumeration (7.2), the union class-key shall be
  14560. // used to refer to a union (clause 9), and either the class or
  14561. // struct class-key shall be used to refer to a class (clause 9)
  14562. // declared using the class or struct class-key.
  14563. TagTypeKind OldTag = Previous->getTagKind();
  14564. if (OldTag != NewTag &&
  14565. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  14566. return false;
  14567. // Tags are compatible, but we might still want to warn on mismatched tags.
  14568. // Non-class tags can't be mismatched at this point.
  14569. if (!isClassCompatTagKind(NewTag))
  14570. return true;
  14571. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  14572. // by our warning analysis. We don't want to warn about mismatches with (eg)
  14573. // declarations in system headers that are designed to be specialized, but if
  14574. // a user asks us to warn, we should warn if their code contains mismatched
  14575. // declarations.
  14576. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  14577. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  14578. Loc);
  14579. };
  14580. if (IsIgnoredLoc(NewTagLoc))
  14581. return true;
  14582. auto IsIgnored = [&](const TagDecl *Tag) {
  14583. return IsIgnoredLoc(Tag->getLocation());
  14584. };
  14585. while (IsIgnored(Previous)) {
  14586. Previous = Previous->getPreviousDecl();
  14587. if (!Previous)
  14588. return true;
  14589. OldTag = Previous->getTagKind();
  14590. }
  14591. bool isTemplate = false;
  14592. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  14593. isTemplate = Record->getDescribedClassTemplate();
  14594. if (inTemplateInstantiation()) {
  14595. if (OldTag != NewTag) {
  14596. // In a template instantiation, do not offer fix-its for tag mismatches
  14597. // since they usually mess up the template instead of fixing the problem.
  14598. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  14599. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  14600. << getRedeclDiagFromTagKind(OldTag);
  14601. // FIXME: Note previous location?
  14602. }
  14603. return true;
  14604. }
  14605. if (isDefinition) {
  14606. // On definitions, check all previous tags and issue a fix-it for each
  14607. // one that doesn't match the current tag.
  14608. if (Previous->getDefinition()) {
  14609. // Don't suggest fix-its for redefinitions.
  14610. return true;
  14611. }
  14612. bool previousMismatch = false;
  14613. for (const TagDecl *I : Previous->redecls()) {
  14614. if (I->getTagKind() != NewTag) {
  14615. // Ignore previous declarations for which the warning was disabled.
  14616. if (IsIgnored(I))
  14617. continue;
  14618. if (!previousMismatch) {
  14619. previousMismatch = true;
  14620. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  14621. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  14622. << getRedeclDiagFromTagKind(I->getTagKind());
  14623. }
  14624. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  14625. << getRedeclDiagFromTagKind(NewTag)
  14626. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  14627. TypeWithKeyword::getTagTypeKindName(NewTag));
  14628. }
  14629. }
  14630. return true;
  14631. }
  14632. // Identify the prevailing tag kind: this is the kind of the definition (if
  14633. // there is a non-ignored definition), or otherwise the kind of the prior
  14634. // (non-ignored) declaration.
  14635. const TagDecl *PrevDef = Previous->getDefinition();
  14636. if (PrevDef && IsIgnored(PrevDef))
  14637. PrevDef = nullptr;
  14638. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  14639. if (Redecl->getTagKind() != NewTag) {
  14640. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  14641. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  14642. << getRedeclDiagFromTagKind(OldTag);
  14643. Diag(Redecl->getLocation(), diag::note_previous_use);
  14644. // If there is a previous definition, suggest a fix-it.
  14645. if (PrevDef) {
  14646. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  14647. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  14648. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  14649. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  14650. }
  14651. }
  14652. return true;
  14653. }
  14654. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  14655. /// from an outer enclosing namespace or file scope inside a friend declaration.
  14656. /// This should provide the commented out code in the following snippet:
  14657. /// namespace N {
  14658. /// struct X;
  14659. /// namespace M {
  14660. /// struct Y { friend struct /*N::*/ X; };
  14661. /// }
  14662. /// }
  14663. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  14664. SourceLocation NameLoc) {
  14665. // While the decl is in a namespace, do repeated lookup of that name and see
  14666. // if we get the same namespace back. If we do not, continue until
  14667. // translation unit scope, at which point we have a fully qualified NNS.
  14668. SmallVector<IdentifierInfo *, 4> Namespaces;
  14669. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  14670. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  14671. // This tag should be declared in a namespace, which can only be enclosed by
  14672. // other namespaces. Bail if there's an anonymous namespace in the chain.
  14673. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  14674. if (!Namespace || Namespace->isAnonymousNamespace())
  14675. return FixItHint();
  14676. IdentifierInfo *II = Namespace->getIdentifier();
  14677. Namespaces.push_back(II);
  14678. NamedDecl *Lookup = SemaRef.LookupSingleName(
  14679. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  14680. if (Lookup == Namespace)
  14681. break;
  14682. }
  14683. // Once we have all the namespaces, reverse them to go outermost first, and
  14684. // build an NNS.
  14685. SmallString<64> Insertion;
  14686. llvm::raw_svector_ostream OS(Insertion);
  14687. if (DC->isTranslationUnit())
  14688. OS << "::";
  14689. std::reverse(Namespaces.begin(), Namespaces.end());
  14690. for (auto *II : Namespaces)
  14691. OS << II->getName() << "::";
  14692. return FixItHint::CreateInsertion(NameLoc, Insertion);
  14693. }
  14694. /// Determine whether a tag originally declared in context \p OldDC can
  14695. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  14696. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  14697. /// using-declaration).
  14698. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  14699. DeclContext *NewDC) {
  14700. OldDC = OldDC->getRedeclContext();
  14701. NewDC = NewDC->getRedeclContext();
  14702. if (OldDC->Equals(NewDC))
  14703. return true;
  14704. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  14705. // encloses the other).
  14706. if (S.getLangOpts().MSVCCompat &&
  14707. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  14708. return true;
  14709. return false;
  14710. }
  14711. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  14712. /// former case, Name will be non-null. In the later case, Name will be null.
  14713. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  14714. /// reference/declaration/definition of a tag.
  14715. ///
  14716. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  14717. /// trailing-type-specifier) other than one in an alias-declaration.
  14718. ///
  14719. /// \param SkipBody If non-null, will be set to indicate if the caller should
  14720. /// skip the definition of this tag and treat it as if it were a declaration.
  14721. DeclResult
  14722. Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
  14723. CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
  14724. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  14725. SourceLocation ModulePrivateLoc,
  14726. MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
  14727. bool &IsDependent, SourceLocation ScopedEnumKWLoc,
  14728. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  14729. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  14730. OffsetOfKind OOK, SkipBodyInfo *SkipBody) {
  14731. // If this is not a definition, it must have a name.
  14732. IdentifierInfo *OrigName = Name;
  14733. assert((Name != nullptr || TUK == TUK_Definition) &&
  14734. "Nameless record must be a definition!");
  14735. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  14736. OwnedDecl = false;
  14737. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  14738. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  14739. // FIXME: Check member specializations more carefully.
  14740. bool isMemberSpecialization = false;
  14741. bool Invalid = false;
  14742. // We only need to do this matching if we have template parameters
  14743. // or a scope specifier, which also conveniently avoids this work
  14744. // for non-C++ cases.
  14745. if (TemplateParameterLists.size() > 0 ||
  14746. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  14747. if (TemplateParameterList *TemplateParams =
  14748. MatchTemplateParametersToScopeSpecifier(
  14749. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  14750. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  14751. if (Kind == TTK_Enum) {
  14752. Diag(KWLoc, diag::err_enum_template);
  14753. return true;
  14754. }
  14755. if (TemplateParams->size() > 0) {
  14756. // This is a declaration or definition of a class template (which may
  14757. // be a member of another template).
  14758. if (Invalid)
  14759. return true;
  14760. OwnedDecl = false;
  14761. DeclResult Result = CheckClassTemplate(
  14762. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  14763. AS, ModulePrivateLoc,
  14764. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  14765. TemplateParameterLists.data(), SkipBody);
  14766. return Result.get();
  14767. } else {
  14768. // The "template<>" header is extraneous.
  14769. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  14770. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  14771. isMemberSpecialization = true;
  14772. }
  14773. }
  14774. if (!TemplateParameterLists.empty() && isMemberSpecialization &&
  14775. CheckTemplateDeclScope(S, TemplateParameterLists.back()))
  14776. return true;
  14777. }
  14778. // Figure out the underlying type if this a enum declaration. We need to do
  14779. // this early, because it's needed to detect if this is an incompatible
  14780. // redeclaration.
  14781. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  14782. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  14783. if (Kind == TTK_Enum) {
  14784. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  14785. // No underlying type explicitly specified, or we failed to parse the
  14786. // type, default to int.
  14787. EnumUnderlying = Context.IntTy.getTypePtr();
  14788. } else if (UnderlyingType.get()) {
  14789. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  14790. // integral type; any cv-qualification is ignored.
  14791. TypeSourceInfo *TI = nullptr;
  14792. GetTypeFromParser(UnderlyingType.get(), &TI);
  14793. EnumUnderlying = TI;
  14794. if (CheckEnumUnderlyingType(TI))
  14795. // Recover by falling back to int.
  14796. EnumUnderlying = Context.IntTy.getTypePtr();
  14797. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  14798. UPPC_FixedUnderlyingType))
  14799. EnumUnderlying = Context.IntTy.getTypePtr();
  14800. } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
  14801. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  14802. // of 'int'. However, if this is an unfixed forward declaration, don't set
  14803. // the underlying type unless the user enables -fms-compatibility. This
  14804. // makes unfixed forward declared enums incomplete and is more conforming.
  14805. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  14806. EnumUnderlying = Context.IntTy.getTypePtr();
  14807. }
  14808. }
  14809. DeclContext *SearchDC = CurContext;
  14810. DeclContext *DC = CurContext;
  14811. bool isStdBadAlloc = false;
  14812. bool isStdAlignValT = false;
  14813. RedeclarationKind Redecl = forRedeclarationInCurContext();
  14814. if (TUK == TUK_Friend || TUK == TUK_Reference)
  14815. Redecl = NotForRedeclaration;
  14816. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  14817. /// implemented asks for structural equivalence checking, the returned decl
  14818. /// here is passed back to the parser, allowing the tag body to be parsed.
  14819. auto createTagFromNewDecl = [&]() -> TagDecl * {
  14820. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  14821. // If there is an identifier, use the location of the identifier as the
  14822. // location of the decl, otherwise use the location of the struct/union
  14823. // keyword.
  14824. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  14825. TagDecl *New = nullptr;
  14826. if (Kind == TTK_Enum) {
  14827. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  14828. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  14829. // If this is an undefined enum, bail.
  14830. if (TUK != TUK_Definition && !Invalid)
  14831. return nullptr;
  14832. if (EnumUnderlying) {
  14833. EnumDecl *ED = cast<EnumDecl>(New);
  14834. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  14835. ED->setIntegerTypeSourceInfo(TI);
  14836. else
  14837. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  14838. QualType EnumTy = ED->getIntegerType();
  14839. ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
  14840. ? Context.getPromotedIntegerType(EnumTy)
  14841. : EnumTy);
  14842. }
  14843. } else { // struct/union
  14844. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  14845. nullptr);
  14846. }
  14847. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  14848. // Add alignment attributes if necessary; these attributes are checked
  14849. // when the ASTContext lays out the structure.
  14850. //
  14851. // It is important for implementing the correct semantics that this
  14852. // happen here (in ActOnTag). The #pragma pack stack is
  14853. // maintained as a result of parser callbacks which can occur at
  14854. // many points during the parsing of a struct declaration (because
  14855. // the #pragma tokens are effectively skipped over during the
  14856. // parsing of the struct).
  14857. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  14858. AddAlignmentAttributesForRecord(RD);
  14859. AddMsStructLayoutForRecord(RD);
  14860. }
  14861. }
  14862. New->setLexicalDeclContext(CurContext);
  14863. return New;
  14864. };
  14865. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  14866. if (Name && SS.isNotEmpty()) {
  14867. // We have a nested-name tag ('struct foo::bar').
  14868. // Check for invalid 'foo::'.
  14869. if (SS.isInvalid()) {
  14870. Name = nullptr;
  14871. goto CreateNewDecl;
  14872. }
  14873. // If this is a friend or a reference to a class in a dependent
  14874. // context, don't try to make a decl for it.
  14875. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  14876. DC = computeDeclContext(SS, false);
  14877. if (!DC) {
  14878. IsDependent = true;
  14879. return true;
  14880. }
  14881. } else {
  14882. DC = computeDeclContext(SS, true);
  14883. if (!DC) {
  14884. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  14885. << SS.getRange();
  14886. return true;
  14887. }
  14888. }
  14889. if (RequireCompleteDeclContext(SS, DC))
  14890. return true;
  14891. SearchDC = DC;
  14892. // Look-up name inside 'foo::'.
  14893. LookupQualifiedName(Previous, DC);
  14894. if (Previous.isAmbiguous())
  14895. return true;
  14896. if (Previous.empty()) {
  14897. // Name lookup did not find anything. However, if the
  14898. // nested-name-specifier refers to the current instantiation,
  14899. // and that current instantiation has any dependent base
  14900. // classes, we might find something at instantiation time: treat
  14901. // this as a dependent elaborated-type-specifier.
  14902. // But this only makes any sense for reference-like lookups.
  14903. if (Previous.wasNotFoundInCurrentInstantiation() &&
  14904. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  14905. IsDependent = true;
  14906. return true;
  14907. }
  14908. // A tag 'foo::bar' must already exist.
  14909. Diag(NameLoc, diag::err_not_tag_in_scope)
  14910. << Kind << Name << DC << SS.getRange();
  14911. Name = nullptr;
  14912. Invalid = true;
  14913. goto CreateNewDecl;
  14914. }
  14915. } else if (Name) {
  14916. // C++14 [class.mem]p14:
  14917. // If T is the name of a class, then each of the following shall have a
  14918. // name different from T:
  14919. // -- every member of class T that is itself a type
  14920. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  14921. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  14922. return true;
  14923. // If this is a named struct, check to see if there was a previous forward
  14924. // declaration or definition.
  14925. // FIXME: We're looking into outer scopes here, even when we
  14926. // shouldn't be. Doing so can result in ambiguities that we
  14927. // shouldn't be diagnosing.
  14928. LookupName(Previous, S);
  14929. // When declaring or defining a tag, ignore ambiguities introduced
  14930. // by types using'ed into this scope.
  14931. if (Previous.isAmbiguous() &&
  14932. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  14933. LookupResult::Filter F = Previous.makeFilter();
  14934. while (F.hasNext()) {
  14935. NamedDecl *ND = F.next();
  14936. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  14937. SearchDC->getRedeclContext()))
  14938. F.erase();
  14939. }
  14940. F.done();
  14941. }
  14942. // C++11 [namespace.memdef]p3:
  14943. // If the name in a friend declaration is neither qualified nor
  14944. // a template-id and the declaration is a function or an
  14945. // elaborated-type-specifier, the lookup to determine whether
  14946. // the entity has been previously declared shall not consider
  14947. // any scopes outside the innermost enclosing namespace.
  14948. //
  14949. // MSVC doesn't implement the above rule for types, so a friend tag
  14950. // declaration may be a redeclaration of a type declared in an enclosing
  14951. // scope. They do implement this rule for friend functions.
  14952. //
  14953. // Does it matter that this should be by scope instead of by
  14954. // semantic context?
  14955. if (!Previous.empty() && TUK == TUK_Friend) {
  14956. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  14957. LookupResult::Filter F = Previous.makeFilter();
  14958. bool FriendSawTagOutsideEnclosingNamespace = false;
  14959. while (F.hasNext()) {
  14960. NamedDecl *ND = F.next();
  14961. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  14962. if (DC->isFileContext() &&
  14963. !EnclosingNS->Encloses(ND->getDeclContext())) {
  14964. if (getLangOpts().MSVCCompat)
  14965. FriendSawTagOutsideEnclosingNamespace = true;
  14966. else
  14967. F.erase();
  14968. }
  14969. }
  14970. F.done();
  14971. // Diagnose this MSVC extension in the easy case where lookup would have
  14972. // unambiguously found something outside the enclosing namespace.
  14973. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  14974. NamedDecl *ND = Previous.getFoundDecl();
  14975. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  14976. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  14977. }
  14978. }
  14979. // Note: there used to be some attempt at recovery here.
  14980. if (Previous.isAmbiguous())
  14981. return true;
  14982. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  14983. // FIXME: This makes sure that we ignore the contexts associated
  14984. // with C structs, unions, and enums when looking for a matching
  14985. // tag declaration or definition. See the similar lookup tweak
  14986. // in Sema::LookupName; is there a better way to deal with this?
  14987. while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC))
  14988. SearchDC = SearchDC->getParent();
  14989. } else if (getLangOpts().CPlusPlus) {
  14990. // Inside ObjCContainer want to keep it as a lexical decl context but go
  14991. // past it (most often to TranslationUnit) to find the semantic decl
  14992. // context.
  14993. while (isa<ObjCContainerDecl>(SearchDC))
  14994. SearchDC = SearchDC->getParent();
  14995. }
  14996. } else if (getLangOpts().CPlusPlus) {
  14997. // Don't use ObjCContainerDecl as the semantic decl context for anonymous
  14998. // TagDecl the same way as we skip it for named TagDecl.
  14999. while (isa<ObjCContainerDecl>(SearchDC))
  15000. SearchDC = SearchDC->getParent();
  15001. }
  15002. if (Previous.isSingleResult() &&
  15003. Previous.getFoundDecl()->isTemplateParameter()) {
  15004. // Maybe we will complain about the shadowed template parameter.
  15005. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  15006. // Just pretend that we didn't see the previous declaration.
  15007. Previous.clear();
  15008. }
  15009. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  15010. DC->Equals(getStdNamespace())) {
  15011. if (Name->isStr("bad_alloc")) {
  15012. // This is a declaration of or a reference to "std::bad_alloc".
  15013. isStdBadAlloc = true;
  15014. // If std::bad_alloc has been implicitly declared (but made invisible to
  15015. // name lookup), fill in this implicit declaration as the previous
  15016. // declaration, so that the declarations get chained appropriately.
  15017. if (Previous.empty() && StdBadAlloc)
  15018. Previous.addDecl(getStdBadAlloc());
  15019. } else if (Name->isStr("align_val_t")) {
  15020. isStdAlignValT = true;
  15021. if (Previous.empty() && StdAlignValT)
  15022. Previous.addDecl(getStdAlignValT());
  15023. }
  15024. }
  15025. // If we didn't find a previous declaration, and this is a reference
  15026. // (or friend reference), move to the correct scope. In C++, we
  15027. // also need to do a redeclaration lookup there, just in case
  15028. // there's a shadow friend decl.
  15029. if (Name && Previous.empty() &&
  15030. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  15031. if (Invalid) goto CreateNewDecl;
  15032. assert(SS.isEmpty());
  15033. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  15034. // C++ [basic.scope.pdecl]p5:
  15035. // -- for an elaborated-type-specifier of the form
  15036. //
  15037. // class-key identifier
  15038. //
  15039. // if the elaborated-type-specifier is used in the
  15040. // decl-specifier-seq or parameter-declaration-clause of a
  15041. // function defined in namespace scope, the identifier is
  15042. // declared as a class-name in the namespace that contains
  15043. // the declaration; otherwise, except as a friend
  15044. // declaration, the identifier is declared in the smallest
  15045. // non-class, non-function-prototype scope that contains the
  15046. // declaration.
  15047. //
  15048. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  15049. // C structs and unions.
  15050. //
  15051. // It is an error in C++ to declare (rather than define) an enum
  15052. // type, including via an elaborated type specifier. We'll
  15053. // diagnose that later; for now, declare the enum in the same
  15054. // scope as we would have picked for any other tag type.
  15055. //
  15056. // GNU C also supports this behavior as part of its incomplete
  15057. // enum types extension, while GNU C++ does not.
  15058. //
  15059. // Find the context where we'll be declaring the tag.
  15060. // FIXME: We would like to maintain the current DeclContext as the
  15061. // lexical context,
  15062. SearchDC = getTagInjectionContext(SearchDC);
  15063. // Find the scope where we'll be declaring the tag.
  15064. S = getTagInjectionScope(S, getLangOpts());
  15065. } else {
  15066. assert(TUK == TUK_Friend);
  15067. // C++ [namespace.memdef]p3:
  15068. // If a friend declaration in a non-local class first declares a
  15069. // class or function, the friend class or function is a member of
  15070. // the innermost enclosing namespace.
  15071. SearchDC = SearchDC->getEnclosingNamespaceContext();
  15072. }
  15073. // In C++, we need to do a redeclaration lookup to properly
  15074. // diagnose some problems.
  15075. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  15076. // hidden declaration so that we don't get ambiguity errors when using a
  15077. // type declared by an elaborated-type-specifier. In C that is not correct
  15078. // and we should instead merge compatible types found by lookup.
  15079. if (getLangOpts().CPlusPlus) {
  15080. // FIXME: This can perform qualified lookups into function contexts,
  15081. // which are meaningless.
  15082. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  15083. LookupQualifiedName(Previous, SearchDC);
  15084. } else {
  15085. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  15086. LookupName(Previous, S);
  15087. }
  15088. }
  15089. // If we have a known previous declaration to use, then use it.
  15090. if (Previous.empty() && SkipBody && SkipBody->Previous)
  15091. Previous.addDecl(SkipBody->Previous);
  15092. if (!Previous.empty()) {
  15093. NamedDecl *PrevDecl = Previous.getFoundDecl();
  15094. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  15095. // It's okay to have a tag decl in the same scope as a typedef
  15096. // which hides a tag decl in the same scope. Finding this
  15097. // with a redeclaration lookup can only actually happen in C++.
  15098. //
  15099. // This is also okay for elaborated-type-specifiers, which is
  15100. // technically forbidden by the current standard but which is
  15101. // okay according to the likely resolution of an open issue;
  15102. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  15103. if (getLangOpts().CPlusPlus) {
  15104. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  15105. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  15106. TagDecl *Tag = TT->getDecl();
  15107. if (Tag->getDeclName() == Name &&
  15108. Tag->getDeclContext()->getRedeclContext()
  15109. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  15110. PrevDecl = Tag;
  15111. Previous.clear();
  15112. Previous.addDecl(Tag);
  15113. Previous.resolveKind();
  15114. }
  15115. }
  15116. }
  15117. }
  15118. // If this is a redeclaration of a using shadow declaration, it must
  15119. // declare a tag in the same context. In MSVC mode, we allow a
  15120. // redefinition if either context is within the other.
  15121. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  15122. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  15123. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  15124. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  15125. !(OldTag && isAcceptableTagRedeclContext(
  15126. *this, OldTag->getDeclContext(), SearchDC))) {
  15127. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  15128. Diag(Shadow->getTargetDecl()->getLocation(),
  15129. diag::note_using_decl_target);
  15130. Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
  15131. << 0;
  15132. // Recover by ignoring the old declaration.
  15133. Previous.clear();
  15134. goto CreateNewDecl;
  15135. }
  15136. }
  15137. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  15138. // If this is a use of a previous tag, or if the tag is already declared
  15139. // in the same scope (so that the definition/declaration completes or
  15140. // rementions the tag), reuse the decl.
  15141. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  15142. isDeclInScope(DirectPrevDecl, SearchDC, S,
  15143. SS.isNotEmpty() || isMemberSpecialization)) {
  15144. // Make sure that this wasn't declared as an enum and now used as a
  15145. // struct or something similar.
  15146. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  15147. TUK == TUK_Definition, KWLoc,
  15148. Name)) {
  15149. bool SafeToContinue
  15150. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  15151. Kind != TTK_Enum);
  15152. if (SafeToContinue)
  15153. Diag(KWLoc, diag::err_use_with_wrong_tag)
  15154. << Name
  15155. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  15156. PrevTagDecl->getKindName());
  15157. else
  15158. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  15159. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  15160. if (SafeToContinue)
  15161. Kind = PrevTagDecl->getTagKind();
  15162. else {
  15163. // Recover by making this an anonymous redefinition.
  15164. Name = nullptr;
  15165. Previous.clear();
  15166. Invalid = true;
  15167. }
  15168. }
  15169. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  15170. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  15171. if (TUK == TUK_Reference || TUK == TUK_Friend)
  15172. return PrevTagDecl;
  15173. QualType EnumUnderlyingTy;
  15174. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  15175. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  15176. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  15177. EnumUnderlyingTy = QualType(T, 0);
  15178. // All conflicts with previous declarations are recovered by
  15179. // returning the previous declaration, unless this is a definition,
  15180. // in which case we want the caller to bail out.
  15181. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  15182. ScopedEnum, EnumUnderlyingTy,
  15183. IsFixed, PrevEnum))
  15184. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  15185. }
  15186. // C++11 [class.mem]p1:
  15187. // A member shall not be declared twice in the member-specification,
  15188. // except that a nested class or member class template can be declared
  15189. // and then later defined.
  15190. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  15191. S->isDeclScope(PrevDecl)) {
  15192. Diag(NameLoc, diag::ext_member_redeclared);
  15193. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  15194. }
  15195. if (!Invalid) {
  15196. // If this is a use, just return the declaration we found, unless
  15197. // we have attributes.
  15198. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  15199. if (!Attrs.empty()) {
  15200. // FIXME: Diagnose these attributes. For now, we create a new
  15201. // declaration to hold them.
  15202. } else if (TUK == TUK_Reference &&
  15203. (PrevTagDecl->getFriendObjectKind() ==
  15204. Decl::FOK_Undeclared ||
  15205. PrevDecl->getOwningModule() != getCurrentModule()) &&
  15206. SS.isEmpty()) {
  15207. // This declaration is a reference to an existing entity, but
  15208. // has different visibility from that entity: it either makes
  15209. // a friend visible or it makes a type visible in a new module.
  15210. // In either case, create a new declaration. We only do this if
  15211. // the declaration would have meant the same thing if no prior
  15212. // declaration were found, that is, if it was found in the same
  15213. // scope where we would have injected a declaration.
  15214. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  15215. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  15216. return PrevTagDecl;
  15217. // This is in the injected scope, create a new declaration in
  15218. // that scope.
  15219. S = getTagInjectionScope(S, getLangOpts());
  15220. } else {
  15221. return PrevTagDecl;
  15222. }
  15223. }
  15224. // Diagnose attempts to redefine a tag.
  15225. if (TUK == TUK_Definition) {
  15226. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  15227. // If we're defining a specialization and the previous definition
  15228. // is from an implicit instantiation, don't emit an error
  15229. // here; we'll catch this in the general case below.
  15230. bool IsExplicitSpecializationAfterInstantiation = false;
  15231. if (isMemberSpecialization) {
  15232. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  15233. IsExplicitSpecializationAfterInstantiation =
  15234. RD->getTemplateSpecializationKind() !=
  15235. TSK_ExplicitSpecialization;
  15236. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  15237. IsExplicitSpecializationAfterInstantiation =
  15238. ED->getTemplateSpecializationKind() !=
  15239. TSK_ExplicitSpecialization;
  15240. }
  15241. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  15242. // not keep more that one definition around (merge them). However,
  15243. // ensure the decl passes the structural compatibility check in
  15244. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  15245. NamedDecl *Hidden = nullptr;
  15246. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  15247. // There is a definition of this tag, but it is not visible. We
  15248. // explicitly make use of C++'s one definition rule here, and
  15249. // assume that this definition is identical to the hidden one
  15250. // we already have. Make the existing definition visible and
  15251. // use it in place of this one.
  15252. if (!getLangOpts().CPlusPlus) {
  15253. // Postpone making the old definition visible until after we
  15254. // complete parsing the new one and do the structural
  15255. // comparison.
  15256. SkipBody->CheckSameAsPrevious = true;
  15257. SkipBody->New = createTagFromNewDecl();
  15258. SkipBody->Previous = Def;
  15259. return Def;
  15260. } else {
  15261. SkipBody->ShouldSkip = true;
  15262. SkipBody->Previous = Def;
  15263. makeMergedDefinitionVisible(Hidden);
  15264. // Carry on and handle it like a normal definition. We'll
  15265. // skip starting the definitiion later.
  15266. }
  15267. } else if (!IsExplicitSpecializationAfterInstantiation) {
  15268. // A redeclaration in function prototype scope in C isn't
  15269. // visible elsewhere, so merely issue a warning.
  15270. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  15271. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  15272. else
  15273. Diag(NameLoc, diag::err_redefinition) << Name;
  15274. notePreviousDefinition(Def,
  15275. NameLoc.isValid() ? NameLoc : KWLoc);
  15276. // If this is a redefinition, recover by making this
  15277. // struct be anonymous, which will make any later
  15278. // references get the previous definition.
  15279. Name = nullptr;
  15280. Previous.clear();
  15281. Invalid = true;
  15282. }
  15283. } else {
  15284. // If the type is currently being defined, complain
  15285. // about a nested redefinition.
  15286. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  15287. if (TD->isBeingDefined()) {
  15288. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  15289. Diag(PrevTagDecl->getLocation(),
  15290. diag::note_previous_definition);
  15291. Name = nullptr;
  15292. Previous.clear();
  15293. Invalid = true;
  15294. }
  15295. }
  15296. // Okay, this is definition of a previously declared or referenced
  15297. // tag. We're going to create a new Decl for it.
  15298. }
  15299. // Okay, we're going to make a redeclaration. If this is some kind
  15300. // of reference, make sure we build the redeclaration in the same DC
  15301. // as the original, and ignore the current access specifier.
  15302. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  15303. SearchDC = PrevTagDecl->getDeclContext();
  15304. AS = AS_none;
  15305. }
  15306. }
  15307. // If we get here we have (another) forward declaration or we
  15308. // have a definition. Just create a new decl.
  15309. } else {
  15310. // If we get here, this is a definition of a new tag type in a nested
  15311. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  15312. // new decl/type. We set PrevDecl to NULL so that the entities
  15313. // have distinct types.
  15314. Previous.clear();
  15315. }
  15316. // If we get here, we're going to create a new Decl. If PrevDecl
  15317. // is non-NULL, it's a definition of the tag declared by
  15318. // PrevDecl. If it's NULL, we have a new definition.
  15319. // Otherwise, PrevDecl is not a tag, but was found with tag
  15320. // lookup. This is only actually possible in C++, where a few
  15321. // things like templates still live in the tag namespace.
  15322. } else {
  15323. // Use a better diagnostic if an elaborated-type-specifier
  15324. // found the wrong kind of type on the first
  15325. // (non-redeclaration) lookup.
  15326. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  15327. !Previous.isForRedeclaration()) {
  15328. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  15329. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  15330. << Kind;
  15331. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  15332. Invalid = true;
  15333. // Otherwise, only diagnose if the declaration is in scope.
  15334. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  15335. SS.isNotEmpty() || isMemberSpecialization)) {
  15336. // do nothing
  15337. // Diagnose implicit declarations introduced by elaborated types.
  15338. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  15339. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  15340. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  15341. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  15342. Invalid = true;
  15343. // Otherwise it's a declaration. Call out a particularly common
  15344. // case here.
  15345. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  15346. unsigned Kind = 0;
  15347. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  15348. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  15349. << Name << Kind << TND->getUnderlyingType();
  15350. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  15351. Invalid = true;
  15352. // Otherwise, diagnose.
  15353. } else {
  15354. // The tag name clashes with something else in the target scope,
  15355. // issue an error and recover by making this tag be anonymous.
  15356. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  15357. notePreviousDefinition(PrevDecl, NameLoc);
  15358. Name = nullptr;
  15359. Invalid = true;
  15360. }
  15361. // The existing declaration isn't relevant to us; we're in a
  15362. // new scope, so clear out the previous declaration.
  15363. Previous.clear();
  15364. }
  15365. }
  15366. CreateNewDecl:
  15367. TagDecl *PrevDecl = nullptr;
  15368. if (Previous.isSingleResult())
  15369. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  15370. // If there is an identifier, use the location of the identifier as the
  15371. // location of the decl, otherwise use the location of the struct/union
  15372. // keyword.
  15373. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  15374. // Otherwise, create a new declaration. If there is a previous
  15375. // declaration of the same entity, the two will be linked via
  15376. // PrevDecl.
  15377. TagDecl *New;
  15378. if (Kind == TTK_Enum) {
  15379. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  15380. // enum X { A, B, C } D; D should chain to X.
  15381. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  15382. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  15383. ScopedEnumUsesClassTag, IsFixed);
  15384. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  15385. StdAlignValT = cast<EnumDecl>(New);
  15386. // If this is an undefined enum, warn.
  15387. if (TUK != TUK_Definition && !Invalid) {
  15388. TagDecl *Def;
  15389. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  15390. // C++0x: 7.2p2: opaque-enum-declaration.
  15391. // Conflicts are diagnosed above. Do nothing.
  15392. }
  15393. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  15394. Diag(Loc, diag::ext_forward_ref_enum_def)
  15395. << New;
  15396. Diag(Def->getLocation(), diag::note_previous_definition);
  15397. } else {
  15398. unsigned DiagID = diag::ext_forward_ref_enum;
  15399. if (getLangOpts().MSVCCompat)
  15400. DiagID = diag::ext_ms_forward_ref_enum;
  15401. else if (getLangOpts().CPlusPlus)
  15402. DiagID = diag::err_forward_ref_enum;
  15403. Diag(Loc, DiagID);
  15404. }
  15405. }
  15406. if (EnumUnderlying) {
  15407. EnumDecl *ED = cast<EnumDecl>(New);
  15408. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  15409. ED->setIntegerTypeSourceInfo(TI);
  15410. else
  15411. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  15412. QualType EnumTy = ED->getIntegerType();
  15413. ED->setPromotionType(Context.isPromotableIntegerType(EnumTy)
  15414. ? Context.getPromotedIntegerType(EnumTy)
  15415. : EnumTy);
  15416. assert(ED->isComplete() && "enum with type should be complete");
  15417. }
  15418. } else {
  15419. // struct/union/class
  15420. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  15421. // struct X { int A; } D; D should chain to X.
  15422. if (getLangOpts().CPlusPlus) {
  15423. // FIXME: Look for a way to use RecordDecl for simple structs.
  15424. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  15425. cast_or_null<CXXRecordDecl>(PrevDecl));
  15426. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  15427. StdBadAlloc = cast<CXXRecordDecl>(New);
  15428. } else
  15429. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  15430. cast_or_null<RecordDecl>(PrevDecl));
  15431. }
  15432. if (OOK != OOK_Outside && TUK == TUK_Definition && !getLangOpts().CPlusPlus)
  15433. Diag(New->getLocation(), diag::ext_type_defined_in_offsetof)
  15434. << (OOK == OOK_Macro) << New->getSourceRange();
  15435. // C++11 [dcl.type]p3:
  15436. // A type-specifier-seq shall not define a class or enumeration [...].
  15437. if (!Invalid && getLangOpts().CPlusPlus &&
  15438. (IsTypeSpecifier || IsTemplateParamOrArg) && TUK == TUK_Definition) {
  15439. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  15440. << Context.getTagDeclType(New);
  15441. Invalid = true;
  15442. }
  15443. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  15444. DC->getDeclKind() == Decl::Enum) {
  15445. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  15446. << Context.getTagDeclType(New);
  15447. Invalid = true;
  15448. }
  15449. // Maybe add qualifier info.
  15450. if (SS.isNotEmpty()) {
  15451. if (SS.isSet()) {
  15452. // If this is either a declaration or a definition, check the
  15453. // nested-name-specifier against the current context.
  15454. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  15455. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  15456. isMemberSpecialization))
  15457. Invalid = true;
  15458. New->setQualifierInfo(SS.getWithLocInContext(Context));
  15459. if (TemplateParameterLists.size() > 0) {
  15460. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  15461. }
  15462. }
  15463. else
  15464. Invalid = true;
  15465. }
  15466. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  15467. // Add alignment attributes if necessary; these attributes are checked when
  15468. // the ASTContext lays out the structure.
  15469. //
  15470. // It is important for implementing the correct semantics that this
  15471. // happen here (in ActOnTag). The #pragma pack stack is
  15472. // maintained as a result of parser callbacks which can occur at
  15473. // many points during the parsing of a struct declaration (because
  15474. // the #pragma tokens are effectively skipped over during the
  15475. // parsing of the struct).
  15476. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  15477. AddAlignmentAttributesForRecord(RD);
  15478. AddMsStructLayoutForRecord(RD);
  15479. }
  15480. }
  15481. if (ModulePrivateLoc.isValid()) {
  15482. if (isMemberSpecialization)
  15483. Diag(New->getLocation(), diag::err_module_private_specialization)
  15484. << 2
  15485. << FixItHint::CreateRemoval(ModulePrivateLoc);
  15486. // __module_private__ does not apply to local classes. However, we only
  15487. // diagnose this as an error when the declaration specifiers are
  15488. // freestanding. Here, we just ignore the __module_private__.
  15489. else if (!SearchDC->isFunctionOrMethod())
  15490. New->setModulePrivate();
  15491. }
  15492. // If this is a specialization of a member class (of a class template),
  15493. // check the specialization.
  15494. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  15495. Invalid = true;
  15496. // If we're declaring or defining a tag in function prototype scope in C,
  15497. // note that this type can only be used within the function and add it to
  15498. // the list of decls to inject into the function definition scope.
  15499. if ((Name || Kind == TTK_Enum) &&
  15500. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  15501. if (getLangOpts().CPlusPlus) {
  15502. // C++ [dcl.fct]p6:
  15503. // Types shall not be defined in return or parameter types.
  15504. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  15505. Diag(Loc, diag::err_type_defined_in_param_type)
  15506. << Name;
  15507. Invalid = true;
  15508. }
  15509. } else if (!PrevDecl) {
  15510. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  15511. }
  15512. }
  15513. if (Invalid)
  15514. New->setInvalidDecl();
  15515. // Set the lexical context. If the tag has a C++ scope specifier, the
  15516. // lexical context will be different from the semantic context.
  15517. New->setLexicalDeclContext(CurContext);
  15518. // Mark this as a friend decl if applicable.
  15519. // In Microsoft mode, a friend declaration also acts as a forward
  15520. // declaration so we always pass true to setObjectOfFriendDecl to make
  15521. // the tag name visible.
  15522. if (TUK == TUK_Friend)
  15523. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  15524. // Set the access specifier.
  15525. if (!Invalid && SearchDC->isRecord())
  15526. SetMemberAccessSpecifier(New, PrevDecl, AS);
  15527. if (PrevDecl)
  15528. CheckRedeclarationInModule(New, PrevDecl);
  15529. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  15530. New->startDefinition();
  15531. ProcessDeclAttributeList(S, New, Attrs);
  15532. AddPragmaAttributes(S, New);
  15533. // If this has an identifier, add it to the scope stack.
  15534. if (TUK == TUK_Friend) {
  15535. // We might be replacing an existing declaration in the lookup tables;
  15536. // if so, borrow its access specifier.
  15537. if (PrevDecl)
  15538. New->setAccess(PrevDecl->getAccess());
  15539. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  15540. DC->makeDeclVisibleInContext(New);
  15541. if (Name) // can be null along some error paths
  15542. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  15543. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  15544. } else if (Name) {
  15545. S = getNonFieldDeclScope(S);
  15546. PushOnScopeChains(New, S, true);
  15547. } else {
  15548. CurContext->addDecl(New);
  15549. }
  15550. // If this is the C FILE type, notify the AST context.
  15551. if (IdentifierInfo *II = New->getIdentifier())
  15552. if (!New->isInvalidDecl() &&
  15553. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  15554. II->isStr("FILE"))
  15555. Context.setFILEDecl(New);
  15556. if (PrevDecl)
  15557. mergeDeclAttributes(New, PrevDecl);
  15558. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
  15559. inferGslOwnerPointerAttribute(CXXRD);
  15560. // If there's a #pragma GCC visibility in scope, set the visibility of this
  15561. // record.
  15562. AddPushedVisibilityAttribute(New);
  15563. if (isMemberSpecialization && !New->isInvalidDecl())
  15564. CompleteMemberSpecialization(New, Previous);
  15565. OwnedDecl = true;
  15566. // In C++, don't return an invalid declaration. We can't recover well from
  15567. // the cases where we make the type anonymous.
  15568. if (Invalid && getLangOpts().CPlusPlus) {
  15569. if (New->isBeingDefined())
  15570. if (auto RD = dyn_cast<RecordDecl>(New))
  15571. RD->completeDefinition();
  15572. return true;
  15573. } else if (SkipBody && SkipBody->ShouldSkip) {
  15574. return SkipBody->Previous;
  15575. } else {
  15576. return New;
  15577. }
  15578. }
  15579. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  15580. AdjustDeclIfTemplate(TagD);
  15581. TagDecl *Tag = cast<TagDecl>(TagD);
  15582. // Enter the tag context.
  15583. PushDeclContext(S, Tag);
  15584. ActOnDocumentableDecl(TagD);
  15585. // If there's a #pragma GCC visibility in scope, set the visibility of this
  15586. // record.
  15587. AddPushedVisibilityAttribute(Tag);
  15588. }
  15589. bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) {
  15590. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  15591. return false;
  15592. // Make the previous decl visible.
  15593. makeMergedDefinitionVisible(SkipBody.Previous);
  15594. return true;
  15595. }
  15596. void Sema::ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl) {
  15597. assert(IDecl->getLexicalParent() == CurContext &&
  15598. "The next DeclContext should be lexically contained in the current one.");
  15599. CurContext = IDecl;
  15600. }
  15601. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  15602. SourceLocation FinalLoc,
  15603. bool IsFinalSpelledSealed,
  15604. bool IsAbstract,
  15605. SourceLocation LBraceLoc) {
  15606. AdjustDeclIfTemplate(TagD);
  15607. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  15608. FieldCollector->StartClass();
  15609. if (!Record->getIdentifier())
  15610. return;
  15611. if (IsAbstract)
  15612. Record->markAbstract();
  15613. if (FinalLoc.isValid()) {
  15614. Record->addAttr(FinalAttr::Create(
  15615. Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
  15616. static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
  15617. }
  15618. // C++ [class]p2:
  15619. // [...] The class-name is also inserted into the scope of the
  15620. // class itself; this is known as the injected-class-name. For
  15621. // purposes of access checking, the injected-class-name is treated
  15622. // as if it were a public member name.
  15623. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  15624. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  15625. Record->getLocation(), Record->getIdentifier(),
  15626. /*PrevDecl=*/nullptr,
  15627. /*DelayTypeCreation=*/true);
  15628. Context.getTypeDeclType(InjectedClassName, Record);
  15629. InjectedClassName->setImplicit();
  15630. InjectedClassName->setAccess(AS_public);
  15631. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  15632. InjectedClassName->setDescribedClassTemplate(Template);
  15633. PushOnScopeChains(InjectedClassName, S);
  15634. assert(InjectedClassName->isInjectedClassName() &&
  15635. "Broken injected-class-name");
  15636. }
  15637. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  15638. SourceRange BraceRange) {
  15639. AdjustDeclIfTemplate(TagD);
  15640. TagDecl *Tag = cast<TagDecl>(TagD);
  15641. Tag->setBraceRange(BraceRange);
  15642. // Make sure we "complete" the definition even it is invalid.
  15643. if (Tag->isBeingDefined()) {
  15644. assert(Tag->isInvalidDecl() && "We should already have completed it");
  15645. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  15646. RD->completeDefinition();
  15647. }
  15648. if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  15649. FieldCollector->FinishClass();
  15650. if (RD->hasAttr<SYCLSpecialClassAttr>()) {
  15651. auto *Def = RD->getDefinition();
  15652. assert(Def && "The record is expected to have a completed definition");
  15653. unsigned NumInitMethods = 0;
  15654. for (auto *Method : Def->methods()) {
  15655. if (!Method->getIdentifier())
  15656. continue;
  15657. if (Method->getName() == "__init")
  15658. NumInitMethods++;
  15659. }
  15660. if (NumInitMethods > 1 || !Def->hasInitMethod())
  15661. Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
  15662. }
  15663. }
  15664. // Exit this scope of this tag's definition.
  15665. PopDeclContext();
  15666. if (getCurLexicalContext()->isObjCContainer() &&
  15667. Tag->getDeclContext()->isFileContext())
  15668. Tag->setTopLevelDeclInObjCContainer();
  15669. // Notify the consumer that we've defined a tag.
  15670. if (!Tag->isInvalidDecl())
  15671. Consumer.HandleTagDeclDefinition(Tag);
  15672. // Clangs implementation of #pragma align(packed) differs in bitfield layout
  15673. // from XLs and instead matches the XL #pragma pack(1) behavior.
  15674. if (Context.getTargetInfo().getTriple().isOSAIX() &&
  15675. AlignPackStack.hasValue()) {
  15676. AlignPackInfo APInfo = AlignPackStack.CurrentValue;
  15677. // Only diagnose #pragma align(packed).
  15678. if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
  15679. return;
  15680. const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
  15681. if (!RD)
  15682. return;
  15683. // Only warn if there is at least 1 bitfield member.
  15684. if (llvm::any_of(RD->fields(),
  15685. [](const FieldDecl *FD) { return FD->isBitField(); }))
  15686. Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
  15687. }
  15688. }
  15689. void Sema::ActOnObjCContainerFinishDefinition() {
  15690. // Exit this scope of this interface definition.
  15691. PopDeclContext();
  15692. }
  15693. void Sema::ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx) {
  15694. assert(ObjCCtx == CurContext && "Mismatch of container contexts");
  15695. OriginalLexicalContext = ObjCCtx;
  15696. ActOnObjCContainerFinishDefinition();
  15697. }
  15698. void Sema::ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx) {
  15699. ActOnObjCContainerStartDefinition(ObjCCtx);
  15700. OriginalLexicalContext = nullptr;
  15701. }
  15702. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  15703. AdjustDeclIfTemplate(TagD);
  15704. TagDecl *Tag = cast<TagDecl>(TagD);
  15705. Tag->setInvalidDecl();
  15706. // Make sure we "complete" the definition even it is invalid.
  15707. if (Tag->isBeingDefined()) {
  15708. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  15709. RD->completeDefinition();
  15710. }
  15711. // We're undoing ActOnTagStartDefinition here, not
  15712. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  15713. // the FieldCollector.
  15714. PopDeclContext();
  15715. }
  15716. // Note that FieldName may be null for anonymous bitfields.
  15717. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  15718. IdentifierInfo *FieldName, QualType FieldTy,
  15719. bool IsMsStruct, Expr *BitWidth) {
  15720. assert(BitWidth);
  15721. if (BitWidth->containsErrors())
  15722. return ExprError();
  15723. // C99 6.7.2.1p4 - verify the field type.
  15724. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  15725. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  15726. // Handle incomplete and sizeless types with a specific error.
  15727. if (RequireCompleteSizedType(FieldLoc, FieldTy,
  15728. diag::err_field_incomplete_or_sizeless))
  15729. return ExprError();
  15730. if (FieldName)
  15731. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  15732. << FieldName << FieldTy << BitWidth->getSourceRange();
  15733. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  15734. << FieldTy << BitWidth->getSourceRange();
  15735. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  15736. UPPC_BitFieldWidth))
  15737. return ExprError();
  15738. // If the bit-width is type- or value-dependent, don't try to check
  15739. // it now.
  15740. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  15741. return BitWidth;
  15742. llvm::APSInt Value;
  15743. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
  15744. if (ICE.isInvalid())
  15745. return ICE;
  15746. BitWidth = ICE.get();
  15747. // Zero-width bitfield is ok for anonymous field.
  15748. if (Value == 0 && FieldName)
  15749. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  15750. if (Value.isSigned() && Value.isNegative()) {
  15751. if (FieldName)
  15752. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  15753. << FieldName << toString(Value, 10);
  15754. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  15755. << toString(Value, 10);
  15756. }
  15757. // The size of the bit-field must not exceed our maximum permitted object
  15758. // size.
  15759. if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
  15760. return Diag(FieldLoc, diag::err_bitfield_too_wide)
  15761. << !FieldName << FieldName << toString(Value, 10);
  15762. }
  15763. if (!FieldTy->isDependentType()) {
  15764. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  15765. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  15766. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  15767. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  15768. // ABI.
  15769. bool CStdConstraintViolation =
  15770. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  15771. bool MSBitfieldViolation =
  15772. Value.ugt(TypeStorageSize) &&
  15773. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  15774. if (CStdConstraintViolation || MSBitfieldViolation) {
  15775. unsigned DiagWidth =
  15776. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  15777. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  15778. << (bool)FieldName << FieldName << toString(Value, 10)
  15779. << !CStdConstraintViolation << DiagWidth;
  15780. }
  15781. // Warn on types where the user might conceivably expect to get all
  15782. // specified bits as value bits: that's all integral types other than
  15783. // 'bool'.
  15784. if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
  15785. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  15786. << FieldName << toString(Value, 10)
  15787. << (unsigned)TypeWidth;
  15788. }
  15789. }
  15790. return BitWidth;
  15791. }
  15792. /// ActOnField - Each field of a C struct/union is passed into this in order
  15793. /// to create a FieldDecl object for it.
  15794. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  15795. Declarator &D, Expr *BitfieldWidth) {
  15796. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  15797. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  15798. /*InitStyle=*/ICIS_NoInit, AS_public);
  15799. return Res;
  15800. }
  15801. /// HandleField - Analyze a field of a C struct or a C++ data member.
  15802. ///
  15803. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  15804. SourceLocation DeclStart,
  15805. Declarator &D, Expr *BitWidth,
  15806. InClassInitStyle InitStyle,
  15807. AccessSpecifier AS) {
  15808. if (D.isDecompositionDeclarator()) {
  15809. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  15810. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  15811. << Decomp.getSourceRange();
  15812. return nullptr;
  15813. }
  15814. IdentifierInfo *II = D.getIdentifier();
  15815. SourceLocation Loc = DeclStart;
  15816. if (II) Loc = D.getIdentifierLoc();
  15817. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  15818. QualType T = TInfo->getType();
  15819. if (getLangOpts().CPlusPlus) {
  15820. CheckExtraCXXDefaultArguments(D);
  15821. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  15822. UPPC_DataMemberType)) {
  15823. D.setInvalidType();
  15824. T = Context.IntTy;
  15825. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  15826. }
  15827. }
  15828. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  15829. if (D.getDeclSpec().isInlineSpecified())
  15830. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  15831. << getLangOpts().CPlusPlus17;
  15832. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  15833. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  15834. diag::err_invalid_thread)
  15835. << DeclSpec::getSpecifierName(TSCS);
  15836. // Check to see if this name was declared as a member previously
  15837. NamedDecl *PrevDecl = nullptr;
  15838. LookupResult Previous(*this, II, Loc, LookupMemberName,
  15839. ForVisibleRedeclaration);
  15840. LookupName(Previous, S);
  15841. switch (Previous.getResultKind()) {
  15842. case LookupResult::Found:
  15843. case LookupResult::FoundUnresolvedValue:
  15844. PrevDecl = Previous.getAsSingle<NamedDecl>();
  15845. break;
  15846. case LookupResult::FoundOverloaded:
  15847. PrevDecl = Previous.getRepresentativeDecl();
  15848. break;
  15849. case LookupResult::NotFound:
  15850. case LookupResult::NotFoundInCurrentInstantiation:
  15851. case LookupResult::Ambiguous:
  15852. break;
  15853. }
  15854. Previous.suppressDiagnostics();
  15855. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  15856. // Maybe we will complain about the shadowed template parameter.
  15857. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  15858. // Just pretend that we didn't see the previous declaration.
  15859. PrevDecl = nullptr;
  15860. }
  15861. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  15862. PrevDecl = nullptr;
  15863. bool Mutable
  15864. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  15865. SourceLocation TSSL = D.getBeginLoc();
  15866. FieldDecl *NewFD
  15867. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  15868. TSSL, AS, PrevDecl, &D);
  15869. if (NewFD->isInvalidDecl())
  15870. Record->setInvalidDecl();
  15871. if (D.getDeclSpec().isModulePrivateSpecified())
  15872. NewFD->setModulePrivate();
  15873. if (NewFD->isInvalidDecl() && PrevDecl) {
  15874. // Don't introduce NewFD into scope; there's already something
  15875. // with the same name in the same scope.
  15876. } else if (II) {
  15877. PushOnScopeChains(NewFD, S);
  15878. } else
  15879. Record->addDecl(NewFD);
  15880. return NewFD;
  15881. }
  15882. /// Build a new FieldDecl and check its well-formedness.
  15883. ///
  15884. /// This routine builds a new FieldDecl given the fields name, type,
  15885. /// record, etc. \p PrevDecl should refer to any previous declaration
  15886. /// with the same name and in the same scope as the field to be
  15887. /// created.
  15888. ///
  15889. /// \returns a new FieldDecl.
  15890. ///
  15891. /// \todo The Declarator argument is a hack. It will be removed once
  15892. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  15893. TypeSourceInfo *TInfo,
  15894. RecordDecl *Record, SourceLocation Loc,
  15895. bool Mutable, Expr *BitWidth,
  15896. InClassInitStyle InitStyle,
  15897. SourceLocation TSSL,
  15898. AccessSpecifier AS, NamedDecl *PrevDecl,
  15899. Declarator *D) {
  15900. IdentifierInfo *II = Name.getAsIdentifierInfo();
  15901. bool InvalidDecl = false;
  15902. if (D) InvalidDecl = D->isInvalidType();
  15903. // If we receive a broken type, recover by assuming 'int' and
  15904. // marking this declaration as invalid.
  15905. if (T.isNull() || T->containsErrors()) {
  15906. InvalidDecl = true;
  15907. T = Context.IntTy;
  15908. }
  15909. QualType EltTy = Context.getBaseElementType(T);
  15910. if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
  15911. if (RequireCompleteSizedType(Loc, EltTy,
  15912. diag::err_field_incomplete_or_sizeless)) {
  15913. // Fields of incomplete type force their record to be invalid.
  15914. Record->setInvalidDecl();
  15915. InvalidDecl = true;
  15916. } else {
  15917. NamedDecl *Def;
  15918. EltTy->isIncompleteType(&Def);
  15919. if (Def && Def->isInvalidDecl()) {
  15920. Record->setInvalidDecl();
  15921. InvalidDecl = true;
  15922. }
  15923. }
  15924. }
  15925. // TR 18037 does not allow fields to be declared with address space
  15926. if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
  15927. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  15928. Diag(Loc, diag::err_field_with_address_space);
  15929. Record->setInvalidDecl();
  15930. InvalidDecl = true;
  15931. }
  15932. if (LangOpts.OpenCL) {
  15933. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  15934. // used as structure or union field: image, sampler, event or block types.
  15935. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  15936. T->isBlockPointerType()) {
  15937. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  15938. Record->setInvalidDecl();
  15939. InvalidDecl = true;
  15940. }
  15941. // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
  15942. // is enabled.
  15943. if (BitWidth && !getOpenCLOptions().isAvailableOption(
  15944. "__cl_clang_bitfields", LangOpts)) {
  15945. Diag(Loc, diag::err_opencl_bitfields);
  15946. InvalidDecl = true;
  15947. }
  15948. }
  15949. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  15950. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  15951. T.hasQualifiers()) {
  15952. InvalidDecl = true;
  15953. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  15954. }
  15955. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  15956. // than a variably modified type.
  15957. if (!InvalidDecl && T->isVariablyModifiedType()) {
  15958. if (!tryToFixVariablyModifiedVarType(
  15959. TInfo, T, Loc, diag::err_typecheck_field_variable_size))
  15960. InvalidDecl = true;
  15961. }
  15962. // Fields can not have abstract class types
  15963. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  15964. diag::err_abstract_type_in_decl,
  15965. AbstractFieldType))
  15966. InvalidDecl = true;
  15967. if (InvalidDecl)
  15968. BitWidth = nullptr;
  15969. // If this is declared as a bit-field, check the bit-field.
  15970. if (BitWidth) {
  15971. BitWidth =
  15972. VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth).get();
  15973. if (!BitWidth) {
  15974. InvalidDecl = true;
  15975. BitWidth = nullptr;
  15976. }
  15977. }
  15978. // Check that 'mutable' is consistent with the type of the declaration.
  15979. if (!InvalidDecl && Mutable) {
  15980. unsigned DiagID = 0;
  15981. if (T->isReferenceType())
  15982. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  15983. : diag::err_mutable_reference;
  15984. else if (T.isConstQualified())
  15985. DiagID = diag::err_mutable_const;
  15986. if (DiagID) {
  15987. SourceLocation ErrLoc = Loc;
  15988. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  15989. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  15990. Diag(ErrLoc, DiagID);
  15991. if (DiagID != diag::ext_mutable_reference) {
  15992. Mutable = false;
  15993. InvalidDecl = true;
  15994. }
  15995. }
  15996. }
  15997. // C++11 [class.union]p8 (DR1460):
  15998. // At most one variant member of a union may have a
  15999. // brace-or-equal-initializer.
  16000. if (InitStyle != ICIS_NoInit)
  16001. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  16002. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  16003. BitWidth, Mutable, InitStyle);
  16004. if (InvalidDecl)
  16005. NewFD->setInvalidDecl();
  16006. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  16007. Diag(Loc, diag::err_duplicate_member) << II;
  16008. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  16009. NewFD->setInvalidDecl();
  16010. }
  16011. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  16012. if (Record->isUnion()) {
  16013. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  16014. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  16015. if (RDecl->getDefinition()) {
  16016. // C++ [class.union]p1: An object of a class with a non-trivial
  16017. // constructor, a non-trivial copy constructor, a non-trivial
  16018. // destructor, or a non-trivial copy assignment operator
  16019. // cannot be a member of a union, nor can an array of such
  16020. // objects.
  16021. if (CheckNontrivialField(NewFD))
  16022. NewFD->setInvalidDecl();
  16023. }
  16024. }
  16025. // C++ [class.union]p1: If a union contains a member of reference type,
  16026. // the program is ill-formed, except when compiling with MSVC extensions
  16027. // enabled.
  16028. if (EltTy->isReferenceType()) {
  16029. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  16030. diag::ext_union_member_of_reference_type :
  16031. diag::err_union_member_of_reference_type)
  16032. << NewFD->getDeclName() << EltTy;
  16033. if (!getLangOpts().MicrosoftExt)
  16034. NewFD->setInvalidDecl();
  16035. }
  16036. }
  16037. }
  16038. // FIXME: We need to pass in the attributes given an AST
  16039. // representation, not a parser representation.
  16040. if (D) {
  16041. // FIXME: The current scope is almost... but not entirely... correct here.
  16042. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  16043. if (NewFD->hasAttrs())
  16044. CheckAlignasUnderalignment(NewFD);
  16045. }
  16046. // In auto-retain/release, infer strong retension for fields of
  16047. // retainable type.
  16048. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  16049. NewFD->setInvalidDecl();
  16050. if (T.isObjCGCWeak())
  16051. Diag(Loc, diag::warn_attribute_weak_on_field);
  16052. // PPC MMA non-pointer types are not allowed as field types.
  16053. if (Context.getTargetInfo().getTriple().isPPC64() &&
  16054. CheckPPCMMAType(T, NewFD->getLocation()))
  16055. NewFD->setInvalidDecl();
  16056. NewFD->setAccess(AS);
  16057. return NewFD;
  16058. }
  16059. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  16060. assert(FD);
  16061. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  16062. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  16063. return false;
  16064. QualType EltTy = Context.getBaseElementType(FD->getType());
  16065. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  16066. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  16067. if (RDecl->getDefinition()) {
  16068. // We check for copy constructors before constructors
  16069. // because otherwise we'll never get complaints about
  16070. // copy constructors.
  16071. CXXSpecialMember member = CXXInvalid;
  16072. // We're required to check for any non-trivial constructors. Since the
  16073. // implicit default constructor is suppressed if there are any
  16074. // user-declared constructors, we just need to check that there is a
  16075. // trivial default constructor and a trivial copy constructor. (We don't
  16076. // worry about move constructors here, since this is a C++98 check.)
  16077. if (RDecl->hasNonTrivialCopyConstructor())
  16078. member = CXXCopyConstructor;
  16079. else if (!RDecl->hasTrivialDefaultConstructor())
  16080. member = CXXDefaultConstructor;
  16081. else if (RDecl->hasNonTrivialCopyAssignment())
  16082. member = CXXCopyAssignment;
  16083. else if (RDecl->hasNonTrivialDestructor())
  16084. member = CXXDestructor;
  16085. if (member != CXXInvalid) {
  16086. if (!getLangOpts().CPlusPlus11 &&
  16087. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  16088. // Objective-C++ ARC: it is an error to have a non-trivial field of
  16089. // a union. However, system headers in Objective-C programs
  16090. // occasionally have Objective-C lifetime objects within unions,
  16091. // and rather than cause the program to fail, we make those
  16092. // members unavailable.
  16093. SourceLocation Loc = FD->getLocation();
  16094. if (getSourceManager().isInSystemHeader(Loc)) {
  16095. if (!FD->hasAttr<UnavailableAttr>())
  16096. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  16097. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  16098. return false;
  16099. }
  16100. }
  16101. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  16102. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  16103. diag::err_illegal_union_or_anon_struct_member)
  16104. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  16105. DiagnoseNontrivial(RDecl, member);
  16106. return !getLangOpts().CPlusPlus11;
  16107. }
  16108. }
  16109. }
  16110. return false;
  16111. }
  16112. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  16113. /// AST enum value.
  16114. static ObjCIvarDecl::AccessControl
  16115. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  16116. switch (ivarVisibility) {
  16117. default: llvm_unreachable("Unknown visitibility kind");
  16118. case tok::objc_private: return ObjCIvarDecl::Private;
  16119. case tok::objc_public: return ObjCIvarDecl::Public;
  16120. case tok::objc_protected: return ObjCIvarDecl::Protected;
  16121. case tok::objc_package: return ObjCIvarDecl::Package;
  16122. }
  16123. }
  16124. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  16125. /// in order to create an IvarDecl object for it.
  16126. Decl *Sema::ActOnIvar(Scope *S,
  16127. SourceLocation DeclStart,
  16128. Declarator &D, Expr *BitfieldWidth,
  16129. tok::ObjCKeywordKind Visibility) {
  16130. IdentifierInfo *II = D.getIdentifier();
  16131. Expr *BitWidth = (Expr*)BitfieldWidth;
  16132. SourceLocation Loc = DeclStart;
  16133. if (II) Loc = D.getIdentifierLoc();
  16134. // FIXME: Unnamed fields can be handled in various different ways, for
  16135. // example, unnamed unions inject all members into the struct namespace!
  16136. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  16137. QualType T = TInfo->getType();
  16138. if (BitWidth) {
  16139. // 6.7.2.1p3, 6.7.2.1p4
  16140. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  16141. if (!BitWidth)
  16142. D.setInvalidType();
  16143. } else {
  16144. // Not a bitfield.
  16145. // validate II.
  16146. }
  16147. if (T->isReferenceType()) {
  16148. Diag(Loc, diag::err_ivar_reference_type);
  16149. D.setInvalidType();
  16150. }
  16151. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  16152. // than a variably modified type.
  16153. else if (T->isVariablyModifiedType()) {
  16154. if (!tryToFixVariablyModifiedVarType(
  16155. TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
  16156. D.setInvalidType();
  16157. }
  16158. // Get the visibility (access control) for this ivar.
  16159. ObjCIvarDecl::AccessControl ac =
  16160. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  16161. : ObjCIvarDecl::None;
  16162. // Must set ivar's DeclContext to its enclosing interface.
  16163. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  16164. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  16165. return nullptr;
  16166. ObjCContainerDecl *EnclosingContext;
  16167. if (ObjCImplementationDecl *IMPDecl =
  16168. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  16169. if (LangOpts.ObjCRuntime.isFragile()) {
  16170. // Case of ivar declared in an implementation. Context is that of its class.
  16171. EnclosingContext = IMPDecl->getClassInterface();
  16172. assert(EnclosingContext && "Implementation has no class interface!");
  16173. }
  16174. else
  16175. EnclosingContext = EnclosingDecl;
  16176. } else {
  16177. if (ObjCCategoryDecl *CDecl =
  16178. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  16179. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  16180. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  16181. return nullptr;
  16182. }
  16183. }
  16184. EnclosingContext = EnclosingDecl;
  16185. }
  16186. // Construct the decl.
  16187. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  16188. DeclStart, Loc, II, T,
  16189. TInfo, ac, (Expr *)BitfieldWidth);
  16190. if (II) {
  16191. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  16192. ForVisibleRedeclaration);
  16193. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  16194. && !isa<TagDecl>(PrevDecl)) {
  16195. Diag(Loc, diag::err_duplicate_member) << II;
  16196. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  16197. NewID->setInvalidDecl();
  16198. }
  16199. }
  16200. // Process attributes attached to the ivar.
  16201. ProcessDeclAttributes(S, NewID, D);
  16202. if (D.isInvalidType())
  16203. NewID->setInvalidDecl();
  16204. // In ARC, infer 'retaining' for ivars of retainable type.
  16205. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  16206. NewID->setInvalidDecl();
  16207. if (D.getDeclSpec().isModulePrivateSpecified())
  16208. NewID->setModulePrivate();
  16209. if (II) {
  16210. // FIXME: When interfaces are DeclContexts, we'll need to add
  16211. // these to the interface.
  16212. S->AddDecl(NewID);
  16213. IdResolver.AddDecl(NewID);
  16214. }
  16215. if (LangOpts.ObjCRuntime.isNonFragile() &&
  16216. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  16217. Diag(Loc, diag::warn_ivars_in_interface);
  16218. return NewID;
  16219. }
  16220. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  16221. /// class and class extensions. For every class \@interface and class
  16222. /// extension \@interface, if the last ivar is a bitfield of any type,
  16223. /// then add an implicit `char :0` ivar to the end of that interface.
  16224. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  16225. SmallVectorImpl<Decl *> &AllIvarDecls) {
  16226. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  16227. return;
  16228. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  16229. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  16230. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  16231. return;
  16232. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  16233. if (!ID) {
  16234. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  16235. if (!CD->IsClassExtension())
  16236. return;
  16237. }
  16238. // No need to add this to end of @implementation.
  16239. else
  16240. return;
  16241. }
  16242. // All conditions are met. Add a new bitfield to the tail end of ivars.
  16243. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  16244. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  16245. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  16246. DeclLoc, DeclLoc, nullptr,
  16247. Context.CharTy,
  16248. Context.getTrivialTypeSourceInfo(Context.CharTy,
  16249. DeclLoc),
  16250. ObjCIvarDecl::Private, BW,
  16251. true);
  16252. AllIvarDecls.push_back(Ivar);
  16253. }
  16254. /// [class.dtor]p4:
  16255. /// At the end of the definition of a class, overload resolution is
  16256. /// performed among the prospective destructors declared in that class with
  16257. /// an empty argument list to select the destructor for the class, also
  16258. /// known as the selected destructor.
  16259. ///
  16260. /// We do the overload resolution here, then mark the selected constructor in the AST.
  16261. /// Later CXXRecordDecl::getDestructor() will return the selected constructor.
  16262. static void ComputeSelectedDestructor(Sema &S, CXXRecordDecl *Record) {
  16263. if (!Record->hasUserDeclaredDestructor()) {
  16264. return;
  16265. }
  16266. SourceLocation Loc = Record->getLocation();
  16267. OverloadCandidateSet OCS(Loc, OverloadCandidateSet::CSK_Normal);
  16268. for (auto *Decl : Record->decls()) {
  16269. if (auto *DD = dyn_cast<CXXDestructorDecl>(Decl)) {
  16270. if (DD->isInvalidDecl())
  16271. continue;
  16272. S.AddOverloadCandidate(DD, DeclAccessPair::make(DD, DD->getAccess()), {},
  16273. OCS);
  16274. assert(DD->isIneligibleOrNotSelected() && "Selecting a destructor but a destructor was already selected.");
  16275. }
  16276. }
  16277. if (OCS.empty()) {
  16278. return;
  16279. }
  16280. OverloadCandidateSet::iterator Best;
  16281. unsigned Msg = 0;
  16282. OverloadCandidateDisplayKind DisplayKind;
  16283. switch (OCS.BestViableFunction(S, Loc, Best)) {
  16284. case OR_Success:
  16285. case OR_Deleted:
  16286. Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(Best->Function));
  16287. break;
  16288. case OR_Ambiguous:
  16289. Msg = diag::err_ambiguous_destructor;
  16290. DisplayKind = OCD_AmbiguousCandidates;
  16291. break;
  16292. case OR_No_Viable_Function:
  16293. Msg = diag::err_no_viable_destructor;
  16294. DisplayKind = OCD_AllCandidates;
  16295. break;
  16296. }
  16297. if (Msg) {
  16298. // OpenCL have got their own thing going with destructors. It's slightly broken,
  16299. // but we allow it.
  16300. if (!S.LangOpts.OpenCL) {
  16301. PartialDiagnostic Diag = S.PDiag(Msg) << Record;
  16302. OCS.NoteCandidates(PartialDiagnosticAt(Loc, Diag), S, DisplayKind, {});
  16303. Record->setInvalidDecl();
  16304. }
  16305. // It's a bit hacky: At this point we've raised an error but we want the
  16306. // rest of the compiler to continue somehow working. However almost
  16307. // everything we'll try to do with the class will depend on there being a
  16308. // destructor. So let's pretend the first one is selected and hope for the
  16309. // best.
  16310. Record->addedSelectedDestructor(dyn_cast<CXXDestructorDecl>(OCS.begin()->Function));
  16311. }
  16312. }
  16313. /// [class.mem.special]p5
  16314. /// Two special member functions are of the same kind if:
  16315. /// - they are both default constructors,
  16316. /// - they are both copy or move constructors with the same first parameter
  16317. /// type, or
  16318. /// - they are both copy or move assignment operators with the same first
  16319. /// parameter type and the same cv-qualifiers and ref-qualifier, if any.
  16320. static bool AreSpecialMemberFunctionsSameKind(ASTContext &Context,
  16321. CXXMethodDecl *M1,
  16322. CXXMethodDecl *M2,
  16323. Sema::CXXSpecialMember CSM) {
  16324. // We don't want to compare templates to non-templates: See
  16325. // https://github.com/llvm/llvm-project/issues/59206
  16326. if (CSM == Sema::CXXDefaultConstructor)
  16327. return bool(M1->getDescribedFunctionTemplate()) ==
  16328. bool(M2->getDescribedFunctionTemplate());
  16329. if (!Context.hasSameType(M1->getParamDecl(0)->getType(),
  16330. M2->getParamDecl(0)->getType()))
  16331. return false;
  16332. if (!Context.hasSameType(M1->getThisType(), M2->getThisType()))
  16333. return false;
  16334. return true;
  16335. }
  16336. /// [class.mem.special]p6:
  16337. /// An eligible special member function is a special member function for which:
  16338. /// - the function is not deleted,
  16339. /// - the associated constraints, if any, are satisfied, and
  16340. /// - no special member function of the same kind whose associated constraints
  16341. /// [CWG2595], if any, are satisfied is more constrained.
  16342. static void SetEligibleMethods(Sema &S, CXXRecordDecl *Record,
  16343. ArrayRef<CXXMethodDecl *> Methods,
  16344. Sema::CXXSpecialMember CSM) {
  16345. SmallVector<bool, 4> SatisfactionStatus;
  16346. for (CXXMethodDecl *Method : Methods) {
  16347. const Expr *Constraints = Method->getTrailingRequiresClause();
  16348. if (!Constraints)
  16349. SatisfactionStatus.push_back(true);
  16350. else {
  16351. ConstraintSatisfaction Satisfaction;
  16352. if (S.CheckFunctionConstraints(Method, Satisfaction))
  16353. SatisfactionStatus.push_back(false);
  16354. else
  16355. SatisfactionStatus.push_back(Satisfaction.IsSatisfied);
  16356. }
  16357. }
  16358. for (size_t i = 0; i < Methods.size(); i++) {
  16359. if (!SatisfactionStatus[i])
  16360. continue;
  16361. CXXMethodDecl *Method = Methods[i];
  16362. CXXMethodDecl *OrigMethod = Method;
  16363. if (FunctionDecl *MF = OrigMethod->getInstantiatedFromMemberFunction())
  16364. OrigMethod = cast<CXXMethodDecl>(MF);
  16365. const Expr *Constraints = OrigMethod->getTrailingRequiresClause();
  16366. bool AnotherMethodIsMoreConstrained = false;
  16367. for (size_t j = 0; j < Methods.size(); j++) {
  16368. if (i == j || !SatisfactionStatus[j])
  16369. continue;
  16370. CXXMethodDecl *OtherMethod = Methods[j];
  16371. if (FunctionDecl *MF = OtherMethod->getInstantiatedFromMemberFunction())
  16372. OtherMethod = cast<CXXMethodDecl>(MF);
  16373. if (!AreSpecialMemberFunctionsSameKind(S.Context, OrigMethod, OtherMethod,
  16374. CSM))
  16375. continue;
  16376. const Expr *OtherConstraints = OtherMethod->getTrailingRequiresClause();
  16377. if (!OtherConstraints)
  16378. continue;
  16379. if (!Constraints) {
  16380. AnotherMethodIsMoreConstrained = true;
  16381. break;
  16382. }
  16383. if (S.IsAtLeastAsConstrained(OtherMethod, {OtherConstraints}, OrigMethod,
  16384. {Constraints},
  16385. AnotherMethodIsMoreConstrained)) {
  16386. // There was an error with the constraints comparison. Exit the loop
  16387. // and don't consider this function eligible.
  16388. AnotherMethodIsMoreConstrained = true;
  16389. }
  16390. if (AnotherMethodIsMoreConstrained)
  16391. break;
  16392. }
  16393. // FIXME: Do not consider deleted methods as eligible after implementing
  16394. // DR1734 and DR1496.
  16395. if (!AnotherMethodIsMoreConstrained) {
  16396. Method->setIneligibleOrNotSelected(false);
  16397. Record->addedEligibleSpecialMemberFunction(Method, 1 << CSM);
  16398. }
  16399. }
  16400. }
  16401. static void ComputeSpecialMemberFunctionsEligiblity(Sema &S,
  16402. CXXRecordDecl *Record) {
  16403. SmallVector<CXXMethodDecl *, 4> DefaultConstructors;
  16404. SmallVector<CXXMethodDecl *, 4> CopyConstructors;
  16405. SmallVector<CXXMethodDecl *, 4> MoveConstructors;
  16406. SmallVector<CXXMethodDecl *, 4> CopyAssignmentOperators;
  16407. SmallVector<CXXMethodDecl *, 4> MoveAssignmentOperators;
  16408. for (auto *Decl : Record->decls()) {
  16409. auto *MD = dyn_cast<CXXMethodDecl>(Decl);
  16410. if (!MD) {
  16411. auto *FTD = dyn_cast<FunctionTemplateDecl>(Decl);
  16412. if (FTD)
  16413. MD = dyn_cast<CXXMethodDecl>(FTD->getTemplatedDecl());
  16414. }
  16415. if (!MD)
  16416. continue;
  16417. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  16418. if (CD->isInvalidDecl())
  16419. continue;
  16420. if (CD->isDefaultConstructor())
  16421. DefaultConstructors.push_back(MD);
  16422. else if (CD->isCopyConstructor())
  16423. CopyConstructors.push_back(MD);
  16424. else if (CD->isMoveConstructor())
  16425. MoveConstructors.push_back(MD);
  16426. } else if (MD->isCopyAssignmentOperator()) {
  16427. CopyAssignmentOperators.push_back(MD);
  16428. } else if (MD->isMoveAssignmentOperator()) {
  16429. MoveAssignmentOperators.push_back(MD);
  16430. }
  16431. }
  16432. SetEligibleMethods(S, Record, DefaultConstructors,
  16433. Sema::CXXDefaultConstructor);
  16434. SetEligibleMethods(S, Record, CopyConstructors, Sema::CXXCopyConstructor);
  16435. SetEligibleMethods(S, Record, MoveConstructors, Sema::CXXMoveConstructor);
  16436. SetEligibleMethods(S, Record, CopyAssignmentOperators,
  16437. Sema::CXXCopyAssignment);
  16438. SetEligibleMethods(S, Record, MoveAssignmentOperators,
  16439. Sema::CXXMoveAssignment);
  16440. }
  16441. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  16442. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  16443. SourceLocation RBrac,
  16444. const ParsedAttributesView &Attrs) {
  16445. assert(EnclosingDecl && "missing record or interface decl");
  16446. // If this is an Objective-C @implementation or category and we have
  16447. // new fields here we should reset the layout of the interface since
  16448. // it will now change.
  16449. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  16450. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  16451. switch (DC->getKind()) {
  16452. default: break;
  16453. case Decl::ObjCCategory:
  16454. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  16455. break;
  16456. case Decl::ObjCImplementation:
  16457. Context.
  16458. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  16459. break;
  16460. }
  16461. }
  16462. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  16463. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  16464. // Start counting up the number of named members; make sure to include
  16465. // members of anonymous structs and unions in the total.
  16466. unsigned NumNamedMembers = 0;
  16467. if (Record) {
  16468. for (const auto *I : Record->decls()) {
  16469. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  16470. if (IFD->getDeclName())
  16471. ++NumNamedMembers;
  16472. }
  16473. }
  16474. // Verify that all the fields are okay.
  16475. SmallVector<FieldDecl*, 32> RecFields;
  16476. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  16477. i != end; ++i) {
  16478. FieldDecl *FD = cast<FieldDecl>(*i);
  16479. // Get the type for the field.
  16480. const Type *FDTy = FD->getType().getTypePtr();
  16481. if (!FD->isAnonymousStructOrUnion()) {
  16482. // Remember all fields written by the user.
  16483. RecFields.push_back(FD);
  16484. }
  16485. // If the field is already invalid for some reason, don't emit more
  16486. // diagnostics about it.
  16487. if (FD->isInvalidDecl()) {
  16488. EnclosingDecl->setInvalidDecl();
  16489. continue;
  16490. }
  16491. // C99 6.7.2.1p2:
  16492. // A structure or union shall not contain a member with
  16493. // incomplete or function type (hence, a structure shall not
  16494. // contain an instance of itself, but may contain a pointer to
  16495. // an instance of itself), except that the last member of a
  16496. // structure with more than one named member may have incomplete
  16497. // array type; such a structure (and any union containing,
  16498. // possibly recursively, a member that is such a structure)
  16499. // shall not be a member of a structure or an element of an
  16500. // array.
  16501. bool IsLastField = (i + 1 == Fields.end());
  16502. if (FDTy->isFunctionType()) {
  16503. // Field declared as a function.
  16504. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  16505. << FD->getDeclName();
  16506. FD->setInvalidDecl();
  16507. EnclosingDecl->setInvalidDecl();
  16508. continue;
  16509. } else if (FDTy->isIncompleteArrayType() &&
  16510. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  16511. if (Record) {
  16512. // Flexible array member.
  16513. // Microsoft and g++ is more permissive regarding flexible array.
  16514. // It will accept flexible array in union and also
  16515. // as the sole element of a struct/class.
  16516. unsigned DiagID = 0;
  16517. if (!Record->isUnion() && !IsLastField) {
  16518. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  16519. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  16520. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  16521. FD->setInvalidDecl();
  16522. EnclosingDecl->setInvalidDecl();
  16523. continue;
  16524. } else if (Record->isUnion())
  16525. DiagID = getLangOpts().MicrosoftExt
  16526. ? diag::ext_flexible_array_union_ms
  16527. : getLangOpts().CPlusPlus
  16528. ? diag::ext_flexible_array_union_gnu
  16529. : diag::err_flexible_array_union;
  16530. else if (NumNamedMembers < 1)
  16531. DiagID = getLangOpts().MicrosoftExt
  16532. ? diag::ext_flexible_array_empty_aggregate_ms
  16533. : getLangOpts().CPlusPlus
  16534. ? diag::ext_flexible_array_empty_aggregate_gnu
  16535. : diag::err_flexible_array_empty_aggregate;
  16536. if (DiagID)
  16537. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  16538. << Record->getTagKind();
  16539. // While the layout of types that contain virtual bases is not specified
  16540. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  16541. // virtual bases after the derived members. This would make a flexible
  16542. // array member declared at the end of an object not adjacent to the end
  16543. // of the type.
  16544. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  16545. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  16546. << FD->getDeclName() << Record->getTagKind();
  16547. if (!getLangOpts().C99)
  16548. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  16549. << FD->getDeclName() << Record->getTagKind();
  16550. // If the element type has a non-trivial destructor, we would not
  16551. // implicitly destroy the elements, so disallow it for now.
  16552. //
  16553. // FIXME: GCC allows this. We should probably either implicitly delete
  16554. // the destructor of the containing class, or just allow this.
  16555. QualType BaseElem = Context.getBaseElementType(FD->getType());
  16556. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  16557. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  16558. << FD->getDeclName() << FD->getType();
  16559. FD->setInvalidDecl();
  16560. EnclosingDecl->setInvalidDecl();
  16561. continue;
  16562. }
  16563. // Okay, we have a legal flexible array member at the end of the struct.
  16564. Record->setHasFlexibleArrayMember(true);
  16565. } else {
  16566. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  16567. // unless they are followed by another ivar. That check is done
  16568. // elsewhere, after synthesized ivars are known.
  16569. }
  16570. } else if (!FDTy->isDependentType() &&
  16571. RequireCompleteSizedType(
  16572. FD->getLocation(), FD->getType(),
  16573. diag::err_field_incomplete_or_sizeless)) {
  16574. // Incomplete type
  16575. FD->setInvalidDecl();
  16576. EnclosingDecl->setInvalidDecl();
  16577. continue;
  16578. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  16579. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  16580. // A type which contains a flexible array member is considered to be a
  16581. // flexible array member.
  16582. Record->setHasFlexibleArrayMember(true);
  16583. if (!Record->isUnion()) {
  16584. // If this is a struct/class and this is not the last element, reject
  16585. // it. Note that GCC supports variable sized arrays in the middle of
  16586. // structures.
  16587. if (!IsLastField)
  16588. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  16589. << FD->getDeclName() << FD->getType();
  16590. else {
  16591. // We support flexible arrays at the end of structs in
  16592. // other structs as an extension.
  16593. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  16594. << FD->getDeclName();
  16595. }
  16596. }
  16597. }
  16598. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  16599. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  16600. diag::err_abstract_type_in_decl,
  16601. AbstractIvarType)) {
  16602. // Ivars can not have abstract class types
  16603. FD->setInvalidDecl();
  16604. }
  16605. if (Record && FDTTy->getDecl()->hasObjectMember())
  16606. Record->setHasObjectMember(true);
  16607. if (Record && FDTTy->getDecl()->hasVolatileMember())
  16608. Record->setHasVolatileMember(true);
  16609. } else if (FDTy->isObjCObjectType()) {
  16610. /// A field cannot be an Objective-c object
  16611. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  16612. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  16613. QualType T = Context.getObjCObjectPointerType(FD->getType());
  16614. FD->setType(T);
  16615. } else if (Record && Record->isUnion() &&
  16616. FD->getType().hasNonTrivialObjCLifetime() &&
  16617. getSourceManager().isInSystemHeader(FD->getLocation()) &&
  16618. !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
  16619. (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
  16620. !Context.hasDirectOwnershipQualifier(FD->getType()))) {
  16621. // For backward compatibility, fields of C unions declared in system
  16622. // headers that have non-trivial ObjC ownership qualifications are marked
  16623. // as unavailable unless the qualifier is explicit and __strong. This can
  16624. // break ABI compatibility between programs compiled with ARC and MRR, but
  16625. // is a better option than rejecting programs using those unions under
  16626. // ARC.
  16627. FD->addAttr(UnavailableAttr::CreateImplicit(
  16628. Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
  16629. FD->getLocation()));
  16630. } else if (getLangOpts().ObjC &&
  16631. getLangOpts().getGC() != LangOptions::NonGC && Record &&
  16632. !Record->hasObjectMember()) {
  16633. if (FD->getType()->isObjCObjectPointerType() ||
  16634. FD->getType().isObjCGCStrong())
  16635. Record->setHasObjectMember(true);
  16636. else if (Context.getAsArrayType(FD->getType())) {
  16637. QualType BaseType = Context.getBaseElementType(FD->getType());
  16638. if (BaseType->isRecordType() &&
  16639. BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
  16640. Record->setHasObjectMember(true);
  16641. else if (BaseType->isObjCObjectPointerType() ||
  16642. BaseType.isObjCGCStrong())
  16643. Record->setHasObjectMember(true);
  16644. }
  16645. }
  16646. if (Record && !getLangOpts().CPlusPlus &&
  16647. !shouldIgnoreForRecordTriviality(FD)) {
  16648. QualType FT = FD->getType();
  16649. if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
  16650. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  16651. if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
  16652. Record->isUnion())
  16653. Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
  16654. }
  16655. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  16656. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
  16657. Record->setNonTrivialToPrimitiveCopy(true);
  16658. if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
  16659. Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
  16660. }
  16661. if (FT.isDestructedType()) {
  16662. Record->setNonTrivialToPrimitiveDestroy(true);
  16663. Record->setParamDestroyedInCallee(true);
  16664. if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
  16665. Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
  16666. }
  16667. if (const auto *RT = FT->getAs<RecordType>()) {
  16668. if (RT->getDecl()->getArgPassingRestrictions() ==
  16669. RecordDecl::APK_CanNeverPassInRegs)
  16670. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  16671. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  16672. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  16673. }
  16674. if (Record && FD->getType().isVolatileQualified())
  16675. Record->setHasVolatileMember(true);
  16676. // Keep track of the number of named members.
  16677. if (FD->getIdentifier())
  16678. ++NumNamedMembers;
  16679. }
  16680. // Okay, we successfully defined 'Record'.
  16681. if (Record) {
  16682. bool Completed = false;
  16683. if (CXXRecord) {
  16684. if (!CXXRecord->isInvalidDecl()) {
  16685. // Set access bits correctly on the directly-declared conversions.
  16686. for (CXXRecordDecl::conversion_iterator
  16687. I = CXXRecord->conversion_begin(),
  16688. E = CXXRecord->conversion_end(); I != E; ++I)
  16689. I.setAccess((*I)->getAccess());
  16690. }
  16691. // Add any implicitly-declared members to this class.
  16692. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  16693. if (!CXXRecord->isDependentType()) {
  16694. if (!CXXRecord->isInvalidDecl()) {
  16695. // If we have virtual base classes, we may end up finding multiple
  16696. // final overriders for a given virtual function. Check for this
  16697. // problem now.
  16698. if (CXXRecord->getNumVBases()) {
  16699. CXXFinalOverriderMap FinalOverriders;
  16700. CXXRecord->getFinalOverriders(FinalOverriders);
  16701. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  16702. MEnd = FinalOverriders.end();
  16703. M != MEnd; ++M) {
  16704. for (OverridingMethods::iterator SO = M->second.begin(),
  16705. SOEnd = M->second.end();
  16706. SO != SOEnd; ++SO) {
  16707. assert(SO->second.size() > 0 &&
  16708. "Virtual function without overriding functions?");
  16709. if (SO->second.size() == 1)
  16710. continue;
  16711. // C++ [class.virtual]p2:
  16712. // In a derived class, if a virtual member function of a base
  16713. // class subobject has more than one final overrider the
  16714. // program is ill-formed.
  16715. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  16716. << (const NamedDecl *)M->first << Record;
  16717. Diag(M->first->getLocation(),
  16718. diag::note_overridden_virtual_function);
  16719. for (OverridingMethods::overriding_iterator
  16720. OM = SO->second.begin(),
  16721. OMEnd = SO->second.end();
  16722. OM != OMEnd; ++OM)
  16723. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  16724. << (const NamedDecl *)M->first << OM->Method->getParent();
  16725. Record->setInvalidDecl();
  16726. }
  16727. }
  16728. CXXRecord->completeDefinition(&FinalOverriders);
  16729. Completed = true;
  16730. }
  16731. }
  16732. ComputeSelectedDestructor(*this, CXXRecord);
  16733. ComputeSpecialMemberFunctionsEligiblity(*this, CXXRecord);
  16734. }
  16735. }
  16736. if (!Completed)
  16737. Record->completeDefinition();
  16738. // Handle attributes before checking the layout.
  16739. ProcessDeclAttributeList(S, Record, Attrs);
  16740. // Check to see if a FieldDecl is a pointer to a function.
  16741. auto IsFunctionPointerOrForwardDecl = [&](const Decl *D) {
  16742. const FieldDecl *FD = dyn_cast<FieldDecl>(D);
  16743. if (!FD) {
  16744. // Check whether this is a forward declaration that was inserted by
  16745. // Clang. This happens when a non-forward declared / defined type is
  16746. // used, e.g.:
  16747. //
  16748. // struct foo {
  16749. // struct bar *(*f)();
  16750. // struct bar *(*g)();
  16751. // };
  16752. //
  16753. // "struct bar" shows up in the decl AST as a "RecordDecl" with an
  16754. // incomplete definition.
  16755. if (const auto *TD = dyn_cast<TagDecl>(D))
  16756. return !TD->isCompleteDefinition();
  16757. return false;
  16758. }
  16759. QualType FieldType = FD->getType().getDesugaredType(Context);
  16760. if (isa<PointerType>(FieldType)) {
  16761. QualType PointeeType = cast<PointerType>(FieldType)->getPointeeType();
  16762. return PointeeType.getDesugaredType(Context)->isFunctionType();
  16763. }
  16764. return false;
  16765. };
  16766. // Maybe randomize the record's decls. We automatically randomize a record
  16767. // of function pointers, unless it has the "no_randomize_layout" attribute.
  16768. if (!getLangOpts().CPlusPlus &&
  16769. (Record->hasAttr<RandomizeLayoutAttr>() ||
  16770. (!Record->hasAttr<NoRandomizeLayoutAttr>() &&
  16771. llvm::all_of(Record->decls(), IsFunctionPointerOrForwardDecl))) &&
  16772. !Record->isUnion() && !getLangOpts().RandstructSeed.empty() &&
  16773. !Record->isRandomized()) {
  16774. SmallVector<Decl *, 32> NewDeclOrdering;
  16775. if (randstruct::randomizeStructureLayout(Context, Record,
  16776. NewDeclOrdering))
  16777. Record->reorderDecls(NewDeclOrdering);
  16778. }
  16779. // We may have deferred checking for a deleted destructor. Check now.
  16780. if (CXXRecord) {
  16781. auto *Dtor = CXXRecord->getDestructor();
  16782. if (Dtor && Dtor->isImplicit() &&
  16783. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  16784. CXXRecord->setImplicitDestructorIsDeleted();
  16785. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  16786. }
  16787. }
  16788. if (Record->hasAttrs()) {
  16789. CheckAlignasUnderalignment(Record);
  16790. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  16791. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  16792. IA->getRange(), IA->getBestCase(),
  16793. IA->getInheritanceModel());
  16794. }
  16795. // Check if the structure/union declaration is a type that can have zero
  16796. // size in C. For C this is a language extension, for C++ it may cause
  16797. // compatibility problems.
  16798. bool CheckForZeroSize;
  16799. if (!getLangOpts().CPlusPlus) {
  16800. CheckForZeroSize = true;
  16801. } else {
  16802. // For C++ filter out types that cannot be referenced in C code.
  16803. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  16804. CheckForZeroSize =
  16805. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  16806. !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
  16807. CXXRecord->isCLike();
  16808. }
  16809. if (CheckForZeroSize) {
  16810. bool ZeroSize = true;
  16811. bool IsEmpty = true;
  16812. unsigned NonBitFields = 0;
  16813. for (RecordDecl::field_iterator I = Record->field_begin(),
  16814. E = Record->field_end();
  16815. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  16816. IsEmpty = false;
  16817. if (I->isUnnamedBitfield()) {
  16818. if (!I->isZeroLengthBitField(Context))
  16819. ZeroSize = false;
  16820. } else {
  16821. ++NonBitFields;
  16822. QualType FieldType = I->getType();
  16823. if (FieldType->isIncompleteType() ||
  16824. !Context.getTypeSizeInChars(FieldType).isZero())
  16825. ZeroSize = false;
  16826. }
  16827. }
  16828. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  16829. // allowed in C++, but warn if its declaration is inside
  16830. // extern "C" block.
  16831. if (ZeroSize) {
  16832. Diag(RecLoc, getLangOpts().CPlusPlus ?
  16833. diag::warn_zero_size_struct_union_in_extern_c :
  16834. diag::warn_zero_size_struct_union_compat)
  16835. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  16836. }
  16837. // Structs without named members are extension in C (C99 6.7.2.1p7),
  16838. // but are accepted by GCC.
  16839. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  16840. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  16841. diag::ext_no_named_members_in_struct_union)
  16842. << Record->isUnion();
  16843. }
  16844. }
  16845. } else {
  16846. ObjCIvarDecl **ClsFields =
  16847. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  16848. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  16849. ID->setEndOfDefinitionLoc(RBrac);
  16850. // Add ivar's to class's DeclContext.
  16851. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  16852. ClsFields[i]->setLexicalDeclContext(ID);
  16853. ID->addDecl(ClsFields[i]);
  16854. }
  16855. // Must enforce the rule that ivars in the base classes may not be
  16856. // duplicates.
  16857. if (ID->getSuperClass())
  16858. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  16859. } else if (ObjCImplementationDecl *IMPDecl =
  16860. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  16861. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  16862. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  16863. // Ivar declared in @implementation never belongs to the implementation.
  16864. // Only it is in implementation's lexical context.
  16865. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  16866. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  16867. IMPDecl->setIvarLBraceLoc(LBrac);
  16868. IMPDecl->setIvarRBraceLoc(RBrac);
  16869. } else if (ObjCCategoryDecl *CDecl =
  16870. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  16871. // case of ivars in class extension; all other cases have been
  16872. // reported as errors elsewhere.
  16873. // FIXME. Class extension does not have a LocEnd field.
  16874. // CDecl->setLocEnd(RBrac);
  16875. // Add ivar's to class extension's DeclContext.
  16876. // Diagnose redeclaration of private ivars.
  16877. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  16878. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  16879. if (IDecl) {
  16880. if (const ObjCIvarDecl *ClsIvar =
  16881. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  16882. Diag(ClsFields[i]->getLocation(),
  16883. diag::err_duplicate_ivar_declaration);
  16884. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  16885. continue;
  16886. }
  16887. for (const auto *Ext : IDecl->known_extensions()) {
  16888. if (const ObjCIvarDecl *ClsExtIvar
  16889. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  16890. Diag(ClsFields[i]->getLocation(),
  16891. diag::err_duplicate_ivar_declaration);
  16892. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  16893. continue;
  16894. }
  16895. }
  16896. }
  16897. ClsFields[i]->setLexicalDeclContext(CDecl);
  16898. CDecl->addDecl(ClsFields[i]);
  16899. }
  16900. CDecl->setIvarLBraceLoc(LBrac);
  16901. CDecl->setIvarRBraceLoc(RBrac);
  16902. }
  16903. }
  16904. }
  16905. /// Determine whether the given integral value is representable within
  16906. /// the given type T.
  16907. static bool isRepresentableIntegerValue(ASTContext &Context,
  16908. llvm::APSInt &Value,
  16909. QualType T) {
  16910. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  16911. "Integral type required!");
  16912. unsigned BitWidth = Context.getIntWidth(T);
  16913. if (Value.isUnsigned() || Value.isNonNegative()) {
  16914. if (T->isSignedIntegerOrEnumerationType())
  16915. --BitWidth;
  16916. return Value.getActiveBits() <= BitWidth;
  16917. }
  16918. return Value.getMinSignedBits() <= BitWidth;
  16919. }
  16920. // Given an integral type, return the next larger integral type
  16921. // (or a NULL type of no such type exists).
  16922. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  16923. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  16924. // enum checking below.
  16925. assert((T->isIntegralType(Context) ||
  16926. T->isEnumeralType()) && "Integral type required!");
  16927. const unsigned NumTypes = 4;
  16928. QualType SignedIntegralTypes[NumTypes] = {
  16929. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  16930. };
  16931. QualType UnsignedIntegralTypes[NumTypes] = {
  16932. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  16933. Context.UnsignedLongLongTy
  16934. };
  16935. unsigned BitWidth = Context.getTypeSize(T);
  16936. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  16937. : UnsignedIntegralTypes;
  16938. for (unsigned I = 0; I != NumTypes; ++I)
  16939. if (Context.getTypeSize(Types[I]) > BitWidth)
  16940. return Types[I];
  16941. return QualType();
  16942. }
  16943. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  16944. EnumConstantDecl *LastEnumConst,
  16945. SourceLocation IdLoc,
  16946. IdentifierInfo *Id,
  16947. Expr *Val) {
  16948. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  16949. llvm::APSInt EnumVal(IntWidth);
  16950. QualType EltTy;
  16951. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  16952. Val = nullptr;
  16953. if (Val)
  16954. Val = DefaultLvalueConversion(Val).get();
  16955. if (Val) {
  16956. if (Enum->isDependentType() || Val->isTypeDependent() ||
  16957. Val->containsErrors())
  16958. EltTy = Context.DependentTy;
  16959. else {
  16960. // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
  16961. // underlying type, but do allow it in all other contexts.
  16962. if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
  16963. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  16964. // constant-expression in the enumerator-definition shall be a converted
  16965. // constant expression of the underlying type.
  16966. EltTy = Enum->getIntegerType();
  16967. ExprResult Converted =
  16968. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  16969. CCEK_Enumerator);
  16970. if (Converted.isInvalid())
  16971. Val = nullptr;
  16972. else
  16973. Val = Converted.get();
  16974. } else if (!Val->isValueDependent() &&
  16975. !(Val =
  16976. VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
  16977. .get())) {
  16978. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  16979. } else {
  16980. if (Enum->isComplete()) {
  16981. EltTy = Enum->getIntegerType();
  16982. // In Obj-C and Microsoft mode, require the enumeration value to be
  16983. // representable in the underlying type of the enumeration. In C++11,
  16984. // we perform a non-narrowing conversion as part of converted constant
  16985. // expression checking.
  16986. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  16987. if (Context.getTargetInfo()
  16988. .getTriple()
  16989. .isWindowsMSVCEnvironment()) {
  16990. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  16991. } else {
  16992. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  16993. }
  16994. }
  16995. // Cast to the underlying type.
  16996. Val = ImpCastExprToType(Val, EltTy,
  16997. EltTy->isBooleanType() ? CK_IntegralToBoolean
  16998. : CK_IntegralCast)
  16999. .get();
  17000. } else if (getLangOpts().CPlusPlus) {
  17001. // C++11 [dcl.enum]p5:
  17002. // If the underlying type is not fixed, the type of each enumerator
  17003. // is the type of its initializing value:
  17004. // - If an initializer is specified for an enumerator, the
  17005. // initializing value has the same type as the expression.
  17006. EltTy = Val->getType();
  17007. } else {
  17008. // C99 6.7.2.2p2:
  17009. // The expression that defines the value of an enumeration constant
  17010. // shall be an integer constant expression that has a value
  17011. // representable as an int.
  17012. // Complain if the value is not representable in an int.
  17013. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  17014. Diag(IdLoc, diag::ext_enum_value_not_int)
  17015. << toString(EnumVal, 10) << Val->getSourceRange()
  17016. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  17017. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  17018. // Force the type of the expression to 'int'.
  17019. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  17020. }
  17021. EltTy = Val->getType();
  17022. }
  17023. }
  17024. }
  17025. }
  17026. if (!Val) {
  17027. if (Enum->isDependentType())
  17028. EltTy = Context.DependentTy;
  17029. else if (!LastEnumConst) {
  17030. // C++0x [dcl.enum]p5:
  17031. // If the underlying type is not fixed, the type of each enumerator
  17032. // is the type of its initializing value:
  17033. // - If no initializer is specified for the first enumerator, the
  17034. // initializing value has an unspecified integral type.
  17035. //
  17036. // GCC uses 'int' for its unspecified integral type, as does
  17037. // C99 6.7.2.2p3.
  17038. if (Enum->isFixed()) {
  17039. EltTy = Enum->getIntegerType();
  17040. }
  17041. else {
  17042. EltTy = Context.IntTy;
  17043. }
  17044. } else {
  17045. // Assign the last value + 1.
  17046. EnumVal = LastEnumConst->getInitVal();
  17047. ++EnumVal;
  17048. EltTy = LastEnumConst->getType();
  17049. // Check for overflow on increment.
  17050. if (EnumVal < LastEnumConst->getInitVal()) {
  17051. // C++0x [dcl.enum]p5:
  17052. // If the underlying type is not fixed, the type of each enumerator
  17053. // is the type of its initializing value:
  17054. //
  17055. // - Otherwise the type of the initializing value is the same as
  17056. // the type of the initializing value of the preceding enumerator
  17057. // unless the incremented value is not representable in that type,
  17058. // in which case the type is an unspecified integral type
  17059. // sufficient to contain the incremented value. If no such type
  17060. // exists, the program is ill-formed.
  17061. QualType T = getNextLargerIntegralType(Context, EltTy);
  17062. if (T.isNull() || Enum->isFixed()) {
  17063. // There is no integral type larger enough to represent this
  17064. // value. Complain, then allow the value to wrap around.
  17065. EnumVal = LastEnumConst->getInitVal();
  17066. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  17067. ++EnumVal;
  17068. if (Enum->isFixed())
  17069. // When the underlying type is fixed, this is ill-formed.
  17070. Diag(IdLoc, diag::err_enumerator_wrapped)
  17071. << toString(EnumVal, 10)
  17072. << EltTy;
  17073. else
  17074. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  17075. << toString(EnumVal, 10);
  17076. } else {
  17077. EltTy = T;
  17078. }
  17079. // Retrieve the last enumerator's value, extent that type to the
  17080. // type that is supposed to be large enough to represent the incremented
  17081. // value, then increment.
  17082. EnumVal = LastEnumConst->getInitVal();
  17083. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  17084. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  17085. ++EnumVal;
  17086. // If we're not in C++, diagnose the overflow of enumerator values,
  17087. // which in C99 means that the enumerator value is not representable in
  17088. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  17089. // permits enumerator values that are representable in some larger
  17090. // integral type.
  17091. if (!getLangOpts().CPlusPlus && !T.isNull())
  17092. Diag(IdLoc, diag::warn_enum_value_overflow);
  17093. } else if (!getLangOpts().CPlusPlus &&
  17094. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  17095. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  17096. Diag(IdLoc, diag::ext_enum_value_not_int)
  17097. << toString(EnumVal, 10) << 1;
  17098. }
  17099. }
  17100. }
  17101. if (!EltTy->isDependentType()) {
  17102. // Make the enumerator value match the signedness and size of the
  17103. // enumerator's type.
  17104. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  17105. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  17106. }
  17107. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  17108. Val, EnumVal);
  17109. }
  17110. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  17111. SourceLocation IILoc) {
  17112. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  17113. !getLangOpts().CPlusPlus)
  17114. return SkipBodyInfo();
  17115. // We have an anonymous enum definition. Look up the first enumerator to
  17116. // determine if we should merge the definition with an existing one and
  17117. // skip the body.
  17118. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  17119. forRedeclarationInCurContext());
  17120. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  17121. if (!PrevECD)
  17122. return SkipBodyInfo();
  17123. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  17124. NamedDecl *Hidden;
  17125. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  17126. SkipBodyInfo Skip;
  17127. Skip.Previous = Hidden;
  17128. return Skip;
  17129. }
  17130. return SkipBodyInfo();
  17131. }
  17132. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  17133. SourceLocation IdLoc, IdentifierInfo *Id,
  17134. const ParsedAttributesView &Attrs,
  17135. SourceLocation EqualLoc, Expr *Val) {
  17136. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  17137. EnumConstantDecl *LastEnumConst =
  17138. cast_or_null<EnumConstantDecl>(lastEnumConst);
  17139. // The scope passed in may not be a decl scope. Zip up the scope tree until
  17140. // we find one that is.
  17141. S = getNonFieldDeclScope(S);
  17142. // Verify that there isn't already something declared with this name in this
  17143. // scope.
  17144. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  17145. LookupName(R, S);
  17146. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  17147. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  17148. // Maybe we will complain about the shadowed template parameter.
  17149. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  17150. // Just pretend that we didn't see the previous declaration.
  17151. PrevDecl = nullptr;
  17152. }
  17153. // C++ [class.mem]p15:
  17154. // If T is the name of a class, then each of the following shall have a name
  17155. // different from T:
  17156. // - every enumerator of every member of class T that is an unscoped
  17157. // enumerated type
  17158. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  17159. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  17160. DeclarationNameInfo(Id, IdLoc));
  17161. EnumConstantDecl *New =
  17162. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  17163. if (!New)
  17164. return nullptr;
  17165. if (PrevDecl) {
  17166. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  17167. // Check for other kinds of shadowing not already handled.
  17168. CheckShadow(New, PrevDecl, R);
  17169. }
  17170. // When in C++, we may get a TagDecl with the same name; in this case the
  17171. // enum constant will 'hide' the tag.
  17172. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  17173. "Received TagDecl when not in C++!");
  17174. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  17175. if (isa<EnumConstantDecl>(PrevDecl))
  17176. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  17177. else
  17178. Diag(IdLoc, diag::err_redefinition) << Id;
  17179. notePreviousDefinition(PrevDecl, IdLoc);
  17180. return nullptr;
  17181. }
  17182. }
  17183. // Process attributes.
  17184. ProcessDeclAttributeList(S, New, Attrs);
  17185. AddPragmaAttributes(S, New);
  17186. // Register this decl in the current scope stack.
  17187. New->setAccess(TheEnumDecl->getAccess());
  17188. PushOnScopeChains(New, S);
  17189. ActOnDocumentableDecl(New);
  17190. return New;
  17191. }
  17192. // Returns true when the enum initial expression does not trigger the
  17193. // duplicate enum warning. A few common cases are exempted as follows:
  17194. // Element2 = Element1
  17195. // Element2 = Element1 + 1
  17196. // Element2 = Element1 - 1
  17197. // Where Element2 and Element1 are from the same enum.
  17198. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  17199. Expr *InitExpr = ECD->getInitExpr();
  17200. if (!InitExpr)
  17201. return true;
  17202. InitExpr = InitExpr->IgnoreImpCasts();
  17203. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  17204. if (!BO->isAdditiveOp())
  17205. return true;
  17206. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  17207. if (!IL)
  17208. return true;
  17209. if (IL->getValue() != 1)
  17210. return true;
  17211. InitExpr = BO->getLHS();
  17212. }
  17213. // This checks if the elements are from the same enum.
  17214. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  17215. if (!DRE)
  17216. return true;
  17217. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  17218. if (!EnumConstant)
  17219. return true;
  17220. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  17221. Enum)
  17222. return true;
  17223. return false;
  17224. }
  17225. // Emits a warning when an element is implicitly set a value that
  17226. // a previous element has already been set to.
  17227. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  17228. EnumDecl *Enum, QualType EnumType) {
  17229. // Avoid anonymous enums
  17230. if (!Enum->getIdentifier())
  17231. return;
  17232. // Only check for small enums.
  17233. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  17234. return;
  17235. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  17236. return;
  17237. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  17238. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  17239. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  17240. // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
  17241. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  17242. // Use int64_t as a key to avoid needing special handling for map keys.
  17243. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  17244. llvm::APSInt Val = D->getInitVal();
  17245. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  17246. };
  17247. DuplicatesVector DupVector;
  17248. ValueToVectorMap EnumMap;
  17249. // Populate the EnumMap with all values represented by enum constants without
  17250. // an initializer.
  17251. for (auto *Element : Elements) {
  17252. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  17253. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  17254. // this constant. Skip this enum since it may be ill-formed.
  17255. if (!ECD) {
  17256. return;
  17257. }
  17258. // Constants with initalizers are handled in the next loop.
  17259. if (ECD->getInitExpr())
  17260. continue;
  17261. // Duplicate values are handled in the next loop.
  17262. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  17263. }
  17264. if (EnumMap.size() == 0)
  17265. return;
  17266. // Create vectors for any values that has duplicates.
  17267. for (auto *Element : Elements) {
  17268. // The last loop returned if any constant was null.
  17269. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  17270. if (!ValidDuplicateEnum(ECD, Enum))
  17271. continue;
  17272. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  17273. if (Iter == EnumMap.end())
  17274. continue;
  17275. DeclOrVector& Entry = Iter->second;
  17276. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  17277. // Ensure constants are different.
  17278. if (D == ECD)
  17279. continue;
  17280. // Create new vector and push values onto it.
  17281. auto Vec = std::make_unique<ECDVector>();
  17282. Vec->push_back(D);
  17283. Vec->push_back(ECD);
  17284. // Update entry to point to the duplicates vector.
  17285. Entry = Vec.get();
  17286. // Store the vector somewhere we can consult later for quick emission of
  17287. // diagnostics.
  17288. DupVector.emplace_back(std::move(Vec));
  17289. continue;
  17290. }
  17291. ECDVector *Vec = Entry.get<ECDVector*>();
  17292. // Make sure constants are not added more than once.
  17293. if (*Vec->begin() == ECD)
  17294. continue;
  17295. Vec->push_back(ECD);
  17296. }
  17297. // Emit diagnostics.
  17298. for (const auto &Vec : DupVector) {
  17299. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  17300. // Emit warning for one enum constant.
  17301. auto *FirstECD = Vec->front();
  17302. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  17303. << FirstECD << toString(FirstECD->getInitVal(), 10)
  17304. << FirstECD->getSourceRange();
  17305. // Emit one note for each of the remaining enum constants with
  17306. // the same value.
  17307. for (auto *ECD : llvm::drop_begin(*Vec))
  17308. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  17309. << ECD << toString(ECD->getInitVal(), 10)
  17310. << ECD->getSourceRange();
  17311. }
  17312. }
  17313. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  17314. bool AllowMask) const {
  17315. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  17316. assert(ED->isCompleteDefinition() && "expected enum definition");
  17317. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  17318. llvm::APInt &FlagBits = R.first->second;
  17319. if (R.second) {
  17320. for (auto *E : ED->enumerators()) {
  17321. const auto &EVal = E->getInitVal();
  17322. // Only single-bit enumerators introduce new flag values.
  17323. if (EVal.isPowerOf2())
  17324. FlagBits = FlagBits.zext(EVal.getBitWidth()) | EVal;
  17325. }
  17326. }
  17327. // A value is in a flag enum if either its bits are a subset of the enum's
  17328. // flag bits (the first condition) or we are allowing masks and the same is
  17329. // true of its complement (the second condition). When masks are allowed, we
  17330. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  17331. //
  17332. // While it's true that any value could be used as a mask, the assumption is
  17333. // that a mask will have all of the insignificant bits set. Anything else is
  17334. // likely a logic error.
  17335. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  17336. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  17337. }
  17338. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  17339. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  17340. const ParsedAttributesView &Attrs) {
  17341. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  17342. QualType EnumType = Context.getTypeDeclType(Enum);
  17343. ProcessDeclAttributeList(S, Enum, Attrs);
  17344. if (Enum->isDependentType()) {
  17345. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  17346. EnumConstantDecl *ECD =
  17347. cast_or_null<EnumConstantDecl>(Elements[i]);
  17348. if (!ECD) continue;
  17349. ECD->setType(EnumType);
  17350. }
  17351. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  17352. return;
  17353. }
  17354. // TODO: If the result value doesn't fit in an int, it must be a long or long
  17355. // long value. ISO C does not support this, but GCC does as an extension,
  17356. // emit a warning.
  17357. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  17358. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  17359. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  17360. // Verify that all the values are okay, compute the size of the values, and
  17361. // reverse the list.
  17362. unsigned NumNegativeBits = 0;
  17363. unsigned NumPositiveBits = 0;
  17364. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  17365. EnumConstantDecl *ECD =
  17366. cast_or_null<EnumConstantDecl>(Elements[i]);
  17367. if (!ECD) continue; // Already issued a diagnostic.
  17368. const llvm::APSInt &InitVal = ECD->getInitVal();
  17369. // Keep track of the size of positive and negative values.
  17370. if (InitVal.isUnsigned() || InitVal.isNonNegative()) {
  17371. // If the enumerator is zero that should still be counted as a positive
  17372. // bit since we need a bit to store the value zero.
  17373. unsigned ActiveBits = InitVal.getActiveBits();
  17374. NumPositiveBits = std::max({NumPositiveBits, ActiveBits, 1u});
  17375. } else {
  17376. NumNegativeBits = std::max(NumNegativeBits,
  17377. (unsigned)InitVal.getMinSignedBits());
  17378. }
  17379. }
  17380. // If we have an empty set of enumerators we still need one bit.
  17381. // From [dcl.enum]p8
  17382. // If the enumerator-list is empty, the values of the enumeration are as if
  17383. // the enumeration had a single enumerator with value 0
  17384. if (!NumPositiveBits && !NumNegativeBits)
  17385. NumPositiveBits = 1;
  17386. // Figure out the type that should be used for this enum.
  17387. QualType BestType;
  17388. unsigned BestWidth;
  17389. // C++0x N3000 [conv.prom]p3:
  17390. // An rvalue of an unscoped enumeration type whose underlying
  17391. // type is not fixed can be converted to an rvalue of the first
  17392. // of the following types that can represent all the values of
  17393. // the enumeration: int, unsigned int, long int, unsigned long
  17394. // int, long long int, or unsigned long long int.
  17395. // C99 6.4.4.3p2:
  17396. // An identifier declared as an enumeration constant has type int.
  17397. // The C99 rule is modified by a gcc extension
  17398. QualType BestPromotionType;
  17399. bool Packed = Enum->hasAttr<PackedAttr>();
  17400. // -fshort-enums is the equivalent to specifying the packed attribute on all
  17401. // enum definitions.
  17402. if (LangOpts.ShortEnums)
  17403. Packed = true;
  17404. // If the enum already has a type because it is fixed or dictated by the
  17405. // target, promote that type instead of analyzing the enumerators.
  17406. if (Enum->isComplete()) {
  17407. BestType = Enum->getIntegerType();
  17408. if (Context.isPromotableIntegerType(BestType))
  17409. BestPromotionType = Context.getPromotedIntegerType(BestType);
  17410. else
  17411. BestPromotionType = BestType;
  17412. BestWidth = Context.getIntWidth(BestType);
  17413. }
  17414. else if (NumNegativeBits) {
  17415. // If there is a negative value, figure out the smallest integer type (of
  17416. // int/long/longlong) that fits.
  17417. // If it's packed, check also if it fits a char or a short.
  17418. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  17419. BestType = Context.SignedCharTy;
  17420. BestWidth = CharWidth;
  17421. } else if (Packed && NumNegativeBits <= ShortWidth &&
  17422. NumPositiveBits < ShortWidth) {
  17423. BestType = Context.ShortTy;
  17424. BestWidth = ShortWidth;
  17425. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  17426. BestType = Context.IntTy;
  17427. BestWidth = IntWidth;
  17428. } else {
  17429. BestWidth = Context.getTargetInfo().getLongWidth();
  17430. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  17431. BestType = Context.LongTy;
  17432. } else {
  17433. BestWidth = Context.getTargetInfo().getLongLongWidth();
  17434. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  17435. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  17436. BestType = Context.LongLongTy;
  17437. }
  17438. }
  17439. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  17440. } else {
  17441. // If there is no negative value, figure out the smallest type that fits
  17442. // all of the enumerator values.
  17443. // If it's packed, check also if it fits a char or a short.
  17444. if (Packed && NumPositiveBits <= CharWidth) {
  17445. BestType = Context.UnsignedCharTy;
  17446. BestPromotionType = Context.IntTy;
  17447. BestWidth = CharWidth;
  17448. } else if (Packed && NumPositiveBits <= ShortWidth) {
  17449. BestType = Context.UnsignedShortTy;
  17450. BestPromotionType = Context.IntTy;
  17451. BestWidth = ShortWidth;
  17452. } else if (NumPositiveBits <= IntWidth) {
  17453. BestType = Context.UnsignedIntTy;
  17454. BestWidth = IntWidth;
  17455. BestPromotionType
  17456. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  17457. ? Context.UnsignedIntTy : Context.IntTy;
  17458. } else if (NumPositiveBits <=
  17459. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  17460. BestType = Context.UnsignedLongTy;
  17461. BestPromotionType
  17462. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  17463. ? Context.UnsignedLongTy : Context.LongTy;
  17464. } else {
  17465. BestWidth = Context.getTargetInfo().getLongLongWidth();
  17466. assert(NumPositiveBits <= BestWidth &&
  17467. "How could an initializer get larger than ULL?");
  17468. BestType = Context.UnsignedLongLongTy;
  17469. BestPromotionType
  17470. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  17471. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  17472. }
  17473. }
  17474. // Loop over all of the enumerator constants, changing their types to match
  17475. // the type of the enum if needed.
  17476. for (auto *D : Elements) {
  17477. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  17478. if (!ECD) continue; // Already issued a diagnostic.
  17479. // Standard C says the enumerators have int type, but we allow, as an
  17480. // extension, the enumerators to be larger than int size. If each
  17481. // enumerator value fits in an int, type it as an int, otherwise type it the
  17482. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  17483. // that X has type 'int', not 'unsigned'.
  17484. // Determine whether the value fits into an int.
  17485. llvm::APSInt InitVal = ECD->getInitVal();
  17486. // If it fits into an integer type, force it. Otherwise force it to match
  17487. // the enum decl type.
  17488. QualType NewTy;
  17489. unsigned NewWidth;
  17490. bool NewSign;
  17491. if (!getLangOpts().CPlusPlus &&
  17492. !Enum->isFixed() &&
  17493. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  17494. NewTy = Context.IntTy;
  17495. NewWidth = IntWidth;
  17496. NewSign = true;
  17497. } else if (ECD->getType() == BestType) {
  17498. // Already the right type!
  17499. if (getLangOpts().CPlusPlus)
  17500. // C++ [dcl.enum]p4: Following the closing brace of an
  17501. // enum-specifier, each enumerator has the type of its
  17502. // enumeration.
  17503. ECD->setType(EnumType);
  17504. continue;
  17505. } else {
  17506. NewTy = BestType;
  17507. NewWidth = BestWidth;
  17508. NewSign = BestType->isSignedIntegerOrEnumerationType();
  17509. }
  17510. // Adjust the APSInt value.
  17511. InitVal = InitVal.extOrTrunc(NewWidth);
  17512. InitVal.setIsSigned(NewSign);
  17513. ECD->setInitVal(InitVal);
  17514. // Adjust the Expr initializer and type.
  17515. if (ECD->getInitExpr() &&
  17516. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  17517. ECD->setInitExpr(ImplicitCastExpr::Create(
  17518. Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
  17519. /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
  17520. if (getLangOpts().CPlusPlus)
  17521. // C++ [dcl.enum]p4: Following the closing brace of an
  17522. // enum-specifier, each enumerator has the type of its
  17523. // enumeration.
  17524. ECD->setType(EnumType);
  17525. else
  17526. ECD->setType(NewTy);
  17527. }
  17528. Enum->completeDefinition(BestType, BestPromotionType,
  17529. NumPositiveBits, NumNegativeBits);
  17530. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  17531. if (Enum->isClosedFlag()) {
  17532. for (Decl *D : Elements) {
  17533. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  17534. if (!ECD) continue; // Already issued a diagnostic.
  17535. llvm::APSInt InitVal = ECD->getInitVal();
  17536. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  17537. !IsValueInFlagEnum(Enum, InitVal, true))
  17538. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  17539. << ECD << Enum;
  17540. }
  17541. }
  17542. // Now that the enum type is defined, ensure it's not been underaligned.
  17543. if (Enum->hasAttrs())
  17544. CheckAlignasUnderalignment(Enum);
  17545. }
  17546. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  17547. SourceLocation StartLoc,
  17548. SourceLocation EndLoc) {
  17549. StringLiteral *AsmString = cast<StringLiteral>(expr);
  17550. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  17551. AsmString, StartLoc,
  17552. EndLoc);
  17553. CurContext->addDecl(New);
  17554. return New;
  17555. }
  17556. Decl *Sema::ActOnTopLevelStmtDecl(Stmt *Statement) {
  17557. auto *New = TopLevelStmtDecl::Create(Context, Statement);
  17558. Context.getTranslationUnitDecl()->addDecl(New);
  17559. return New;
  17560. }
  17561. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  17562. IdentifierInfo* AliasName,
  17563. SourceLocation PragmaLoc,
  17564. SourceLocation NameLoc,
  17565. SourceLocation AliasNameLoc) {
  17566. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  17567. LookupOrdinaryName);
  17568. AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
  17569. AttributeCommonInfo::AS_Pragma);
  17570. AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
  17571. Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
  17572. // If a declaration that:
  17573. // 1) declares a function or a variable
  17574. // 2) has external linkage
  17575. // already exists, add a label attribute to it.
  17576. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  17577. if (isDeclExternC(PrevDecl))
  17578. PrevDecl->addAttr(Attr);
  17579. else
  17580. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  17581. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  17582. // Otherwise, add a label attribute to ExtnameUndeclaredIdentifiers.
  17583. } else
  17584. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  17585. }
  17586. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  17587. SourceLocation PragmaLoc,
  17588. SourceLocation NameLoc) {
  17589. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  17590. if (PrevDecl) {
  17591. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
  17592. } else {
  17593. (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
  17594. }
  17595. }
  17596. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  17597. IdentifierInfo* AliasName,
  17598. SourceLocation PragmaLoc,
  17599. SourceLocation NameLoc,
  17600. SourceLocation AliasNameLoc) {
  17601. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  17602. LookupOrdinaryName);
  17603. WeakInfo W = WeakInfo(Name, NameLoc);
  17604. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  17605. if (!PrevDecl->hasAttr<AliasAttr>())
  17606. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  17607. DeclApplyPragmaWeak(TUScope, ND, W);
  17608. } else {
  17609. (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
  17610. }
  17611. }
  17612. ObjCContainerDecl *Sema::getObjCDeclContext() const {
  17613. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  17614. }
  17615. Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
  17616. bool Final) {
  17617. assert(FD && "Expected non-null FunctionDecl");
  17618. // SYCL functions can be template, so we check if they have appropriate
  17619. // attribute prior to checking if it is a template.
  17620. if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
  17621. return FunctionEmissionStatus::Emitted;
  17622. // Templates are emitted when they're instantiated.
  17623. if (FD->isDependentContext())
  17624. return FunctionEmissionStatus::TemplateDiscarded;
  17625. // Check whether this function is an externally visible definition.
  17626. auto IsEmittedForExternalSymbol = [this, FD]() {
  17627. // We have to check the GVA linkage of the function's *definition* -- if we
  17628. // only have a declaration, we don't know whether or not the function will
  17629. // be emitted, because (say) the definition could include "inline".
  17630. FunctionDecl *Def = FD->getDefinition();
  17631. return Def && !isDiscardableGVALinkage(
  17632. getASTContext().GetGVALinkageForFunction(Def));
  17633. };
  17634. if (LangOpts.OpenMPIsDevice) {
  17635. // In OpenMP device mode we will not emit host only functions, or functions
  17636. // we don't need due to their linkage.
  17637. std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  17638. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  17639. // DevTy may be changed later by
  17640. // #pragma omp declare target to(*) device_type(*).
  17641. // Therefore DevTy having no value does not imply host. The emission status
  17642. // will be checked again at the end of compilation unit with Final = true.
  17643. if (DevTy)
  17644. if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
  17645. return FunctionEmissionStatus::OMPDiscarded;
  17646. // If we have an explicit value for the device type, or we are in a target
  17647. // declare context, we need to emit all extern and used symbols.
  17648. if (isInOpenMPDeclareTargetContext() || DevTy)
  17649. if (IsEmittedForExternalSymbol())
  17650. return FunctionEmissionStatus::Emitted;
  17651. // Device mode only emits what it must, if it wasn't tagged yet and needed,
  17652. // we'll omit it.
  17653. if (Final)
  17654. return FunctionEmissionStatus::OMPDiscarded;
  17655. } else if (LangOpts.OpenMP > 45) {
  17656. // In OpenMP host compilation prior to 5.0 everything was an emitted host
  17657. // function. In 5.0, no_host was introduced which might cause a function to
  17658. // be ommitted.
  17659. std::optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
  17660. OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
  17661. if (DevTy)
  17662. if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
  17663. return FunctionEmissionStatus::OMPDiscarded;
  17664. }
  17665. if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
  17666. return FunctionEmissionStatus::Emitted;
  17667. if (LangOpts.CUDA) {
  17668. // When compiling for device, host functions are never emitted. Similarly,
  17669. // when compiling for host, device and global functions are never emitted.
  17670. // (Technically, we do emit a host-side stub for global functions, but this
  17671. // doesn't count for our purposes here.)
  17672. Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
  17673. if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
  17674. return FunctionEmissionStatus::CUDADiscarded;
  17675. if (!LangOpts.CUDAIsDevice &&
  17676. (T == Sema::CFT_Device || T == Sema::CFT_Global))
  17677. return FunctionEmissionStatus::CUDADiscarded;
  17678. if (IsEmittedForExternalSymbol())
  17679. return FunctionEmissionStatus::Emitted;
  17680. }
  17681. // Otherwise, the function is known-emitted if it's in our set of
  17682. // known-emitted functions.
  17683. return FunctionEmissionStatus::Unknown;
  17684. }
  17685. bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
  17686. // Host-side references to a __global__ function refer to the stub, so the
  17687. // function itself is never emitted and therefore should not be marked.
  17688. // If we have host fn calls kernel fn calls host+device, the HD function
  17689. // does not get instantiated on the host. We model this by omitting at the
  17690. // call to the kernel from the callgraph. This ensures that, when compiling
  17691. // for host, only HD functions actually called from the host get marked as
  17692. // known-emitted.
  17693. return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
  17694. IdentifyCUDATarget(Callee) == CFT_Global;
  17695. }