SemaDecl.cpp 673 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for declarations.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTLambda.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/CommentDiagnostic.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/EvaluatedExprVisitor.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/AST/StmtCXX.h"
  25. #include "clang/Basic/Builtins.h"
  26. #include "clang/Basic/PartialDiagnostic.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  30. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  31. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  32. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  33. #include "clang/Sema/CXXFieldCollector.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/DelayedDiagnostic.h"
  36. #include "clang/Sema/Initialization.h"
  37. #include "clang/Sema/Lookup.h"
  38. #include "clang/Sema/ParsedTemplate.h"
  39. #include "clang/Sema/Scope.h"
  40. #include "clang/Sema/ScopeInfo.h"
  41. #include "clang/Sema/SemaInternal.h"
  42. #include "clang/Sema/Template.h"
  43. #include "llvm/ADT/SmallString.h"
  44. #include "llvm/ADT/Triple.h"
  45. #include <algorithm>
  46. #include <cstring>
  47. #include <functional>
  48. using namespace clang;
  49. using namespace sema;
  50. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  51. if (OwnedType) {
  52. Decl *Group[2] = { OwnedType, Ptr };
  53. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  54. }
  55. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  56. }
  57. namespace {
  58. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  59. public:
  60. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  61. bool AllowTemplates = false,
  62. bool AllowNonTemplates = true)
  63. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  64. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  65. WantExpressionKeywords = false;
  66. WantCXXNamedCasts = false;
  67. WantRemainingKeywords = false;
  68. }
  69. bool ValidateCandidate(const TypoCorrection &candidate) override {
  70. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  71. if (!AllowInvalidDecl && ND->isInvalidDecl())
  72. return false;
  73. if (getAsTypeTemplateDecl(ND))
  74. return AllowTemplates;
  75. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  76. if (!IsType)
  77. return false;
  78. if (AllowNonTemplates)
  79. return true;
  80. // An injected-class-name of a class template (specialization) is valid
  81. // as a template or as a non-template.
  82. if (AllowTemplates) {
  83. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  84. if (!RD || !RD->isInjectedClassName())
  85. return false;
  86. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  87. return RD->getDescribedClassTemplate() ||
  88. isa<ClassTemplateSpecializationDecl>(RD);
  89. }
  90. return false;
  91. }
  92. return !WantClassName && candidate.isKeyword();
  93. }
  94. private:
  95. bool AllowInvalidDecl;
  96. bool WantClassName;
  97. bool AllowTemplates;
  98. bool AllowNonTemplates;
  99. };
  100. } // end anonymous namespace
  101. /// Determine whether the token kind starts a simple-type-specifier.
  102. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  103. switch (Kind) {
  104. // FIXME: Take into account the current language when deciding whether a
  105. // token kind is a valid type specifier
  106. case tok::kw_short:
  107. case tok::kw_long:
  108. case tok::kw___int64:
  109. case tok::kw___int128:
  110. case tok::kw_signed:
  111. case tok::kw_unsigned:
  112. case tok::kw_void:
  113. case tok::kw_char:
  114. case tok::kw_int:
  115. case tok::kw_half:
  116. case tok::kw_float:
  117. case tok::kw_double:
  118. case tok::kw__Float16:
  119. case tok::kw___float128:
  120. case tok::kw_wchar_t:
  121. case tok::kw_bool:
  122. case tok::kw___underlying_type:
  123. case tok::kw___auto_type:
  124. return true;
  125. case tok::annot_typename:
  126. case tok::kw_char16_t:
  127. case tok::kw_char32_t:
  128. case tok::kw_typeof:
  129. case tok::annot_decltype:
  130. case tok::kw_decltype:
  131. return getLangOpts().CPlusPlus;
  132. case tok::kw_char8_t:
  133. return getLangOpts().Char8;
  134. default:
  135. break;
  136. }
  137. return false;
  138. }
  139. namespace {
  140. enum class UnqualifiedTypeNameLookupResult {
  141. NotFound,
  142. FoundNonType,
  143. FoundType
  144. };
  145. } // end anonymous namespace
  146. /// Tries to perform unqualified lookup of the type decls in bases for
  147. /// dependent class.
  148. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  149. /// type decl, \a FoundType if only type decls are found.
  150. static UnqualifiedTypeNameLookupResult
  151. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  152. SourceLocation NameLoc,
  153. const CXXRecordDecl *RD) {
  154. if (!RD->hasDefinition())
  155. return UnqualifiedTypeNameLookupResult::NotFound;
  156. // Look for type decls in base classes.
  157. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  158. UnqualifiedTypeNameLookupResult::NotFound;
  159. for (const auto &Base : RD->bases()) {
  160. const CXXRecordDecl *BaseRD = nullptr;
  161. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  162. BaseRD = BaseTT->getAsCXXRecordDecl();
  163. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  164. // Look for type decls in dependent base classes that have known primary
  165. // templates.
  166. if (!TST || !TST->isDependentType())
  167. continue;
  168. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  169. if (!TD)
  170. continue;
  171. if (auto *BasePrimaryTemplate =
  172. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  173. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  174. BaseRD = BasePrimaryTemplate;
  175. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  176. if (const ClassTemplatePartialSpecializationDecl *PS =
  177. CTD->findPartialSpecialization(Base.getType()))
  178. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  179. BaseRD = PS;
  180. }
  181. }
  182. }
  183. if (BaseRD) {
  184. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  185. if (!isa<TypeDecl>(ND))
  186. return UnqualifiedTypeNameLookupResult::FoundNonType;
  187. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  188. }
  189. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  190. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  191. case UnqualifiedTypeNameLookupResult::FoundNonType:
  192. return UnqualifiedTypeNameLookupResult::FoundNonType;
  193. case UnqualifiedTypeNameLookupResult::FoundType:
  194. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  195. break;
  196. case UnqualifiedTypeNameLookupResult::NotFound:
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. return FoundTypeDecl;
  203. }
  204. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  205. const IdentifierInfo &II,
  206. SourceLocation NameLoc) {
  207. // Lookup in the parent class template context, if any.
  208. const CXXRecordDecl *RD = nullptr;
  209. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  210. UnqualifiedTypeNameLookupResult::NotFound;
  211. for (DeclContext *DC = S.CurContext;
  212. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  213. DC = DC->getParent()) {
  214. // Look for type decls in dependent base classes that have known primary
  215. // templates.
  216. RD = dyn_cast<CXXRecordDecl>(DC);
  217. if (RD && RD->getDescribedClassTemplate())
  218. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  219. }
  220. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  221. return nullptr;
  222. // We found some types in dependent base classes. Recover as if the user
  223. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  224. // lookup during template instantiation.
  225. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  226. ASTContext &Context = S.Context;
  227. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  228. cast<Type>(Context.getRecordType(RD)));
  229. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  230. CXXScopeSpec SS;
  231. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  232. TypeLocBuilder Builder;
  233. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  234. DepTL.setNameLoc(NameLoc);
  235. DepTL.setElaboratedKeywordLoc(SourceLocation());
  236. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  237. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  238. }
  239. /// If the identifier refers to a type name within this scope,
  240. /// return the declaration of that type.
  241. ///
  242. /// This routine performs ordinary name lookup of the identifier II
  243. /// within the given scope, with optional C++ scope specifier SS, to
  244. /// determine whether the name refers to a type. If so, returns an
  245. /// opaque pointer (actually a QualType) corresponding to that
  246. /// type. Otherwise, returns NULL.
  247. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  248. Scope *S, CXXScopeSpec *SS,
  249. bool isClassName, bool HasTrailingDot,
  250. ParsedType ObjectTypePtr,
  251. bool IsCtorOrDtorName,
  252. bool WantNontrivialTypeSourceInfo,
  253. bool IsClassTemplateDeductionContext,
  254. IdentifierInfo **CorrectedII) {
  255. // FIXME: Consider allowing this outside C++1z mode as an extension.
  256. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  257. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  258. !isClassName && !HasTrailingDot;
  259. // Determine where we will perform name lookup.
  260. DeclContext *LookupCtx = nullptr;
  261. if (ObjectTypePtr) {
  262. QualType ObjectType = ObjectTypePtr.get();
  263. if (ObjectType->isRecordType())
  264. LookupCtx = computeDeclContext(ObjectType);
  265. } else if (SS && SS->isNotEmpty()) {
  266. LookupCtx = computeDeclContext(*SS, false);
  267. if (!LookupCtx) {
  268. if (isDependentScopeSpecifier(*SS)) {
  269. // C++ [temp.res]p3:
  270. // A qualified-id that refers to a type and in which the
  271. // nested-name-specifier depends on a template-parameter (14.6.2)
  272. // shall be prefixed by the keyword typename to indicate that the
  273. // qualified-id denotes a type, forming an
  274. // elaborated-type-specifier (7.1.5.3).
  275. //
  276. // We therefore do not perform any name lookup if the result would
  277. // refer to a member of an unknown specialization.
  278. if (!isClassName && !IsCtorOrDtorName)
  279. return nullptr;
  280. // We know from the grammar that this name refers to a type,
  281. // so build a dependent node to describe the type.
  282. if (WantNontrivialTypeSourceInfo)
  283. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  284. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  285. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  286. II, NameLoc);
  287. return ParsedType::make(T);
  288. }
  289. return nullptr;
  290. }
  291. if (!LookupCtx->isDependentContext() &&
  292. RequireCompleteDeclContext(*SS, LookupCtx))
  293. return nullptr;
  294. }
  295. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  296. // lookup for class-names.
  297. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  298. LookupOrdinaryName;
  299. LookupResult Result(*this, &II, NameLoc, Kind);
  300. if (LookupCtx) {
  301. // Perform "qualified" name lookup into the declaration context we
  302. // computed, which is either the type of the base of a member access
  303. // expression or the declaration context associated with a prior
  304. // nested-name-specifier.
  305. LookupQualifiedName(Result, LookupCtx);
  306. if (ObjectTypePtr && Result.empty()) {
  307. // C++ [basic.lookup.classref]p3:
  308. // If the unqualified-id is ~type-name, the type-name is looked up
  309. // in the context of the entire postfix-expression. If the type T of
  310. // the object expression is of a class type C, the type-name is also
  311. // looked up in the scope of class C. At least one of the lookups shall
  312. // find a name that refers to (possibly cv-qualified) T.
  313. LookupName(Result, S);
  314. }
  315. } else {
  316. // Perform unqualified name lookup.
  317. LookupName(Result, S);
  318. // For unqualified lookup in a class template in MSVC mode, look into
  319. // dependent base classes where the primary class template is known.
  320. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  321. if (ParsedType TypeInBase =
  322. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  323. return TypeInBase;
  324. }
  325. }
  326. NamedDecl *IIDecl = nullptr;
  327. switch (Result.getResultKind()) {
  328. case LookupResult::NotFound:
  329. case LookupResult::NotFoundInCurrentInstantiation:
  330. if (CorrectedII) {
  331. TypoCorrection Correction =
  332. CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
  333. llvm::make_unique<TypeNameValidatorCCC>(
  334. true, isClassName, AllowDeducedTemplate),
  335. CTK_ErrorRecovery);
  336. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  337. TemplateTy Template;
  338. bool MemberOfUnknownSpecialization;
  339. UnqualifiedId TemplateName;
  340. TemplateName.setIdentifier(NewII, NameLoc);
  341. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  342. CXXScopeSpec NewSS, *NewSSPtr = SS;
  343. if (SS && NNS) {
  344. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  345. NewSSPtr = &NewSS;
  346. }
  347. if (Correction && (NNS || NewII != &II) &&
  348. // Ignore a correction to a template type as the to-be-corrected
  349. // identifier is not a template (typo correction for template names
  350. // is handled elsewhere).
  351. !(getLangOpts().CPlusPlus && NewSSPtr &&
  352. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  353. Template, MemberOfUnknownSpecialization))) {
  354. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  355. isClassName, HasTrailingDot, ObjectTypePtr,
  356. IsCtorOrDtorName,
  357. WantNontrivialTypeSourceInfo,
  358. IsClassTemplateDeductionContext);
  359. if (Ty) {
  360. diagnoseTypo(Correction,
  361. PDiag(diag::err_unknown_type_or_class_name_suggest)
  362. << Result.getLookupName() << isClassName);
  363. if (SS && NNS)
  364. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  365. *CorrectedII = NewII;
  366. return Ty;
  367. }
  368. }
  369. }
  370. // If typo correction failed or was not performed, fall through
  371. LLVM_FALLTHROUGH;
  372. case LookupResult::FoundOverloaded:
  373. case LookupResult::FoundUnresolvedValue:
  374. Result.suppressDiagnostics();
  375. return nullptr;
  376. case LookupResult::Ambiguous:
  377. // Recover from type-hiding ambiguities by hiding the type. We'll
  378. // do the lookup again when looking for an object, and we can
  379. // diagnose the error then. If we don't do this, then the error
  380. // about hiding the type will be immediately followed by an error
  381. // that only makes sense if the identifier was treated like a type.
  382. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  383. Result.suppressDiagnostics();
  384. return nullptr;
  385. }
  386. // Look to see if we have a type anywhere in the list of results.
  387. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  388. Res != ResEnd; ++Res) {
  389. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  390. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  391. if (!IIDecl ||
  392. (*Res)->getLocation().getRawEncoding() <
  393. IIDecl->getLocation().getRawEncoding())
  394. IIDecl = *Res;
  395. }
  396. }
  397. if (!IIDecl) {
  398. // None of the entities we found is a type, so there is no way
  399. // to even assume that the result is a type. In this case, don't
  400. // complain about the ambiguity. The parser will either try to
  401. // perform this lookup again (e.g., as an object name), which
  402. // will produce the ambiguity, or will complain that it expected
  403. // a type name.
  404. Result.suppressDiagnostics();
  405. return nullptr;
  406. }
  407. // We found a type within the ambiguous lookup; diagnose the
  408. // ambiguity and then return that type. This might be the right
  409. // answer, or it might not be, but it suppresses any attempt to
  410. // perform the name lookup again.
  411. break;
  412. case LookupResult::Found:
  413. IIDecl = Result.getFoundDecl();
  414. break;
  415. }
  416. assert(IIDecl && "Didn't find decl");
  417. QualType T;
  418. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  419. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  420. // instead names the constructors of the class, except when naming a class.
  421. // This is ill-formed when we're not actually forming a ctor or dtor name.
  422. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  423. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  424. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  425. FoundRD->isInjectedClassName() &&
  426. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  427. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  428. << &II << /*Type*/1;
  429. DiagnoseUseOfDecl(IIDecl, NameLoc);
  430. T = Context.getTypeDeclType(TD);
  431. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  432. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  433. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  434. if (!HasTrailingDot)
  435. T = Context.getObjCInterfaceType(IDecl);
  436. } else if (AllowDeducedTemplate) {
  437. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  438. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  439. QualType(), false);
  440. }
  441. if (T.isNull()) {
  442. // If it's not plausibly a type, suppress diagnostics.
  443. Result.suppressDiagnostics();
  444. return nullptr;
  445. }
  446. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  447. // constructor or destructor name (in such a case, the scope specifier
  448. // will be attached to the enclosing Expr or Decl node).
  449. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  450. !isa<ObjCInterfaceDecl>(IIDecl)) {
  451. if (WantNontrivialTypeSourceInfo) {
  452. // Construct a type with type-source information.
  453. TypeLocBuilder Builder;
  454. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  455. T = getElaboratedType(ETK_None, *SS, T);
  456. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  457. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  458. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  459. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  460. } else {
  461. T = getElaboratedType(ETK_None, *SS, T);
  462. }
  463. }
  464. return ParsedType::make(T);
  465. }
  466. // Builds a fake NNS for the given decl context.
  467. static NestedNameSpecifier *
  468. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  469. for (;; DC = DC->getLookupParent()) {
  470. DC = DC->getPrimaryContext();
  471. auto *ND = dyn_cast<NamespaceDecl>(DC);
  472. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  473. return NestedNameSpecifier::Create(Context, nullptr, ND);
  474. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  475. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  476. RD->getTypeForDecl());
  477. else if (isa<TranslationUnitDecl>(DC))
  478. return NestedNameSpecifier::GlobalSpecifier(Context);
  479. }
  480. llvm_unreachable("something isn't in TU scope?");
  481. }
  482. /// Find the parent class with dependent bases of the innermost enclosing method
  483. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  484. /// up allowing unqualified dependent type names at class-level, which MSVC
  485. /// correctly rejects.
  486. static const CXXRecordDecl *
  487. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  488. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  489. DC = DC->getPrimaryContext();
  490. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  491. if (MD->getParent()->hasAnyDependentBases())
  492. return MD->getParent();
  493. }
  494. return nullptr;
  495. }
  496. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  497. SourceLocation NameLoc,
  498. bool IsTemplateTypeArg) {
  499. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  500. NestedNameSpecifier *NNS = nullptr;
  501. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  502. // If we weren't able to parse a default template argument, delay lookup
  503. // until instantiation time by making a non-dependent DependentTypeName. We
  504. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  505. // lookup is retried.
  506. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  507. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  508. // name specifiers.
  509. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  510. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  511. } else if (const CXXRecordDecl *RD =
  512. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  513. // Build a DependentNameType that will perform lookup into RD at
  514. // instantiation time.
  515. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  516. RD->getTypeForDecl());
  517. // Diagnose that this identifier was undeclared, and retry the lookup during
  518. // template instantiation.
  519. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  520. << RD;
  521. } else {
  522. // This is not a situation that we should recover from.
  523. return ParsedType();
  524. }
  525. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  526. // Build type location information. We synthesized the qualifier, so we have
  527. // to build a fake NestedNameSpecifierLoc.
  528. NestedNameSpecifierLocBuilder NNSLocBuilder;
  529. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  530. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  531. TypeLocBuilder Builder;
  532. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  533. DepTL.setNameLoc(NameLoc);
  534. DepTL.setElaboratedKeywordLoc(SourceLocation());
  535. DepTL.setQualifierLoc(QualifierLoc);
  536. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  537. }
  538. /// isTagName() - This method is called *for error recovery purposes only*
  539. /// to determine if the specified name is a valid tag name ("struct foo"). If
  540. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  541. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  542. /// cases in C where the user forgot to specify the tag.
  543. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  544. // Do a tag name lookup in this scope.
  545. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  546. LookupName(R, S, false);
  547. R.suppressDiagnostics();
  548. if (R.getResultKind() == LookupResult::Found)
  549. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  550. switch (TD->getTagKind()) {
  551. case TTK_Struct: return DeclSpec::TST_struct;
  552. case TTK_Interface: return DeclSpec::TST_interface;
  553. case TTK_Union: return DeclSpec::TST_union;
  554. case TTK_Class: return DeclSpec::TST_class;
  555. case TTK_Enum: return DeclSpec::TST_enum;
  556. }
  557. }
  558. return DeclSpec::TST_unspecified;
  559. }
  560. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  561. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  562. /// then downgrade the missing typename error to a warning.
  563. /// This is needed for MSVC compatibility; Example:
  564. /// @code
  565. /// template<class T> class A {
  566. /// public:
  567. /// typedef int TYPE;
  568. /// };
  569. /// template<class T> class B : public A<T> {
  570. /// public:
  571. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  572. /// };
  573. /// @endcode
  574. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  575. if (CurContext->isRecord()) {
  576. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  577. return true;
  578. const Type *Ty = SS->getScopeRep()->getAsType();
  579. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  580. for (const auto &Base : RD->bases())
  581. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  582. return true;
  583. return S->isFunctionPrototypeScope();
  584. }
  585. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  586. }
  587. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  588. SourceLocation IILoc,
  589. Scope *S,
  590. CXXScopeSpec *SS,
  591. ParsedType &SuggestedType,
  592. bool IsTemplateName) {
  593. // Don't report typename errors for editor placeholders.
  594. if (II->isEditorPlaceholder())
  595. return;
  596. // We don't have anything to suggest (yet).
  597. SuggestedType = nullptr;
  598. // There may have been a typo in the name of the type. Look up typo
  599. // results, in case we have something that we can suggest.
  600. if (TypoCorrection Corrected =
  601. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  602. llvm::make_unique<TypeNameValidatorCCC>(
  603. false, false, IsTemplateName, !IsTemplateName),
  604. CTK_ErrorRecovery)) {
  605. // FIXME: Support error recovery for the template-name case.
  606. bool CanRecover = !IsTemplateName;
  607. if (Corrected.isKeyword()) {
  608. // We corrected to a keyword.
  609. diagnoseTypo(Corrected,
  610. PDiag(IsTemplateName ? diag::err_no_template_suggest
  611. : diag::err_unknown_typename_suggest)
  612. << II);
  613. II = Corrected.getCorrectionAsIdentifierInfo();
  614. } else {
  615. // We found a similarly-named type or interface; suggest that.
  616. if (!SS || !SS->isSet()) {
  617. diagnoseTypo(Corrected,
  618. PDiag(IsTemplateName ? diag::err_no_template_suggest
  619. : diag::err_unknown_typename_suggest)
  620. << II, CanRecover);
  621. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  622. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  623. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  624. II->getName().equals(CorrectedStr);
  625. diagnoseTypo(Corrected,
  626. PDiag(IsTemplateName
  627. ? diag::err_no_member_template_suggest
  628. : diag::err_unknown_nested_typename_suggest)
  629. << II << DC << DroppedSpecifier << SS->getRange(),
  630. CanRecover);
  631. } else {
  632. llvm_unreachable("could not have corrected a typo here");
  633. }
  634. if (!CanRecover)
  635. return;
  636. CXXScopeSpec tmpSS;
  637. if (Corrected.getCorrectionSpecifier())
  638. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  639. SourceRange(IILoc));
  640. // FIXME: Support class template argument deduction here.
  641. SuggestedType =
  642. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  643. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  644. /*IsCtorOrDtorName=*/false,
  645. /*NonTrivialTypeSourceInfo=*/true);
  646. }
  647. return;
  648. }
  649. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  650. // See if II is a class template that the user forgot to pass arguments to.
  651. UnqualifiedId Name;
  652. Name.setIdentifier(II, IILoc);
  653. CXXScopeSpec EmptySS;
  654. TemplateTy TemplateResult;
  655. bool MemberOfUnknownSpecialization;
  656. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  657. Name, nullptr, true, TemplateResult,
  658. MemberOfUnknownSpecialization) == TNK_Type_template) {
  659. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  660. return;
  661. }
  662. }
  663. // FIXME: Should we move the logic that tries to recover from a missing tag
  664. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  665. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  666. Diag(IILoc, IsTemplateName ? diag::err_no_template
  667. : diag::err_unknown_typename)
  668. << II;
  669. else if (DeclContext *DC = computeDeclContext(*SS, false))
  670. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  671. : diag::err_typename_nested_not_found)
  672. << II << DC << SS->getRange();
  673. else if (isDependentScopeSpecifier(*SS)) {
  674. unsigned DiagID = diag::err_typename_missing;
  675. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  676. DiagID = diag::ext_typename_missing;
  677. Diag(SS->getRange().getBegin(), DiagID)
  678. << SS->getScopeRep() << II->getName()
  679. << SourceRange(SS->getRange().getBegin(), IILoc)
  680. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  681. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  682. *SS, *II, IILoc).get();
  683. } else {
  684. assert(SS && SS->isInvalid() &&
  685. "Invalid scope specifier has already been diagnosed");
  686. }
  687. }
  688. /// Determine whether the given result set contains either a type name
  689. /// or
  690. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  691. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  692. NextToken.is(tok::less);
  693. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  694. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  695. return true;
  696. if (CheckTemplate && isa<TemplateDecl>(*I))
  697. return true;
  698. }
  699. return false;
  700. }
  701. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  702. Scope *S, CXXScopeSpec &SS,
  703. IdentifierInfo *&Name,
  704. SourceLocation NameLoc) {
  705. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  706. SemaRef.LookupParsedName(R, S, &SS);
  707. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  708. StringRef FixItTagName;
  709. switch (Tag->getTagKind()) {
  710. case TTK_Class:
  711. FixItTagName = "class ";
  712. break;
  713. case TTK_Enum:
  714. FixItTagName = "enum ";
  715. break;
  716. case TTK_Struct:
  717. FixItTagName = "struct ";
  718. break;
  719. case TTK_Interface:
  720. FixItTagName = "__interface ";
  721. break;
  722. case TTK_Union:
  723. FixItTagName = "union ";
  724. break;
  725. }
  726. StringRef TagName = FixItTagName.drop_back();
  727. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  728. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  729. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  730. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  731. I != IEnd; ++I)
  732. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  733. << Name << TagName;
  734. // Replace lookup results with just the tag decl.
  735. Result.clear(Sema::LookupTagName);
  736. SemaRef.LookupParsedName(Result, S, &SS);
  737. return true;
  738. }
  739. return false;
  740. }
  741. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  742. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  743. QualType T, SourceLocation NameLoc) {
  744. ASTContext &Context = S.Context;
  745. TypeLocBuilder Builder;
  746. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  747. T = S.getElaboratedType(ETK_None, SS, T);
  748. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  749. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  750. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  751. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  752. }
  753. Sema::NameClassification
  754. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  755. SourceLocation NameLoc, const Token &NextToken,
  756. bool IsAddressOfOperand,
  757. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  758. DeclarationNameInfo NameInfo(Name, NameLoc);
  759. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  760. if (NextToken.is(tok::coloncolon)) {
  761. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  762. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  763. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  764. isCurrentClassName(*Name, S, &SS)) {
  765. // Per [class.qual]p2, this names the constructors of SS, not the
  766. // injected-class-name. We don't have a classification for that.
  767. // There's not much point caching this result, since the parser
  768. // will reject it later.
  769. return NameClassification::Unknown();
  770. }
  771. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  772. LookupParsedName(Result, S, &SS, !CurMethod);
  773. // For unqualified lookup in a class template in MSVC mode, look into
  774. // dependent base classes where the primary class template is known.
  775. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  776. if (ParsedType TypeInBase =
  777. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  778. return TypeInBase;
  779. }
  780. // Perform lookup for Objective-C instance variables (including automatically
  781. // synthesized instance variables), if we're in an Objective-C method.
  782. // FIXME: This lookup really, really needs to be folded in to the normal
  783. // unqualified lookup mechanism.
  784. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  785. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  786. if (E.get() || E.isInvalid())
  787. return E;
  788. }
  789. bool SecondTry = false;
  790. bool IsFilteredTemplateName = false;
  791. Corrected:
  792. switch (Result.getResultKind()) {
  793. case LookupResult::NotFound:
  794. // If an unqualified-id is followed by a '(', then we have a function
  795. // call.
  796. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  797. // In C++, this is an ADL-only call.
  798. // FIXME: Reference?
  799. if (getLangOpts().CPlusPlus)
  800. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  801. // C90 6.3.2.2:
  802. // If the expression that precedes the parenthesized argument list in a
  803. // function call consists solely of an identifier, and if no
  804. // declaration is visible for this identifier, the identifier is
  805. // implicitly declared exactly as if, in the innermost block containing
  806. // the function call, the declaration
  807. //
  808. // extern int identifier ();
  809. //
  810. // appeared.
  811. //
  812. // We also allow this in C99 as an extension.
  813. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  814. Result.addDecl(D);
  815. Result.resolveKind();
  816. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  817. }
  818. }
  819. // In C, we first see whether there is a tag type by the same name, in
  820. // which case it's likely that the user just forgot to write "enum",
  821. // "struct", or "union".
  822. if (!getLangOpts().CPlusPlus && !SecondTry &&
  823. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  824. break;
  825. }
  826. // Perform typo correction to determine if there is another name that is
  827. // close to this name.
  828. if (!SecondTry && CCC) {
  829. SecondTry = true;
  830. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  831. Result.getLookupKind(), S,
  832. &SS, std::move(CCC),
  833. CTK_ErrorRecovery)) {
  834. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  835. unsigned QualifiedDiag = diag::err_no_member_suggest;
  836. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  837. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  838. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  839. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  840. UnqualifiedDiag = diag::err_no_template_suggest;
  841. QualifiedDiag = diag::err_no_member_template_suggest;
  842. } else if (UnderlyingFirstDecl &&
  843. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  844. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  845. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  846. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  847. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  848. }
  849. if (SS.isEmpty()) {
  850. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  851. } else {// FIXME: is this even reachable? Test it.
  852. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  853. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  854. Name->getName().equals(CorrectedStr);
  855. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  856. << Name << computeDeclContext(SS, false)
  857. << DroppedSpecifier << SS.getRange());
  858. }
  859. // Update the name, so that the caller has the new name.
  860. Name = Corrected.getCorrectionAsIdentifierInfo();
  861. // Typo correction corrected to a keyword.
  862. if (Corrected.isKeyword())
  863. return Name;
  864. // Also update the LookupResult...
  865. // FIXME: This should probably go away at some point
  866. Result.clear();
  867. Result.setLookupName(Corrected.getCorrection());
  868. if (FirstDecl)
  869. Result.addDecl(FirstDecl);
  870. // If we found an Objective-C instance variable, let
  871. // LookupInObjCMethod build the appropriate expression to
  872. // reference the ivar.
  873. // FIXME: This is a gross hack.
  874. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  875. Result.clear();
  876. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  877. return E;
  878. }
  879. goto Corrected;
  880. }
  881. }
  882. // We failed to correct; just fall through and let the parser deal with it.
  883. Result.suppressDiagnostics();
  884. return NameClassification::Unknown();
  885. case LookupResult::NotFoundInCurrentInstantiation: {
  886. // We performed name lookup into the current instantiation, and there were
  887. // dependent bases, so we treat this result the same way as any other
  888. // dependent nested-name-specifier.
  889. // C++ [temp.res]p2:
  890. // A name used in a template declaration or definition and that is
  891. // dependent on a template-parameter is assumed not to name a type
  892. // unless the applicable name lookup finds a type name or the name is
  893. // qualified by the keyword typename.
  894. //
  895. // FIXME: If the next token is '<', we might want to ask the parser to
  896. // perform some heroics to see if we actually have a
  897. // template-argument-list, which would indicate a missing 'template'
  898. // keyword here.
  899. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  900. NameInfo, IsAddressOfOperand,
  901. /*TemplateArgs=*/nullptr);
  902. }
  903. case LookupResult::Found:
  904. case LookupResult::FoundOverloaded:
  905. case LookupResult::FoundUnresolvedValue:
  906. break;
  907. case LookupResult::Ambiguous:
  908. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  909. hasAnyAcceptableTemplateNames(Result)) {
  910. // C++ [temp.local]p3:
  911. // A lookup that finds an injected-class-name (10.2) can result in an
  912. // ambiguity in certain cases (for example, if it is found in more than
  913. // one base class). If all of the injected-class-names that are found
  914. // refer to specializations of the same class template, and if the name
  915. // is followed by a template-argument-list, the reference refers to the
  916. // class template itself and not a specialization thereof, and is not
  917. // ambiguous.
  918. //
  919. // This filtering can make an ambiguous result into an unambiguous one,
  920. // so try again after filtering out template names.
  921. FilterAcceptableTemplateNames(Result);
  922. if (!Result.isAmbiguous()) {
  923. IsFilteredTemplateName = true;
  924. break;
  925. }
  926. }
  927. // Diagnose the ambiguity and return an error.
  928. return NameClassification::Error();
  929. }
  930. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  931. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  932. // C++ [temp.names]p3:
  933. // After name lookup (3.4) finds that a name is a template-name or that
  934. // an operator-function-id or a literal- operator-id refers to a set of
  935. // overloaded functions any member of which is a function template if
  936. // this is followed by a <, the < is always taken as the delimiter of a
  937. // template-argument-list and never as the less-than operator.
  938. if (!IsFilteredTemplateName)
  939. FilterAcceptableTemplateNames(Result);
  940. if (!Result.empty()) {
  941. bool IsFunctionTemplate;
  942. bool IsVarTemplate;
  943. TemplateName Template;
  944. if (Result.end() - Result.begin() > 1) {
  945. IsFunctionTemplate = true;
  946. Template = Context.getOverloadedTemplateName(Result.begin(),
  947. Result.end());
  948. } else {
  949. TemplateDecl *TD
  950. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  951. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  952. IsVarTemplate = isa<VarTemplateDecl>(TD);
  953. if (SS.isSet() && !SS.isInvalid())
  954. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  955. /*TemplateKeyword=*/false,
  956. TD);
  957. else
  958. Template = TemplateName(TD);
  959. }
  960. if (IsFunctionTemplate) {
  961. // Function templates always go through overload resolution, at which
  962. // point we'll perform the various checks (e.g., accessibility) we need
  963. // to based on which function we selected.
  964. Result.suppressDiagnostics();
  965. return NameClassification::FunctionTemplate(Template);
  966. }
  967. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  968. : NameClassification::TypeTemplate(Template);
  969. }
  970. }
  971. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  972. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  973. DiagnoseUseOfDecl(Type, NameLoc);
  974. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  975. QualType T = Context.getTypeDeclType(Type);
  976. if (SS.isNotEmpty())
  977. return buildNestedType(*this, SS, T, NameLoc);
  978. return ParsedType::make(T);
  979. }
  980. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  981. if (!Class) {
  982. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  983. if (ObjCCompatibleAliasDecl *Alias =
  984. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  985. Class = Alias->getClassInterface();
  986. }
  987. if (Class) {
  988. DiagnoseUseOfDecl(Class, NameLoc);
  989. if (NextToken.is(tok::period)) {
  990. // Interface. <something> is parsed as a property reference expression.
  991. // Just return "unknown" as a fall-through for now.
  992. Result.suppressDiagnostics();
  993. return NameClassification::Unknown();
  994. }
  995. QualType T = Context.getObjCInterfaceType(Class);
  996. return ParsedType::make(T);
  997. }
  998. // We can have a type template here if we're classifying a template argument.
  999. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1000. !isa<VarTemplateDecl>(FirstDecl))
  1001. return NameClassification::TypeTemplate(
  1002. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1003. // Check for a tag type hidden by a non-type decl in a few cases where it
  1004. // seems likely a type is wanted instead of the non-type that was found.
  1005. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1006. if ((NextToken.is(tok::identifier) ||
  1007. (NextIsOp &&
  1008. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1009. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1010. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1011. DiagnoseUseOfDecl(Type, NameLoc);
  1012. QualType T = Context.getTypeDeclType(Type);
  1013. if (SS.isNotEmpty())
  1014. return buildNestedType(*this, SS, T, NameLoc);
  1015. return ParsedType::make(T);
  1016. }
  1017. if (FirstDecl->isCXXClassMember())
  1018. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1019. nullptr, S);
  1020. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1021. return BuildDeclarationNameExpr(SS, Result, ADL);
  1022. }
  1023. Sema::TemplateNameKindForDiagnostics
  1024. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1025. auto *TD = Name.getAsTemplateDecl();
  1026. if (!TD)
  1027. return TemplateNameKindForDiagnostics::DependentTemplate;
  1028. if (isa<ClassTemplateDecl>(TD))
  1029. return TemplateNameKindForDiagnostics::ClassTemplate;
  1030. if (isa<FunctionTemplateDecl>(TD))
  1031. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1032. if (isa<VarTemplateDecl>(TD))
  1033. return TemplateNameKindForDiagnostics::VarTemplate;
  1034. if (isa<TypeAliasTemplateDecl>(TD))
  1035. return TemplateNameKindForDiagnostics::AliasTemplate;
  1036. if (isa<TemplateTemplateParmDecl>(TD))
  1037. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1038. return TemplateNameKindForDiagnostics::DependentTemplate;
  1039. }
  1040. // Determines the context to return to after temporarily entering a
  1041. // context. This depends in an unnecessarily complicated way on the
  1042. // exact ordering of callbacks from the parser.
  1043. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1044. // Functions defined inline within classes aren't parsed until we've
  1045. // finished parsing the top-level class, so the top-level class is
  1046. // the context we'll need to return to.
  1047. // A Lambda call operator whose parent is a class must not be treated
  1048. // as an inline member function. A Lambda can be used legally
  1049. // either as an in-class member initializer or a default argument. These
  1050. // are parsed once the class has been marked complete and so the containing
  1051. // context would be the nested class (when the lambda is defined in one);
  1052. // If the class is not complete, then the lambda is being used in an
  1053. // ill-formed fashion (such as to specify the width of a bit-field, or
  1054. // in an array-bound) - in which case we still want to return the
  1055. // lexically containing DC (which could be a nested class).
  1056. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1057. DC = DC->getLexicalParent();
  1058. // A function not defined within a class will always return to its
  1059. // lexical context.
  1060. if (!isa<CXXRecordDecl>(DC))
  1061. return DC;
  1062. // A C++ inline method/friend is parsed *after* the topmost class
  1063. // it was declared in is fully parsed ("complete"); the topmost
  1064. // class is the context we need to return to.
  1065. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1066. DC = RD;
  1067. // Return the declaration context of the topmost class the inline method is
  1068. // declared in.
  1069. return DC;
  1070. }
  1071. return DC->getLexicalParent();
  1072. }
  1073. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1074. assert(getContainingDC(DC) == CurContext &&
  1075. "The next DeclContext should be lexically contained in the current one.");
  1076. CurContext = DC;
  1077. S->setEntity(DC);
  1078. }
  1079. void Sema::PopDeclContext() {
  1080. assert(CurContext && "DeclContext imbalance!");
  1081. CurContext = getContainingDC(CurContext);
  1082. assert(CurContext && "Popped translation unit!");
  1083. }
  1084. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1085. Decl *D) {
  1086. // Unlike PushDeclContext, the context to which we return is not necessarily
  1087. // the containing DC of TD, because the new context will be some pre-existing
  1088. // TagDecl definition instead of a fresh one.
  1089. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1090. CurContext = cast<TagDecl>(D)->getDefinition();
  1091. assert(CurContext && "skipping definition of undefined tag");
  1092. // Start lookups from the parent of the current context; we don't want to look
  1093. // into the pre-existing complete definition.
  1094. S->setEntity(CurContext->getLookupParent());
  1095. return Result;
  1096. }
  1097. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1098. CurContext = static_cast<decltype(CurContext)>(Context);
  1099. }
  1100. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1101. /// of a declarator's nested name specifier.
  1102. ///
  1103. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1104. // C++0x [basic.lookup.unqual]p13:
  1105. // A name used in the definition of a static data member of class
  1106. // X (after the qualified-id of the static member) is looked up as
  1107. // if the name was used in a member function of X.
  1108. // C++0x [basic.lookup.unqual]p14:
  1109. // If a variable member of a namespace is defined outside of the
  1110. // scope of its namespace then any name used in the definition of
  1111. // the variable member (after the declarator-id) is looked up as
  1112. // if the definition of the variable member occurred in its
  1113. // namespace.
  1114. // Both of these imply that we should push a scope whose context
  1115. // is the semantic context of the declaration. We can't use
  1116. // PushDeclContext here because that context is not necessarily
  1117. // lexically contained in the current context. Fortunately,
  1118. // the containing scope should have the appropriate information.
  1119. assert(!S->getEntity() && "scope already has entity");
  1120. #ifndef NDEBUG
  1121. Scope *Ancestor = S->getParent();
  1122. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1123. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1124. #endif
  1125. CurContext = DC;
  1126. S->setEntity(DC);
  1127. }
  1128. void Sema::ExitDeclaratorContext(Scope *S) {
  1129. assert(S->getEntity() == CurContext && "Context imbalance!");
  1130. // Switch back to the lexical context. The safety of this is
  1131. // enforced by an assert in EnterDeclaratorContext.
  1132. Scope *Ancestor = S->getParent();
  1133. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1134. CurContext = Ancestor->getEntity();
  1135. // We don't need to do anything with the scope, which is going to
  1136. // disappear.
  1137. }
  1138. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1139. // We assume that the caller has already called
  1140. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1141. FunctionDecl *FD = D->getAsFunction();
  1142. if (!FD)
  1143. return;
  1144. // Same implementation as PushDeclContext, but enters the context
  1145. // from the lexical parent, rather than the top-level class.
  1146. assert(CurContext == FD->getLexicalParent() &&
  1147. "The next DeclContext should be lexically contained in the current one.");
  1148. CurContext = FD;
  1149. S->setEntity(CurContext);
  1150. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1151. ParmVarDecl *Param = FD->getParamDecl(P);
  1152. // If the parameter has an identifier, then add it to the scope
  1153. if (Param->getIdentifier()) {
  1154. S->AddDecl(Param);
  1155. IdResolver.AddDecl(Param);
  1156. }
  1157. }
  1158. }
  1159. void Sema::ActOnExitFunctionContext() {
  1160. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1161. // rather than the top-level class.
  1162. assert(CurContext && "DeclContext imbalance!");
  1163. CurContext = CurContext->getLexicalParent();
  1164. assert(CurContext && "Popped translation unit!");
  1165. }
  1166. /// Determine whether we allow overloading of the function
  1167. /// PrevDecl with another declaration.
  1168. ///
  1169. /// This routine determines whether overloading is possible, not
  1170. /// whether some new function is actually an overload. It will return
  1171. /// true in C++ (where we can always provide overloads) or, as an
  1172. /// extension, in C when the previous function is already an
  1173. /// overloaded function declaration or has the "overloadable"
  1174. /// attribute.
  1175. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1176. ASTContext &Context,
  1177. const FunctionDecl *New) {
  1178. if (Context.getLangOpts().CPlusPlus)
  1179. return true;
  1180. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1181. return true;
  1182. return Previous.getResultKind() == LookupResult::Found &&
  1183. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1184. New->hasAttr<OverloadableAttr>());
  1185. }
  1186. /// Add this decl to the scope shadowed decl chains.
  1187. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1188. // Move up the scope chain until we find the nearest enclosing
  1189. // non-transparent context. The declaration will be introduced into this
  1190. // scope.
  1191. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1192. S = S->getParent();
  1193. // Add scoped declarations into their context, so that they can be
  1194. // found later. Declarations without a context won't be inserted
  1195. // into any context.
  1196. if (AddToContext)
  1197. CurContext->addDecl(D);
  1198. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1199. // are function-local declarations.
  1200. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1201. !D->getDeclContext()->getRedeclContext()->Equals(
  1202. D->getLexicalDeclContext()->getRedeclContext()) &&
  1203. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1204. return;
  1205. // Template instantiations should also not be pushed into scope.
  1206. if (isa<FunctionDecl>(D) &&
  1207. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1208. return;
  1209. // If this replaces anything in the current scope,
  1210. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1211. IEnd = IdResolver.end();
  1212. for (; I != IEnd; ++I) {
  1213. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1214. S->RemoveDecl(*I);
  1215. IdResolver.RemoveDecl(*I);
  1216. // Should only need to replace one decl.
  1217. break;
  1218. }
  1219. }
  1220. S->AddDecl(D);
  1221. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1222. // Implicitly-generated labels may end up getting generated in an order that
  1223. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1224. // the label at the appropriate place in the identifier chain.
  1225. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1226. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1227. if (IDC == CurContext) {
  1228. if (!S->isDeclScope(*I))
  1229. continue;
  1230. } else if (IDC->Encloses(CurContext))
  1231. break;
  1232. }
  1233. IdResolver.InsertDeclAfter(I, D);
  1234. } else {
  1235. IdResolver.AddDecl(D);
  1236. }
  1237. }
  1238. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1239. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1240. TUScope->AddDecl(D);
  1241. }
  1242. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1243. bool AllowInlineNamespace) {
  1244. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1245. }
  1246. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1247. DeclContext *TargetDC = DC->getPrimaryContext();
  1248. do {
  1249. if (DeclContext *ScopeDC = S->getEntity())
  1250. if (ScopeDC->getPrimaryContext() == TargetDC)
  1251. return S;
  1252. } while ((S = S->getParent()));
  1253. return nullptr;
  1254. }
  1255. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1256. DeclContext*,
  1257. ASTContext&);
  1258. /// Filters out lookup results that don't fall within the given scope
  1259. /// as determined by isDeclInScope.
  1260. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1261. bool ConsiderLinkage,
  1262. bool AllowInlineNamespace) {
  1263. LookupResult::Filter F = R.makeFilter();
  1264. while (F.hasNext()) {
  1265. NamedDecl *D = F.next();
  1266. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1267. continue;
  1268. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1269. continue;
  1270. F.erase();
  1271. }
  1272. F.done();
  1273. }
  1274. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1275. /// have compatible owning modules.
  1276. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1277. // FIXME: The Modules TS is not clear about how friend declarations are
  1278. // to be treated. It's not meaningful to have different owning modules for
  1279. // linkage in redeclarations of the same entity, so for now allow the
  1280. // redeclaration and change the owning modules to match.
  1281. if (New->getFriendObjectKind() &&
  1282. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1283. New->setLocalOwningModule(Old->getOwningModule());
  1284. makeMergedDefinitionVisible(New);
  1285. return false;
  1286. }
  1287. Module *NewM = New->getOwningModule();
  1288. Module *OldM = Old->getOwningModule();
  1289. if (NewM == OldM)
  1290. return false;
  1291. // FIXME: Check proclaimed-ownership-declarations here too.
  1292. bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
  1293. bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
  1294. if (NewIsModuleInterface || OldIsModuleInterface) {
  1295. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1296. // if a declaration of D [...] appears in the purview of a module, all
  1297. // other such declarations shall appear in the purview of the same module
  1298. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1299. << New
  1300. << NewIsModuleInterface
  1301. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1302. << OldIsModuleInterface
  1303. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1304. Diag(Old->getLocation(), diag::note_previous_declaration);
  1305. New->setInvalidDecl();
  1306. return true;
  1307. }
  1308. return false;
  1309. }
  1310. static bool isUsingDecl(NamedDecl *D) {
  1311. return isa<UsingShadowDecl>(D) ||
  1312. isa<UnresolvedUsingTypenameDecl>(D) ||
  1313. isa<UnresolvedUsingValueDecl>(D);
  1314. }
  1315. /// Removes using shadow declarations from the lookup results.
  1316. static void RemoveUsingDecls(LookupResult &R) {
  1317. LookupResult::Filter F = R.makeFilter();
  1318. while (F.hasNext())
  1319. if (isUsingDecl(F.next()))
  1320. F.erase();
  1321. F.done();
  1322. }
  1323. /// Check for this common pattern:
  1324. /// @code
  1325. /// class S {
  1326. /// S(const S&); // DO NOT IMPLEMENT
  1327. /// void operator=(const S&); // DO NOT IMPLEMENT
  1328. /// };
  1329. /// @endcode
  1330. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1331. // FIXME: Should check for private access too but access is set after we get
  1332. // the decl here.
  1333. if (D->doesThisDeclarationHaveABody())
  1334. return false;
  1335. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1336. return CD->isCopyConstructor();
  1337. return D->isCopyAssignmentOperator();
  1338. }
  1339. // We need this to handle
  1340. //
  1341. // typedef struct {
  1342. // void *foo() { return 0; }
  1343. // } A;
  1344. //
  1345. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1346. // for example. If 'A', foo will have external linkage. If we have '*A',
  1347. // foo will have no linkage. Since we can't know until we get to the end
  1348. // of the typedef, this function finds out if D might have non-external linkage.
  1349. // Callers should verify at the end of the TU if it D has external linkage or
  1350. // not.
  1351. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1352. const DeclContext *DC = D->getDeclContext();
  1353. while (!DC->isTranslationUnit()) {
  1354. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1355. if (!RD->hasNameForLinkage())
  1356. return true;
  1357. }
  1358. DC = DC->getParent();
  1359. }
  1360. return !D->isExternallyVisible();
  1361. }
  1362. // FIXME: This needs to be refactored; some other isInMainFile users want
  1363. // these semantics.
  1364. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1365. if (S.TUKind != TU_Complete)
  1366. return false;
  1367. return S.SourceMgr.isInMainFile(Loc);
  1368. }
  1369. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1370. assert(D);
  1371. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1372. return false;
  1373. // Ignore all entities declared within templates, and out-of-line definitions
  1374. // of members of class templates.
  1375. if (D->getDeclContext()->isDependentContext() ||
  1376. D->getLexicalDeclContext()->isDependentContext())
  1377. return false;
  1378. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1379. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1380. return false;
  1381. // A non-out-of-line declaration of a member specialization was implicitly
  1382. // instantiated; it's the out-of-line declaration that we're interested in.
  1383. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1384. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1385. return false;
  1386. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1387. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1388. return false;
  1389. } else {
  1390. // 'static inline' functions are defined in headers; don't warn.
  1391. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1392. return false;
  1393. }
  1394. if (FD->doesThisDeclarationHaveABody() &&
  1395. Context.DeclMustBeEmitted(FD))
  1396. return false;
  1397. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1398. // Constants and utility variables are defined in headers with internal
  1399. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1400. // like "inline".)
  1401. if (!isMainFileLoc(*this, VD->getLocation()))
  1402. return false;
  1403. if (Context.DeclMustBeEmitted(VD))
  1404. return false;
  1405. if (VD->isStaticDataMember() &&
  1406. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1407. return false;
  1408. if (VD->isStaticDataMember() &&
  1409. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1410. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1411. return false;
  1412. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1413. return false;
  1414. } else {
  1415. return false;
  1416. }
  1417. // Only warn for unused decls internal to the translation unit.
  1418. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1419. // for inline functions defined in the main source file, for instance.
  1420. return mightHaveNonExternalLinkage(D);
  1421. }
  1422. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1423. if (!D)
  1424. return;
  1425. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1426. const FunctionDecl *First = FD->getFirstDecl();
  1427. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1428. return; // First should already be in the vector.
  1429. }
  1430. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1431. const VarDecl *First = VD->getFirstDecl();
  1432. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1433. return; // First should already be in the vector.
  1434. }
  1435. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1436. UnusedFileScopedDecls.push_back(D);
  1437. }
  1438. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1439. if (D->isInvalidDecl())
  1440. return false;
  1441. bool Referenced = false;
  1442. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1443. // For a decomposition declaration, warn if none of the bindings are
  1444. // referenced, instead of if the variable itself is referenced (which
  1445. // it is, by the bindings' expressions).
  1446. for (auto *BD : DD->bindings()) {
  1447. if (BD->isReferenced()) {
  1448. Referenced = true;
  1449. break;
  1450. }
  1451. }
  1452. } else if (!D->getDeclName()) {
  1453. return false;
  1454. } else if (D->isReferenced() || D->isUsed()) {
  1455. Referenced = true;
  1456. }
  1457. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1458. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1459. return false;
  1460. if (isa<LabelDecl>(D))
  1461. return true;
  1462. // Except for labels, we only care about unused decls that are local to
  1463. // functions.
  1464. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1465. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1466. // For dependent types, the diagnostic is deferred.
  1467. WithinFunction =
  1468. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1469. if (!WithinFunction)
  1470. return false;
  1471. if (isa<TypedefNameDecl>(D))
  1472. return true;
  1473. // White-list anything that isn't a local variable.
  1474. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1475. return false;
  1476. // Types of valid local variables should be complete, so this should succeed.
  1477. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1478. // White-list anything with an __attribute__((unused)) type.
  1479. const auto *Ty = VD->getType().getTypePtr();
  1480. // Only look at the outermost level of typedef.
  1481. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1482. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1483. return false;
  1484. }
  1485. // If we failed to complete the type for some reason, or if the type is
  1486. // dependent, don't diagnose the variable.
  1487. if (Ty->isIncompleteType() || Ty->isDependentType())
  1488. return false;
  1489. // Look at the element type to ensure that the warning behaviour is
  1490. // consistent for both scalars and arrays.
  1491. Ty = Ty->getBaseElementTypeUnsafe();
  1492. if (const TagType *TT = Ty->getAs<TagType>()) {
  1493. const TagDecl *Tag = TT->getDecl();
  1494. if (Tag->hasAttr<UnusedAttr>())
  1495. return false;
  1496. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1497. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1498. return false;
  1499. if (const Expr *Init = VD->getInit()) {
  1500. if (const ExprWithCleanups *Cleanups =
  1501. dyn_cast<ExprWithCleanups>(Init))
  1502. Init = Cleanups->getSubExpr();
  1503. const CXXConstructExpr *Construct =
  1504. dyn_cast<CXXConstructExpr>(Init);
  1505. if (Construct && !Construct->isElidable()) {
  1506. CXXConstructorDecl *CD = Construct->getConstructor();
  1507. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1508. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1509. return false;
  1510. }
  1511. }
  1512. }
  1513. }
  1514. // TODO: __attribute__((unused)) templates?
  1515. }
  1516. return true;
  1517. }
  1518. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1519. FixItHint &Hint) {
  1520. if (isa<LabelDecl>(D)) {
  1521. SourceLocation AfterColon = Lexer::findLocationAfterToken(
  1522. D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
  1523. true);
  1524. if (AfterColon.isInvalid())
  1525. return;
  1526. Hint = FixItHint::CreateRemoval(
  1527. CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
  1528. }
  1529. }
  1530. void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
  1531. if (D->getTypeForDecl()->isDependentType())
  1532. return;
  1533. for (auto *TmpD : D->decls()) {
  1534. if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
  1535. DiagnoseUnusedDecl(T);
  1536. else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
  1537. DiagnoseUnusedNestedTypedefs(R);
  1538. }
  1539. }
  1540. /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
  1541. /// unless they are marked attr(unused).
  1542. void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
  1543. if (!ShouldDiagnoseUnusedDecl(D))
  1544. return;
  1545. if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  1546. // typedefs can be referenced later on, so the diagnostics are emitted
  1547. // at end-of-translation-unit.
  1548. UnusedLocalTypedefNameCandidates.insert(TD);
  1549. return;
  1550. }
  1551. FixItHint Hint;
  1552. GenerateFixForUnusedDecl(D, Context, Hint);
  1553. unsigned DiagID;
  1554. if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
  1555. DiagID = diag::warn_unused_exception_param;
  1556. else if (isa<LabelDecl>(D))
  1557. DiagID = diag::warn_unused_label;
  1558. else
  1559. DiagID = diag::warn_unused_variable;
  1560. Diag(D->getLocation(), DiagID) << D << Hint;
  1561. }
  1562. static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
  1563. // Verify that we have no forward references left. If so, there was a goto
  1564. // or address of a label taken, but no definition of it. Label fwd
  1565. // definitions are indicated with a null substmt which is also not a resolved
  1566. // MS inline assembly label name.
  1567. bool Diagnose = false;
  1568. if (L->isMSAsmLabel())
  1569. Diagnose = !L->isResolvedMSAsmLabel();
  1570. else
  1571. Diagnose = L->getStmt() == nullptr;
  1572. if (Diagnose)
  1573. S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
  1574. }
  1575. void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
  1576. S->mergeNRVOIntoParent();
  1577. if (S->decl_empty()) return;
  1578. assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
  1579. "Scope shouldn't contain decls!");
  1580. for (auto *TmpD : S->decls()) {
  1581. assert(TmpD && "This decl didn't get pushed??");
  1582. assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
  1583. NamedDecl *D = cast<NamedDecl>(TmpD);
  1584. // Diagnose unused variables in this scope.
  1585. if (!S->hasUnrecoverableErrorOccurred()) {
  1586. DiagnoseUnusedDecl(D);
  1587. if (const auto *RD = dyn_cast<RecordDecl>(D))
  1588. DiagnoseUnusedNestedTypedefs(RD);
  1589. }
  1590. if (!D->getDeclName()) continue;
  1591. // If this was a forward reference to a label, verify it was defined.
  1592. if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
  1593. CheckPoppedLabel(LD, *this);
  1594. // Remove this name from our lexical scope, and warn on it if we haven't
  1595. // already.
  1596. IdResolver.RemoveDecl(D);
  1597. auto ShadowI = ShadowingDecls.find(D);
  1598. if (ShadowI != ShadowingDecls.end()) {
  1599. if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
  1600. Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
  1601. << D << FD << FD->getParent();
  1602. Diag(FD->getLocation(), diag::note_previous_declaration);
  1603. }
  1604. ShadowingDecls.erase(ShadowI);
  1605. }
  1606. }
  1607. }
  1608. /// Look for an Objective-C class in the translation unit.
  1609. ///
  1610. /// \param Id The name of the Objective-C class we're looking for. If
  1611. /// typo-correction fixes this name, the Id will be updated
  1612. /// to the fixed name.
  1613. ///
  1614. /// \param IdLoc The location of the name in the translation unit.
  1615. ///
  1616. /// \param DoTypoCorrection If true, this routine will attempt typo correction
  1617. /// if there is no class with the given name.
  1618. ///
  1619. /// \returns The declaration of the named Objective-C class, or NULL if the
  1620. /// class could not be found.
  1621. ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
  1622. SourceLocation IdLoc,
  1623. bool DoTypoCorrection) {
  1624. // The third "scope" argument is 0 since we aren't enabling lazy built-in
  1625. // creation from this context.
  1626. NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
  1627. if (!IDecl && DoTypoCorrection) {
  1628. // Perform typo correction at the given location, but only if we
  1629. // find an Objective-C class name.
  1630. if (TypoCorrection C = CorrectTypo(
  1631. DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
  1632. llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
  1633. CTK_ErrorRecovery)) {
  1634. diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
  1635. IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
  1636. Id = IDecl->getIdentifier();
  1637. }
  1638. }
  1639. ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
  1640. // This routine must always return a class definition, if any.
  1641. if (Def && Def->getDefinition())
  1642. Def = Def->getDefinition();
  1643. return Def;
  1644. }
  1645. /// getNonFieldDeclScope - Retrieves the innermost scope, starting
  1646. /// from S, where a non-field would be declared. This routine copes
  1647. /// with the difference between C and C++ scoping rules in structs and
  1648. /// unions. For example, the following code is well-formed in C but
  1649. /// ill-formed in C++:
  1650. /// @code
  1651. /// struct S6 {
  1652. /// enum { BAR } e;
  1653. /// };
  1654. ///
  1655. /// void test_S6() {
  1656. /// struct S6 a;
  1657. /// a.e = BAR;
  1658. /// }
  1659. /// @endcode
  1660. /// For the declaration of BAR, this routine will return a different
  1661. /// scope. The scope S will be the scope of the unnamed enumeration
  1662. /// within S6. In C++, this routine will return the scope associated
  1663. /// with S6, because the enumeration's scope is a transparent
  1664. /// context but structures can contain non-field names. In C, this
  1665. /// routine will return the translation unit scope, since the
  1666. /// enumeration's scope is a transparent context and structures cannot
  1667. /// contain non-field names.
  1668. Scope *Sema::getNonFieldDeclScope(Scope *S) {
  1669. while (((S->getFlags() & Scope::DeclScope) == 0) ||
  1670. (S->getEntity() && S->getEntity()->isTransparentContext()) ||
  1671. (S->isClassScope() && !getLangOpts().CPlusPlus))
  1672. S = S->getParent();
  1673. return S;
  1674. }
  1675. /// Looks up the declaration of "struct objc_super" and
  1676. /// saves it for later use in building builtin declaration of
  1677. /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
  1678. /// pre-existing declaration exists no action takes place.
  1679. static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
  1680. IdentifierInfo *II) {
  1681. if (!II->isStr("objc_msgSendSuper"))
  1682. return;
  1683. ASTContext &Context = ThisSema.Context;
  1684. LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
  1685. SourceLocation(), Sema::LookupTagName);
  1686. ThisSema.LookupName(Result, S);
  1687. if (Result.getResultKind() == LookupResult::Found)
  1688. if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
  1689. Context.setObjCSuperType(Context.getTagDeclType(TD));
  1690. }
  1691. static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
  1692. ASTContext::GetBuiltinTypeError Error) {
  1693. switch (Error) {
  1694. case ASTContext::GE_None:
  1695. return "";
  1696. case ASTContext::GE_Missing_type:
  1697. return BuiltinInfo.getHeaderName(ID);
  1698. case ASTContext::GE_Missing_stdio:
  1699. return "stdio.h";
  1700. case ASTContext::GE_Missing_setjmp:
  1701. return "setjmp.h";
  1702. case ASTContext::GE_Missing_ucontext:
  1703. return "ucontext.h";
  1704. }
  1705. llvm_unreachable("unhandled error kind");
  1706. }
  1707. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1708. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1709. /// if we're creating this built-in in anticipation of redeclaring the
  1710. /// built-in.
  1711. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1712. Scope *S, bool ForRedeclaration,
  1713. SourceLocation Loc) {
  1714. LookupPredefedObjCSuperType(*this, S, II);
  1715. ASTContext::GetBuiltinTypeError Error;
  1716. QualType R = Context.GetBuiltinType(ID, Error);
  1717. if (Error) {
  1718. if (ForRedeclaration)
  1719. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1720. << getHeaderName(Context.BuiltinInfo, ID, Error)
  1721. << Context.BuiltinInfo.getName(ID);
  1722. return nullptr;
  1723. }
  1724. if (!ForRedeclaration &&
  1725. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1726. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1727. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1728. << Context.BuiltinInfo.getName(ID) << R;
  1729. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1730. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1731. Diag(Loc, diag::note_include_header_or_declare)
  1732. << Context.BuiltinInfo.getHeaderName(ID)
  1733. << Context.BuiltinInfo.getName(ID);
  1734. }
  1735. if (R.isNull())
  1736. return nullptr;
  1737. DeclContext *Parent = Context.getTranslationUnitDecl();
  1738. if (getLangOpts().CPlusPlus) {
  1739. LinkageSpecDecl *CLinkageDecl =
  1740. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1741. LinkageSpecDecl::lang_c, false);
  1742. CLinkageDecl->setImplicit();
  1743. Parent->addDecl(CLinkageDecl);
  1744. Parent = CLinkageDecl;
  1745. }
  1746. FunctionDecl *New = FunctionDecl::Create(Context,
  1747. Parent,
  1748. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1749. SC_Extern,
  1750. false,
  1751. R->isFunctionProtoType());
  1752. New->setImplicit();
  1753. // Create Decl objects for each parameter, adding them to the
  1754. // FunctionDecl.
  1755. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1756. SmallVector<ParmVarDecl*, 16> Params;
  1757. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1758. ParmVarDecl *parm =
  1759. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1760. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1761. SC_None, nullptr);
  1762. parm->setScopeInfo(0, i);
  1763. Params.push_back(parm);
  1764. }
  1765. New->setParams(Params);
  1766. }
  1767. AddKnownFunctionAttributes(New);
  1768. RegisterLocallyScopedExternCDecl(New, S);
  1769. // TUScope is the translation-unit scope to insert this function into.
  1770. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1771. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1772. // entirely, but we're not there yet.
  1773. DeclContext *SavedContext = CurContext;
  1774. CurContext = Parent;
  1775. PushOnScopeChains(New, TUScope);
  1776. CurContext = SavedContext;
  1777. return New;
  1778. }
  1779. /// Typedef declarations don't have linkage, but they still denote the same
  1780. /// entity if their types are the same.
  1781. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1782. /// isSameEntity.
  1783. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1784. TypedefNameDecl *Decl,
  1785. LookupResult &Previous) {
  1786. // This is only interesting when modules are enabled.
  1787. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1788. return;
  1789. // Empty sets are uninteresting.
  1790. if (Previous.empty())
  1791. return;
  1792. LookupResult::Filter Filter = Previous.makeFilter();
  1793. while (Filter.hasNext()) {
  1794. NamedDecl *Old = Filter.next();
  1795. // Non-hidden declarations are never ignored.
  1796. if (S.isVisible(Old))
  1797. continue;
  1798. // Declarations of the same entity are not ignored, even if they have
  1799. // different linkages.
  1800. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1801. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1802. Decl->getUnderlyingType()))
  1803. continue;
  1804. // If both declarations give a tag declaration a typedef name for linkage
  1805. // purposes, then they declare the same entity.
  1806. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1807. Decl->getAnonDeclWithTypedefName())
  1808. continue;
  1809. }
  1810. Filter.erase();
  1811. }
  1812. Filter.done();
  1813. }
  1814. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1815. QualType OldType;
  1816. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1817. OldType = OldTypedef->getUnderlyingType();
  1818. else
  1819. OldType = Context.getTypeDeclType(Old);
  1820. QualType NewType = New->getUnderlyingType();
  1821. if (NewType->isVariablyModifiedType()) {
  1822. // Must not redefine a typedef with a variably-modified type.
  1823. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1824. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1825. << Kind << NewType;
  1826. if (Old->getLocation().isValid())
  1827. notePreviousDefinition(Old, New->getLocation());
  1828. New->setInvalidDecl();
  1829. return true;
  1830. }
  1831. if (OldType != NewType &&
  1832. !OldType->isDependentType() &&
  1833. !NewType->isDependentType() &&
  1834. !Context.hasSameType(OldType, NewType)) {
  1835. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1836. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1837. << Kind << NewType << OldType;
  1838. if (Old->getLocation().isValid())
  1839. notePreviousDefinition(Old, New->getLocation());
  1840. New->setInvalidDecl();
  1841. return true;
  1842. }
  1843. return false;
  1844. }
  1845. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1846. /// same name and scope as a previous declaration 'Old'. Figure out
  1847. /// how to resolve this situation, merging decls or emitting
  1848. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1849. ///
  1850. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1851. LookupResult &OldDecls) {
  1852. // If the new decl is known invalid already, don't bother doing any
  1853. // merging checks.
  1854. if (New->isInvalidDecl()) return;
  1855. // Allow multiple definitions for ObjC built-in typedefs.
  1856. // FIXME: Verify the underlying types are equivalent!
  1857. if (getLangOpts().ObjC) {
  1858. const IdentifierInfo *TypeID = New->getIdentifier();
  1859. switch (TypeID->getLength()) {
  1860. default: break;
  1861. case 2:
  1862. {
  1863. if (!TypeID->isStr("id"))
  1864. break;
  1865. QualType T = New->getUnderlyingType();
  1866. if (!T->isPointerType())
  1867. break;
  1868. if (!T->isVoidPointerType()) {
  1869. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1870. if (!PT->isStructureType())
  1871. break;
  1872. }
  1873. Context.setObjCIdRedefinitionType(T);
  1874. // Install the built-in type for 'id', ignoring the current definition.
  1875. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1876. return;
  1877. }
  1878. case 5:
  1879. if (!TypeID->isStr("Class"))
  1880. break;
  1881. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1882. // Install the built-in type for 'Class', ignoring the current definition.
  1883. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1884. return;
  1885. case 3:
  1886. if (!TypeID->isStr("SEL"))
  1887. break;
  1888. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1889. // Install the built-in type for 'SEL', ignoring the current definition.
  1890. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1891. return;
  1892. }
  1893. // Fall through - the typedef name was not a builtin type.
  1894. }
  1895. // Verify the old decl was also a type.
  1896. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1897. if (!Old) {
  1898. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1899. << New->getDeclName();
  1900. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1901. if (OldD->getLocation().isValid())
  1902. notePreviousDefinition(OldD, New->getLocation());
  1903. return New->setInvalidDecl();
  1904. }
  1905. // If the old declaration is invalid, just give up here.
  1906. if (Old->isInvalidDecl())
  1907. return New->setInvalidDecl();
  1908. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1909. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1910. auto *NewTag = New->getAnonDeclWithTypedefName();
  1911. NamedDecl *Hidden = nullptr;
  1912. if (OldTag && NewTag &&
  1913. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1914. !hasVisibleDefinition(OldTag, &Hidden)) {
  1915. // There is a definition of this tag, but it is not visible. Use it
  1916. // instead of our tag.
  1917. New->setTypeForDecl(OldTD->getTypeForDecl());
  1918. if (OldTD->isModed())
  1919. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1920. OldTD->getUnderlyingType());
  1921. else
  1922. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1923. // Make the old tag definition visible.
  1924. makeMergedDefinitionVisible(Hidden);
  1925. // If this was an unscoped enumeration, yank all of its enumerators
  1926. // out of the scope.
  1927. if (isa<EnumDecl>(NewTag)) {
  1928. Scope *EnumScope = getNonFieldDeclScope(S);
  1929. for (auto *D : NewTag->decls()) {
  1930. auto *ED = cast<EnumConstantDecl>(D);
  1931. assert(EnumScope->isDeclScope(ED));
  1932. EnumScope->RemoveDecl(ED);
  1933. IdResolver.RemoveDecl(ED);
  1934. ED->getLexicalDeclContext()->removeDecl(ED);
  1935. }
  1936. }
  1937. }
  1938. }
  1939. // If the typedef types are not identical, reject them in all languages and
  1940. // with any extensions enabled.
  1941. if (isIncompatibleTypedef(Old, New))
  1942. return;
  1943. // The types match. Link up the redeclaration chain and merge attributes if
  1944. // the old declaration was a typedef.
  1945. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1946. New->setPreviousDecl(Typedef);
  1947. mergeDeclAttributes(New, Old);
  1948. }
  1949. if (getLangOpts().MicrosoftExt)
  1950. return;
  1951. if (getLangOpts().CPlusPlus) {
  1952. // C++ [dcl.typedef]p2:
  1953. // In a given non-class scope, a typedef specifier can be used to
  1954. // redefine the name of any type declared in that scope to refer
  1955. // to the type to which it already refers.
  1956. if (!isa<CXXRecordDecl>(CurContext))
  1957. return;
  1958. // C++0x [dcl.typedef]p4:
  1959. // In a given class scope, a typedef specifier can be used to redefine
  1960. // any class-name declared in that scope that is not also a typedef-name
  1961. // to refer to the type to which it already refers.
  1962. //
  1963. // This wording came in via DR424, which was a correction to the
  1964. // wording in DR56, which accidentally banned code like:
  1965. //
  1966. // struct S {
  1967. // typedef struct A { } A;
  1968. // };
  1969. //
  1970. // in the C++03 standard. We implement the C++0x semantics, which
  1971. // allow the above but disallow
  1972. //
  1973. // struct S {
  1974. // typedef int I;
  1975. // typedef int I;
  1976. // };
  1977. //
  1978. // since that was the intent of DR56.
  1979. if (!isa<TypedefNameDecl>(Old))
  1980. return;
  1981. Diag(New->getLocation(), diag::err_redefinition)
  1982. << New->getDeclName();
  1983. notePreviousDefinition(Old, New->getLocation());
  1984. return New->setInvalidDecl();
  1985. }
  1986. // Modules always permit redefinition of typedefs, as does C11.
  1987. if (getLangOpts().Modules || getLangOpts().C11)
  1988. return;
  1989. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1990. // is normally mapped to an error, but can be controlled with
  1991. // -Wtypedef-redefinition. If either the original or the redefinition is
  1992. // in a system header, don't emit this for compatibility with GCC.
  1993. if (getDiagnostics().getSuppressSystemWarnings() &&
  1994. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  1995. (Old->isImplicit() ||
  1996. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1997. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1998. return;
  1999. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  2000. << New->getDeclName();
  2001. notePreviousDefinition(Old, New->getLocation());
  2002. }
  2003. /// DeclhasAttr - returns true if decl Declaration already has the target
  2004. /// attribute.
  2005. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2006. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2007. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2008. for (const auto *i : D->attrs())
  2009. if (i->getKind() == A->getKind()) {
  2010. if (Ann) {
  2011. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2012. return true;
  2013. continue;
  2014. }
  2015. // FIXME: Don't hardcode this check
  2016. if (OA && isa<OwnershipAttr>(i))
  2017. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2018. return true;
  2019. }
  2020. return false;
  2021. }
  2022. static bool isAttributeTargetADefinition(Decl *D) {
  2023. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2024. return VD->isThisDeclarationADefinition();
  2025. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2026. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2027. return true;
  2028. }
  2029. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2030. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2031. ///
  2032. /// \return \c true if any attributes were added to \p New.
  2033. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2034. // Look for alignas attributes on Old, and pick out whichever attribute
  2035. // specifies the strictest alignment requirement.
  2036. AlignedAttr *OldAlignasAttr = nullptr;
  2037. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2038. unsigned OldAlign = 0;
  2039. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2040. // FIXME: We have no way of representing inherited dependent alignments
  2041. // in a case like:
  2042. // template<int A, int B> struct alignas(A) X;
  2043. // template<int A, int B> struct alignas(B) X {};
  2044. // For now, we just ignore any alignas attributes which are not on the
  2045. // definition in such a case.
  2046. if (I->isAlignmentDependent())
  2047. return false;
  2048. if (I->isAlignas())
  2049. OldAlignasAttr = I;
  2050. unsigned Align = I->getAlignment(S.Context);
  2051. if (Align > OldAlign) {
  2052. OldAlign = Align;
  2053. OldStrictestAlignAttr = I;
  2054. }
  2055. }
  2056. // Look for alignas attributes on New.
  2057. AlignedAttr *NewAlignasAttr = nullptr;
  2058. unsigned NewAlign = 0;
  2059. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2060. if (I->isAlignmentDependent())
  2061. return false;
  2062. if (I->isAlignas())
  2063. NewAlignasAttr = I;
  2064. unsigned Align = I->getAlignment(S.Context);
  2065. if (Align > NewAlign)
  2066. NewAlign = Align;
  2067. }
  2068. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2069. // Both declarations have 'alignas' attributes. We require them to match.
  2070. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2071. // fall short. (If two declarations both have alignas, they must both match
  2072. // every definition, and so must match each other if there is a definition.)
  2073. // If either declaration only contains 'alignas(0)' specifiers, then it
  2074. // specifies the natural alignment for the type.
  2075. if (OldAlign == 0 || NewAlign == 0) {
  2076. QualType Ty;
  2077. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2078. Ty = VD->getType();
  2079. else
  2080. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2081. if (OldAlign == 0)
  2082. OldAlign = S.Context.getTypeAlign(Ty);
  2083. if (NewAlign == 0)
  2084. NewAlign = S.Context.getTypeAlign(Ty);
  2085. }
  2086. if (OldAlign != NewAlign) {
  2087. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2088. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2089. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2090. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2091. }
  2092. }
  2093. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2094. // C++11 [dcl.align]p6:
  2095. // if any declaration of an entity has an alignment-specifier,
  2096. // every defining declaration of that entity shall specify an
  2097. // equivalent alignment.
  2098. // C11 6.7.5/7:
  2099. // If the definition of an object does not have an alignment
  2100. // specifier, any other declaration of that object shall also
  2101. // have no alignment specifier.
  2102. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2103. << OldAlignasAttr;
  2104. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2105. << OldAlignasAttr;
  2106. }
  2107. bool AnyAdded = false;
  2108. // Ensure we have an attribute representing the strictest alignment.
  2109. if (OldAlign > NewAlign) {
  2110. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2111. Clone->setInherited(true);
  2112. New->addAttr(Clone);
  2113. AnyAdded = true;
  2114. }
  2115. // Ensure we have an alignas attribute if the old declaration had one.
  2116. if (OldAlignasAttr && !NewAlignasAttr &&
  2117. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2118. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2119. Clone->setInherited(true);
  2120. New->addAttr(Clone);
  2121. AnyAdded = true;
  2122. }
  2123. return AnyAdded;
  2124. }
  2125. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2126. const InheritableAttr *Attr,
  2127. Sema::AvailabilityMergeKind AMK) {
  2128. // This function copies an attribute Attr from a previous declaration to the
  2129. // new declaration D if the new declaration doesn't itself have that attribute
  2130. // yet or if that attribute allows duplicates.
  2131. // If you're adding a new attribute that requires logic different from
  2132. // "use explicit attribute on decl if present, else use attribute from
  2133. // previous decl", for example if the attribute needs to be consistent
  2134. // between redeclarations, you need to call a custom merge function here.
  2135. InheritableAttr *NewAttr = nullptr;
  2136. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2137. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2138. NewAttr = S.mergeAvailabilityAttr(
  2139. D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
  2140. AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
  2141. AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
  2142. AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
  2143. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2144. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2145. AttrSpellingListIndex);
  2146. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2147. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2148. AttrSpellingListIndex);
  2149. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2150. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2151. AttrSpellingListIndex);
  2152. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2153. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2154. AttrSpellingListIndex);
  2155. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2156. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2157. FA->getFormatIdx(), FA->getFirstArg(),
  2158. AttrSpellingListIndex);
  2159. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2160. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2161. AttrSpellingListIndex);
  2162. else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
  2163. NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
  2164. AttrSpellingListIndex);
  2165. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2166. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2167. AttrSpellingListIndex,
  2168. IA->getSemanticSpelling());
  2169. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2170. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2171. &S.Context.Idents.get(AA->getSpelling()),
  2172. AttrSpellingListIndex);
  2173. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2174. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2175. isa<CUDAGlobalAttr>(Attr))) {
  2176. // CUDA target attributes are part of function signature for
  2177. // overloading purposes and must not be merged.
  2178. return false;
  2179. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2180. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2181. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2182. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2183. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2184. NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
  2185. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2186. NewAttr = S.mergeCommonAttr(D, *CommonA);
  2187. else if (isa<AlignedAttr>(Attr))
  2188. // AlignedAttrs are handled separately, because we need to handle all
  2189. // such attributes on a declaration at the same time.
  2190. NewAttr = nullptr;
  2191. else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
  2192. (AMK == Sema::AMK_Override ||
  2193. AMK == Sema::AMK_ProtocolImplementation))
  2194. NewAttr = nullptr;
  2195. else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
  2196. NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
  2197. UA->getGuid());
  2198. else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
  2199. NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
  2200. else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
  2201. NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
  2202. else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2203. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2204. if (NewAttr) {
  2205. NewAttr->setInherited(true);
  2206. D->addAttr(NewAttr);
  2207. if (isa<MSInheritanceAttr>(NewAttr))
  2208. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2209. return true;
  2210. }
  2211. return false;
  2212. }
  2213. static const NamedDecl *getDefinition(const Decl *D) {
  2214. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2215. return TD->getDefinition();
  2216. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2217. const VarDecl *Def = VD->getDefinition();
  2218. if (Def)
  2219. return Def;
  2220. return VD->getActingDefinition();
  2221. }
  2222. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2223. return FD->getDefinition();
  2224. return nullptr;
  2225. }
  2226. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2227. for (const auto *Attribute : D->attrs())
  2228. if (Attribute->getKind() == Kind)
  2229. return true;
  2230. return false;
  2231. }
  2232. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2233. /// there are no new attributes in this declaration.
  2234. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2235. if (!New->hasAttrs())
  2236. return;
  2237. const NamedDecl *Def = getDefinition(Old);
  2238. if (!Def || Def == New)
  2239. return;
  2240. AttrVec &NewAttributes = New->getAttrs();
  2241. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2242. const Attr *NewAttribute = NewAttributes[I];
  2243. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2244. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2245. Sema::SkipBodyInfo SkipBody;
  2246. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2247. // If we're skipping this definition, drop the "alias" attribute.
  2248. if (SkipBody.ShouldSkip) {
  2249. NewAttributes.erase(NewAttributes.begin() + I);
  2250. --E;
  2251. continue;
  2252. }
  2253. } else {
  2254. VarDecl *VD = cast<VarDecl>(New);
  2255. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2256. VarDecl::TentativeDefinition
  2257. ? diag::err_alias_after_tentative
  2258. : diag::err_redefinition;
  2259. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2260. if (Diag == diag::err_redefinition)
  2261. S.notePreviousDefinition(Def, VD->getLocation());
  2262. else
  2263. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2264. VD->setInvalidDecl();
  2265. }
  2266. ++I;
  2267. continue;
  2268. }
  2269. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2270. // Tentative definitions are only interesting for the alias check above.
  2271. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2272. ++I;
  2273. continue;
  2274. }
  2275. }
  2276. if (hasAttribute(Def, NewAttribute->getKind())) {
  2277. ++I;
  2278. continue; // regular attr merging will take care of validating this.
  2279. }
  2280. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2281. // C's _Noreturn is allowed to be added to a function after it is defined.
  2282. ++I;
  2283. continue;
  2284. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2285. if (AA->isAlignas()) {
  2286. // C++11 [dcl.align]p6:
  2287. // if any declaration of an entity has an alignment-specifier,
  2288. // every defining declaration of that entity shall specify an
  2289. // equivalent alignment.
  2290. // C11 6.7.5/7:
  2291. // If the definition of an object does not have an alignment
  2292. // specifier, any other declaration of that object shall also
  2293. // have no alignment specifier.
  2294. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2295. << AA;
  2296. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2297. << AA;
  2298. NewAttributes.erase(NewAttributes.begin() + I);
  2299. --E;
  2300. continue;
  2301. }
  2302. }
  2303. S.Diag(NewAttribute->getLocation(),
  2304. diag::warn_attribute_precede_definition);
  2305. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2306. NewAttributes.erase(NewAttributes.begin() + I);
  2307. --E;
  2308. }
  2309. }
  2310. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2311. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2312. AvailabilityMergeKind AMK) {
  2313. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2314. UsedAttr *NewAttr = OldAttr->clone(Context);
  2315. NewAttr->setInherited(true);
  2316. New->addAttr(NewAttr);
  2317. }
  2318. if (!Old->hasAttrs() && !New->hasAttrs())
  2319. return;
  2320. // Attributes declared post-definition are currently ignored.
  2321. checkNewAttributesAfterDef(*this, New, Old);
  2322. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2323. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2324. if (OldA->getLabel() != NewA->getLabel()) {
  2325. // This redeclaration changes __asm__ label.
  2326. Diag(New->getLocation(), diag::err_different_asm_label);
  2327. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2328. }
  2329. } else if (Old->isUsed()) {
  2330. // This redeclaration adds an __asm__ label to a declaration that has
  2331. // already been ODR-used.
  2332. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2333. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2334. }
  2335. }
  2336. // Re-declaration cannot add abi_tag's.
  2337. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2338. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2339. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2340. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2341. NewTag) == OldAbiTagAttr->tags_end()) {
  2342. Diag(NewAbiTagAttr->getLocation(),
  2343. diag::err_new_abi_tag_on_redeclaration)
  2344. << NewTag;
  2345. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2346. }
  2347. }
  2348. } else {
  2349. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2350. Diag(Old->getLocation(), diag::note_previous_declaration);
  2351. }
  2352. }
  2353. // This redeclaration adds a section attribute.
  2354. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2355. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2356. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2357. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2358. Diag(Old->getLocation(), diag::note_previous_declaration);
  2359. }
  2360. }
  2361. }
  2362. // Redeclaration adds code-seg attribute.
  2363. const auto *NewCSA = New->getAttr<CodeSegAttr>();
  2364. if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
  2365. !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
  2366. Diag(New->getLocation(), diag::warn_mismatched_section)
  2367. << 0 /*codeseg*/;
  2368. Diag(Old->getLocation(), diag::note_previous_declaration);
  2369. }
  2370. if (!Old->hasAttrs())
  2371. return;
  2372. bool foundAny = New->hasAttrs();
  2373. // Ensure that any moving of objects within the allocated map is done before
  2374. // we process them.
  2375. if (!foundAny) New->setAttrs(AttrVec());
  2376. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2377. // Ignore deprecated/unavailable/availability attributes if requested.
  2378. AvailabilityMergeKind LocalAMK = AMK_None;
  2379. if (isa<DeprecatedAttr>(I) ||
  2380. isa<UnavailableAttr>(I) ||
  2381. isa<AvailabilityAttr>(I)) {
  2382. switch (AMK) {
  2383. case AMK_None:
  2384. continue;
  2385. case AMK_Redeclaration:
  2386. case AMK_Override:
  2387. case AMK_ProtocolImplementation:
  2388. LocalAMK = AMK;
  2389. break;
  2390. }
  2391. }
  2392. // Already handled.
  2393. if (isa<UsedAttr>(I))
  2394. continue;
  2395. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2396. foundAny = true;
  2397. }
  2398. if (mergeAlignedAttrs(*this, New, Old))
  2399. foundAny = true;
  2400. if (!foundAny) New->dropAttrs();
  2401. }
  2402. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2403. /// to the new one.
  2404. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2405. const ParmVarDecl *oldDecl,
  2406. Sema &S) {
  2407. // C++11 [dcl.attr.depend]p2:
  2408. // The first declaration of a function shall specify the
  2409. // carries_dependency attribute for its declarator-id if any declaration
  2410. // of the function specifies the carries_dependency attribute.
  2411. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2412. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2413. S.Diag(CDA->getLocation(),
  2414. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2415. // Find the first declaration of the parameter.
  2416. // FIXME: Should we build redeclaration chains for function parameters?
  2417. const FunctionDecl *FirstFD =
  2418. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2419. const ParmVarDecl *FirstVD =
  2420. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2421. S.Diag(FirstVD->getLocation(),
  2422. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2423. }
  2424. if (!oldDecl->hasAttrs())
  2425. return;
  2426. bool foundAny = newDecl->hasAttrs();
  2427. // Ensure that any moving of objects within the allocated map is
  2428. // done before we process them.
  2429. if (!foundAny) newDecl->setAttrs(AttrVec());
  2430. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2431. if (!DeclHasAttr(newDecl, I)) {
  2432. InheritableAttr *newAttr =
  2433. cast<InheritableParamAttr>(I->clone(S.Context));
  2434. newAttr->setInherited(true);
  2435. newDecl->addAttr(newAttr);
  2436. foundAny = true;
  2437. }
  2438. }
  2439. if (!foundAny) newDecl->dropAttrs();
  2440. }
  2441. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2442. const ParmVarDecl *OldParam,
  2443. Sema &S) {
  2444. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2445. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2446. if (*Oldnullability != *Newnullability) {
  2447. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2448. << DiagNullabilityKind(
  2449. *Newnullability,
  2450. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2451. != 0))
  2452. << DiagNullabilityKind(
  2453. *Oldnullability,
  2454. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2455. != 0));
  2456. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2457. }
  2458. } else {
  2459. QualType NewT = NewParam->getType();
  2460. NewT = S.Context.getAttributedType(
  2461. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2462. NewT, NewT);
  2463. NewParam->setType(NewT);
  2464. }
  2465. }
  2466. }
  2467. namespace {
  2468. /// Used in MergeFunctionDecl to keep track of function parameters in
  2469. /// C.
  2470. struct GNUCompatibleParamWarning {
  2471. ParmVarDecl *OldParm;
  2472. ParmVarDecl *NewParm;
  2473. QualType PromotedType;
  2474. };
  2475. } // end anonymous namespace
  2476. /// getSpecialMember - get the special member enum for a method.
  2477. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2478. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2479. if (Ctor->isDefaultConstructor())
  2480. return Sema::CXXDefaultConstructor;
  2481. if (Ctor->isCopyConstructor())
  2482. return Sema::CXXCopyConstructor;
  2483. if (Ctor->isMoveConstructor())
  2484. return Sema::CXXMoveConstructor;
  2485. } else if (isa<CXXDestructorDecl>(MD)) {
  2486. return Sema::CXXDestructor;
  2487. } else if (MD->isCopyAssignmentOperator()) {
  2488. return Sema::CXXCopyAssignment;
  2489. } else if (MD->isMoveAssignmentOperator()) {
  2490. return Sema::CXXMoveAssignment;
  2491. }
  2492. return Sema::CXXInvalid;
  2493. }
  2494. // Determine whether the previous declaration was a definition, implicit
  2495. // declaration, or a declaration.
  2496. template <typename T>
  2497. static std::pair<diag::kind, SourceLocation>
  2498. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2499. diag::kind PrevDiag;
  2500. SourceLocation OldLocation = Old->getLocation();
  2501. if (Old->isThisDeclarationADefinition())
  2502. PrevDiag = diag::note_previous_definition;
  2503. else if (Old->isImplicit()) {
  2504. PrevDiag = diag::note_previous_implicit_declaration;
  2505. if (OldLocation.isInvalid())
  2506. OldLocation = New->getLocation();
  2507. } else
  2508. PrevDiag = diag::note_previous_declaration;
  2509. return std::make_pair(PrevDiag, OldLocation);
  2510. }
  2511. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2512. /// only extern inline functions can be redefined, and even then only in
  2513. /// GNU89 mode.
  2514. static bool canRedefineFunction(const FunctionDecl *FD,
  2515. const LangOptions& LangOpts) {
  2516. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2517. !LangOpts.CPlusPlus &&
  2518. FD->isInlineSpecified() &&
  2519. FD->getStorageClass() == SC_Extern);
  2520. }
  2521. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2522. const AttributedType *AT = T->getAs<AttributedType>();
  2523. while (AT && !AT->isCallingConv())
  2524. AT = AT->getModifiedType()->getAs<AttributedType>();
  2525. return AT;
  2526. }
  2527. template <typename T>
  2528. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2529. const DeclContext *DC = Old->getDeclContext();
  2530. if (DC->isRecord())
  2531. return false;
  2532. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2533. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2534. return true;
  2535. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2536. return true;
  2537. return false;
  2538. }
  2539. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2540. static bool isExternC(VarTemplateDecl *) { return false; }
  2541. /// Check whether a redeclaration of an entity introduced by a
  2542. /// using-declaration is valid, given that we know it's not an overload
  2543. /// (nor a hidden tag declaration).
  2544. template<typename ExpectedDecl>
  2545. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2546. ExpectedDecl *New) {
  2547. // C++11 [basic.scope.declarative]p4:
  2548. // Given a set of declarations in a single declarative region, each of
  2549. // which specifies the same unqualified name,
  2550. // -- they shall all refer to the same entity, or all refer to functions
  2551. // and function templates; or
  2552. // -- exactly one declaration shall declare a class name or enumeration
  2553. // name that is not a typedef name and the other declarations shall all
  2554. // refer to the same variable or enumerator, or all refer to functions
  2555. // and function templates; in this case the class name or enumeration
  2556. // name is hidden (3.3.10).
  2557. // C++11 [namespace.udecl]p14:
  2558. // If a function declaration in namespace scope or block scope has the
  2559. // same name and the same parameter-type-list as a function introduced
  2560. // by a using-declaration, and the declarations do not declare the same
  2561. // function, the program is ill-formed.
  2562. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2563. if (Old &&
  2564. !Old->getDeclContext()->getRedeclContext()->Equals(
  2565. New->getDeclContext()->getRedeclContext()) &&
  2566. !(isExternC(Old) && isExternC(New)))
  2567. Old = nullptr;
  2568. if (!Old) {
  2569. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2570. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2571. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2572. return true;
  2573. }
  2574. return false;
  2575. }
  2576. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2577. const FunctionDecl *B) {
  2578. assert(A->getNumParams() == B->getNumParams());
  2579. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2580. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2581. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2582. if (AttrA == AttrB)
  2583. return true;
  2584. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2585. };
  2586. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2587. }
  2588. /// If necessary, adjust the semantic declaration context for a qualified
  2589. /// declaration to name the correct inline namespace within the qualifier.
  2590. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2591. DeclaratorDecl *OldD) {
  2592. // The only case where we need to update the DeclContext is when
  2593. // redeclaration lookup for a qualified name finds a declaration
  2594. // in an inline namespace within the context named by the qualifier:
  2595. //
  2596. // inline namespace N { int f(); }
  2597. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2598. //
  2599. // For unqualified declarations, the semantic context *can* change
  2600. // along the redeclaration chain (for local extern declarations,
  2601. // extern "C" declarations, and friend declarations in particular).
  2602. if (!NewD->getQualifier())
  2603. return;
  2604. // NewD is probably already in the right context.
  2605. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2606. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2607. if (NamedDC->Equals(SemaDC))
  2608. return;
  2609. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2610. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2611. "unexpected context for redeclaration");
  2612. auto *LexDC = NewD->getLexicalDeclContext();
  2613. auto FixSemaDC = [=](NamedDecl *D) {
  2614. if (!D)
  2615. return;
  2616. D->setDeclContext(SemaDC);
  2617. D->setLexicalDeclContext(LexDC);
  2618. };
  2619. FixSemaDC(NewD);
  2620. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2621. FixSemaDC(FD->getDescribedFunctionTemplate());
  2622. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2623. FixSemaDC(VD->getDescribedVarTemplate());
  2624. }
  2625. /// MergeFunctionDecl - We just parsed a function 'New' from
  2626. /// declarator D which has the same name and scope as a previous
  2627. /// declaration 'Old'. Figure out how to resolve this situation,
  2628. /// merging decls or emitting diagnostics as appropriate.
  2629. ///
  2630. /// In C++, New and Old must be declarations that are not
  2631. /// overloaded. Use IsOverload to determine whether New and Old are
  2632. /// overloaded, and to select the Old declaration that New should be
  2633. /// merged with.
  2634. ///
  2635. /// Returns true if there was an error, false otherwise.
  2636. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2637. Scope *S, bool MergeTypeWithOld) {
  2638. // Verify the old decl was also a function.
  2639. FunctionDecl *Old = OldD->getAsFunction();
  2640. if (!Old) {
  2641. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2642. if (New->getFriendObjectKind()) {
  2643. Diag(New->getLocation(), diag::err_using_decl_friend);
  2644. Diag(Shadow->getTargetDecl()->getLocation(),
  2645. diag::note_using_decl_target);
  2646. Diag(Shadow->getUsingDecl()->getLocation(),
  2647. diag::note_using_decl) << 0;
  2648. return true;
  2649. }
  2650. // Check whether the two declarations might declare the same function.
  2651. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2652. return true;
  2653. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2654. } else {
  2655. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2656. << New->getDeclName();
  2657. notePreviousDefinition(OldD, New->getLocation());
  2658. return true;
  2659. }
  2660. }
  2661. // If the old declaration is invalid, just give up here.
  2662. if (Old->isInvalidDecl())
  2663. return true;
  2664. // Disallow redeclaration of some builtins.
  2665. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2666. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2667. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2668. << Old << Old->getType();
  2669. return true;
  2670. }
  2671. diag::kind PrevDiag;
  2672. SourceLocation OldLocation;
  2673. std::tie(PrevDiag, OldLocation) =
  2674. getNoteDiagForInvalidRedeclaration(Old, New);
  2675. // Don't complain about this if we're in GNU89 mode and the old function
  2676. // is an extern inline function.
  2677. // Don't complain about specializations. They are not supposed to have
  2678. // storage classes.
  2679. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2680. New->getStorageClass() == SC_Static &&
  2681. Old->hasExternalFormalLinkage() &&
  2682. !New->getTemplateSpecializationInfo() &&
  2683. !canRedefineFunction(Old, getLangOpts())) {
  2684. if (getLangOpts().MicrosoftExt) {
  2685. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2686. Diag(OldLocation, PrevDiag);
  2687. } else {
  2688. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2689. Diag(OldLocation, PrevDiag);
  2690. return true;
  2691. }
  2692. }
  2693. if (New->hasAttr<InternalLinkageAttr>() &&
  2694. !Old->hasAttr<InternalLinkageAttr>()) {
  2695. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2696. << New->getDeclName();
  2697. notePreviousDefinition(Old, New->getLocation());
  2698. New->dropAttr<InternalLinkageAttr>();
  2699. }
  2700. if (CheckRedeclarationModuleOwnership(New, Old))
  2701. return true;
  2702. if (!getLangOpts().CPlusPlus) {
  2703. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2704. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2705. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2706. << New << OldOvl;
  2707. // Try our best to find a decl that actually has the overloadable
  2708. // attribute for the note. In most cases (e.g. programs with only one
  2709. // broken declaration/definition), this won't matter.
  2710. //
  2711. // FIXME: We could do this if we juggled some extra state in
  2712. // OverloadableAttr, rather than just removing it.
  2713. const Decl *DiagOld = Old;
  2714. if (OldOvl) {
  2715. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2716. const auto *A = D->getAttr<OverloadableAttr>();
  2717. return A && !A->isImplicit();
  2718. });
  2719. // If we've implicitly added *all* of the overloadable attrs to this
  2720. // chain, emitting a "previous redecl" note is pointless.
  2721. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2722. }
  2723. if (DiagOld)
  2724. Diag(DiagOld->getLocation(),
  2725. diag::note_attribute_overloadable_prev_overload)
  2726. << OldOvl;
  2727. if (OldOvl)
  2728. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2729. else
  2730. New->dropAttr<OverloadableAttr>();
  2731. }
  2732. }
  2733. // If a function is first declared with a calling convention, but is later
  2734. // declared or defined without one, all following decls assume the calling
  2735. // convention of the first.
  2736. //
  2737. // It's OK if a function is first declared without a calling convention,
  2738. // but is later declared or defined with the default calling convention.
  2739. //
  2740. // To test if either decl has an explicit calling convention, we look for
  2741. // AttributedType sugar nodes on the type as written. If they are missing or
  2742. // were canonicalized away, we assume the calling convention was implicit.
  2743. //
  2744. // Note also that we DO NOT return at this point, because we still have
  2745. // other tests to run.
  2746. QualType OldQType = Context.getCanonicalType(Old->getType());
  2747. QualType NewQType = Context.getCanonicalType(New->getType());
  2748. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2749. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2750. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2751. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2752. bool RequiresAdjustment = false;
  2753. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2754. FunctionDecl *First = Old->getFirstDecl();
  2755. const FunctionType *FT =
  2756. First->getType().getCanonicalType()->castAs<FunctionType>();
  2757. FunctionType::ExtInfo FI = FT->getExtInfo();
  2758. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2759. if (!NewCCExplicit) {
  2760. // Inherit the CC from the previous declaration if it was specified
  2761. // there but not here.
  2762. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2763. RequiresAdjustment = true;
  2764. } else {
  2765. // Calling conventions aren't compatible, so complain.
  2766. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2767. Diag(New->getLocation(), diag::err_cconv_change)
  2768. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2769. << !FirstCCExplicit
  2770. << (!FirstCCExplicit ? "" :
  2771. FunctionType::getNameForCallConv(FI.getCC()));
  2772. // Put the note on the first decl, since it is the one that matters.
  2773. Diag(First->getLocation(), diag::note_previous_declaration);
  2774. return true;
  2775. }
  2776. }
  2777. // FIXME: diagnose the other way around?
  2778. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2779. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2780. RequiresAdjustment = true;
  2781. }
  2782. // Merge regparm attribute.
  2783. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2784. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2785. if (NewTypeInfo.getHasRegParm()) {
  2786. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2787. << NewType->getRegParmType()
  2788. << OldType->getRegParmType();
  2789. Diag(OldLocation, diag::note_previous_declaration);
  2790. return true;
  2791. }
  2792. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2793. RequiresAdjustment = true;
  2794. }
  2795. // Merge ns_returns_retained attribute.
  2796. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2797. if (NewTypeInfo.getProducesResult()) {
  2798. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2799. << "'ns_returns_retained'";
  2800. Diag(OldLocation, diag::note_previous_declaration);
  2801. return true;
  2802. }
  2803. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2804. RequiresAdjustment = true;
  2805. }
  2806. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2807. NewTypeInfo.getNoCallerSavedRegs()) {
  2808. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2809. AnyX86NoCallerSavedRegistersAttr *Attr =
  2810. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2811. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2812. Diag(OldLocation, diag::note_previous_declaration);
  2813. return true;
  2814. }
  2815. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2816. RequiresAdjustment = true;
  2817. }
  2818. if (RequiresAdjustment) {
  2819. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2820. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2821. New->setType(QualType(AdjustedType, 0));
  2822. NewQType = Context.getCanonicalType(New->getType());
  2823. NewType = cast<FunctionType>(NewQType);
  2824. }
  2825. // If this redeclaration makes the function inline, we may need to add it to
  2826. // UndefinedButUsed.
  2827. if (!Old->isInlined() && New->isInlined() &&
  2828. !New->hasAttr<GNUInlineAttr>() &&
  2829. !getLangOpts().GNUInline &&
  2830. Old->isUsed(false) &&
  2831. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2832. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2833. SourceLocation()));
  2834. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2835. // about it.
  2836. if (New->hasAttr<GNUInlineAttr>() &&
  2837. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2838. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2839. }
  2840. // If pass_object_size params don't match up perfectly, this isn't a valid
  2841. // redeclaration.
  2842. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2843. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2844. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2845. << New->getDeclName();
  2846. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2847. return true;
  2848. }
  2849. if (getLangOpts().CPlusPlus) {
  2850. // C++1z [over.load]p2
  2851. // Certain function declarations cannot be overloaded:
  2852. // -- Function declarations that differ only in the return type,
  2853. // the exception specification, or both cannot be overloaded.
  2854. // Check the exception specifications match. This may recompute the type of
  2855. // both Old and New if it resolved exception specifications, so grab the
  2856. // types again after this. Because this updates the type, we do this before
  2857. // any of the other checks below, which may update the "de facto" NewQType
  2858. // but do not necessarily update the type of New.
  2859. if (CheckEquivalentExceptionSpec(Old, New))
  2860. return true;
  2861. OldQType = Context.getCanonicalType(Old->getType());
  2862. NewQType = Context.getCanonicalType(New->getType());
  2863. // Go back to the type source info to compare the declared return types,
  2864. // per C++1y [dcl.type.auto]p13:
  2865. // Redeclarations or specializations of a function or function template
  2866. // with a declared return type that uses a placeholder type shall also
  2867. // use that placeholder, not a deduced type.
  2868. QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
  2869. QualType NewDeclaredReturnType = New->getDeclaredReturnType();
  2870. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2871. canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
  2872. OldDeclaredReturnType)) {
  2873. QualType ResQT;
  2874. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2875. OldDeclaredReturnType->isObjCObjectPointerType())
  2876. // FIXME: This does the wrong thing for a deduced return type.
  2877. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2878. if (ResQT.isNull()) {
  2879. if (New->isCXXClassMember() && New->isOutOfLine())
  2880. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2881. << New << New->getReturnTypeSourceRange();
  2882. else
  2883. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2884. << New->getReturnTypeSourceRange();
  2885. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2886. << Old->getReturnTypeSourceRange();
  2887. return true;
  2888. }
  2889. else
  2890. NewQType = ResQT;
  2891. }
  2892. QualType OldReturnType = OldType->getReturnType();
  2893. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2894. if (OldReturnType != NewReturnType) {
  2895. // If this function has a deduced return type and has already been
  2896. // defined, copy the deduced value from the old declaration.
  2897. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2898. if (OldAT && OldAT->isDeduced()) {
  2899. New->setType(
  2900. SubstAutoType(New->getType(),
  2901. OldAT->isDependentType() ? Context.DependentTy
  2902. : OldAT->getDeducedType()));
  2903. NewQType = Context.getCanonicalType(
  2904. SubstAutoType(NewQType,
  2905. OldAT->isDependentType() ? Context.DependentTy
  2906. : OldAT->getDeducedType()));
  2907. }
  2908. }
  2909. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2910. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2911. if (OldMethod && NewMethod) {
  2912. // Preserve triviality.
  2913. NewMethod->setTrivial(OldMethod->isTrivial());
  2914. // MSVC allows explicit template specialization at class scope:
  2915. // 2 CXXMethodDecls referring to the same function will be injected.
  2916. // We don't want a redeclaration error.
  2917. bool IsClassScopeExplicitSpecialization =
  2918. OldMethod->isFunctionTemplateSpecialization() &&
  2919. NewMethod->isFunctionTemplateSpecialization();
  2920. bool isFriend = NewMethod->getFriendObjectKind();
  2921. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2922. !IsClassScopeExplicitSpecialization) {
  2923. // -- Member function declarations with the same name and the
  2924. // same parameter types cannot be overloaded if any of them
  2925. // is a static member function declaration.
  2926. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2927. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2928. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2929. return true;
  2930. }
  2931. // C++ [class.mem]p1:
  2932. // [...] A member shall not be declared twice in the
  2933. // member-specification, except that a nested class or member
  2934. // class template can be declared and then later defined.
  2935. if (!inTemplateInstantiation()) {
  2936. unsigned NewDiag;
  2937. if (isa<CXXConstructorDecl>(OldMethod))
  2938. NewDiag = diag::err_constructor_redeclared;
  2939. else if (isa<CXXDestructorDecl>(NewMethod))
  2940. NewDiag = diag::err_destructor_redeclared;
  2941. else if (isa<CXXConversionDecl>(NewMethod))
  2942. NewDiag = diag::err_conv_function_redeclared;
  2943. else
  2944. NewDiag = diag::err_member_redeclared;
  2945. Diag(New->getLocation(), NewDiag);
  2946. } else {
  2947. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2948. << New << New->getType();
  2949. }
  2950. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2951. return true;
  2952. // Complain if this is an explicit declaration of a special
  2953. // member that was initially declared implicitly.
  2954. //
  2955. // As an exception, it's okay to befriend such methods in order
  2956. // to permit the implicit constructor/destructor/operator calls.
  2957. } else if (OldMethod->isImplicit()) {
  2958. if (isFriend) {
  2959. NewMethod->setImplicit();
  2960. } else {
  2961. Diag(NewMethod->getLocation(),
  2962. diag::err_definition_of_implicitly_declared_member)
  2963. << New << getSpecialMember(OldMethod);
  2964. return true;
  2965. }
  2966. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2967. Diag(NewMethod->getLocation(),
  2968. diag::err_definition_of_explicitly_defaulted_member)
  2969. << getSpecialMember(OldMethod);
  2970. return true;
  2971. }
  2972. }
  2973. // C++11 [dcl.attr.noreturn]p1:
  2974. // The first declaration of a function shall specify the noreturn
  2975. // attribute if any declaration of that function specifies the noreturn
  2976. // attribute.
  2977. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2978. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2979. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2980. Diag(Old->getFirstDecl()->getLocation(),
  2981. diag::note_noreturn_missing_first_decl);
  2982. }
  2983. // C++11 [dcl.attr.depend]p2:
  2984. // The first declaration of a function shall specify the
  2985. // carries_dependency attribute for its declarator-id if any declaration
  2986. // of the function specifies the carries_dependency attribute.
  2987. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2988. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2989. Diag(CDA->getLocation(),
  2990. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2991. Diag(Old->getFirstDecl()->getLocation(),
  2992. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2993. }
  2994. // (C++98 8.3.5p3):
  2995. // All declarations for a function shall agree exactly in both the
  2996. // return type and the parameter-type-list.
  2997. // We also want to respect all the extended bits except noreturn.
  2998. // noreturn should now match unless the old type info didn't have it.
  2999. QualType OldQTypeForComparison = OldQType;
  3000. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  3001. auto *OldType = OldQType->castAs<FunctionProtoType>();
  3002. const FunctionType *OldTypeForComparison
  3003. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  3004. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  3005. assert(OldQTypeForComparison.isCanonical());
  3006. }
  3007. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3008. // As a special case, retain the language linkage from previous
  3009. // declarations of a friend function as an extension.
  3010. //
  3011. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3012. // and is useful because there's otherwise no way to specify language
  3013. // linkage within class scope.
  3014. //
  3015. // Check cautiously as the friend object kind isn't yet complete.
  3016. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3017. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3018. Diag(OldLocation, PrevDiag);
  3019. } else {
  3020. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3021. Diag(OldLocation, PrevDiag);
  3022. return true;
  3023. }
  3024. }
  3025. if (OldQTypeForComparison == NewQType)
  3026. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3027. // If the types are imprecise (due to dependent constructs in friends or
  3028. // local extern declarations), it's OK if they differ. We'll check again
  3029. // during instantiation.
  3030. if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
  3031. return false;
  3032. // Fall through for conflicting redeclarations and redefinitions.
  3033. }
  3034. // C: Function types need to be compatible, not identical. This handles
  3035. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3036. if (!getLangOpts().CPlusPlus &&
  3037. Context.typesAreCompatible(OldQType, NewQType)) {
  3038. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3039. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3040. const FunctionProtoType *OldProto = nullptr;
  3041. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3042. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3043. // The old declaration provided a function prototype, but the
  3044. // new declaration does not. Merge in the prototype.
  3045. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3046. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3047. NewQType =
  3048. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3049. OldProto->getExtProtoInfo());
  3050. New->setType(NewQType);
  3051. New->setHasInheritedPrototype();
  3052. // Synthesize parameters with the same types.
  3053. SmallVector<ParmVarDecl*, 16> Params;
  3054. for (const auto &ParamType : OldProto->param_types()) {
  3055. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3056. SourceLocation(), nullptr,
  3057. ParamType, /*TInfo=*/nullptr,
  3058. SC_None, nullptr);
  3059. Param->setScopeInfo(0, Params.size());
  3060. Param->setImplicit();
  3061. Params.push_back(Param);
  3062. }
  3063. New->setParams(Params);
  3064. }
  3065. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3066. }
  3067. // GNU C permits a K&R definition to follow a prototype declaration
  3068. // if the declared types of the parameters in the K&R definition
  3069. // match the types in the prototype declaration, even when the
  3070. // promoted types of the parameters from the K&R definition differ
  3071. // from the types in the prototype. GCC then keeps the types from
  3072. // the prototype.
  3073. //
  3074. // If a variadic prototype is followed by a non-variadic K&R definition,
  3075. // the K&R definition becomes variadic. This is sort of an edge case, but
  3076. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3077. // C99 6.9.1p8.
  3078. if (!getLangOpts().CPlusPlus &&
  3079. Old->hasPrototype() && !New->hasPrototype() &&
  3080. New->getType()->getAs<FunctionProtoType>() &&
  3081. Old->getNumParams() == New->getNumParams()) {
  3082. SmallVector<QualType, 16> ArgTypes;
  3083. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3084. const FunctionProtoType *OldProto
  3085. = Old->getType()->getAs<FunctionProtoType>();
  3086. const FunctionProtoType *NewProto
  3087. = New->getType()->getAs<FunctionProtoType>();
  3088. // Determine whether this is the GNU C extension.
  3089. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3090. NewProto->getReturnType());
  3091. bool LooseCompatible = !MergedReturn.isNull();
  3092. for (unsigned Idx = 0, End = Old->getNumParams();
  3093. LooseCompatible && Idx != End; ++Idx) {
  3094. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3095. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3096. if (Context.typesAreCompatible(OldParm->getType(),
  3097. NewProto->getParamType(Idx))) {
  3098. ArgTypes.push_back(NewParm->getType());
  3099. } else if (Context.typesAreCompatible(OldParm->getType(),
  3100. NewParm->getType(),
  3101. /*CompareUnqualified=*/true)) {
  3102. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3103. NewProto->getParamType(Idx) };
  3104. Warnings.push_back(Warn);
  3105. ArgTypes.push_back(NewParm->getType());
  3106. } else
  3107. LooseCompatible = false;
  3108. }
  3109. if (LooseCompatible) {
  3110. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3111. Diag(Warnings[Warn].NewParm->getLocation(),
  3112. diag::ext_param_promoted_not_compatible_with_prototype)
  3113. << Warnings[Warn].PromotedType
  3114. << Warnings[Warn].OldParm->getType();
  3115. if (Warnings[Warn].OldParm->getLocation().isValid())
  3116. Diag(Warnings[Warn].OldParm->getLocation(),
  3117. diag::note_previous_declaration);
  3118. }
  3119. if (MergeTypeWithOld)
  3120. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3121. OldProto->getExtProtoInfo()));
  3122. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3123. }
  3124. // Fall through to diagnose conflicting types.
  3125. }
  3126. // A function that has already been declared has been redeclared or
  3127. // defined with a different type; show an appropriate diagnostic.
  3128. // If the previous declaration was an implicitly-generated builtin
  3129. // declaration, then at the very least we should use a specialized note.
  3130. unsigned BuiltinID;
  3131. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3132. // If it's actually a library-defined builtin function like 'malloc'
  3133. // or 'printf', just warn about the incompatible redeclaration.
  3134. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3135. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3136. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3137. << Old << Old->getType();
  3138. // If this is a global redeclaration, just forget hereafter
  3139. // about the "builtin-ness" of the function.
  3140. //
  3141. // Doing this for local extern declarations is problematic. If
  3142. // the builtin declaration remains visible, a second invalid
  3143. // local declaration will produce a hard error; if it doesn't
  3144. // remain visible, a single bogus local redeclaration (which is
  3145. // actually only a warning) could break all the downstream code.
  3146. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3147. New->getIdentifier()->revertBuiltin();
  3148. return false;
  3149. }
  3150. PrevDiag = diag::note_previous_builtin_declaration;
  3151. }
  3152. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3153. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3154. return true;
  3155. }
  3156. /// Completes the merge of two function declarations that are
  3157. /// known to be compatible.
  3158. ///
  3159. /// This routine handles the merging of attributes and other
  3160. /// properties of function declarations from the old declaration to
  3161. /// the new declaration, once we know that New is in fact a
  3162. /// redeclaration of Old.
  3163. ///
  3164. /// \returns false
  3165. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3166. Scope *S, bool MergeTypeWithOld) {
  3167. // Merge the attributes
  3168. mergeDeclAttributes(New, Old);
  3169. // Merge "pure" flag.
  3170. if (Old->isPure())
  3171. New->setPure();
  3172. // Merge "used" flag.
  3173. if (Old->getMostRecentDecl()->isUsed(false))
  3174. New->setIsUsed();
  3175. // Merge attributes from the parameters. These can mismatch with K&R
  3176. // declarations.
  3177. if (New->getNumParams() == Old->getNumParams())
  3178. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3179. ParmVarDecl *NewParam = New->getParamDecl(i);
  3180. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3181. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3182. mergeParamDeclTypes(NewParam, OldParam, *this);
  3183. }
  3184. if (getLangOpts().CPlusPlus)
  3185. return MergeCXXFunctionDecl(New, Old, S);
  3186. // Merge the function types so the we get the composite types for the return
  3187. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3188. // was visible.
  3189. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3190. if (!Merged.isNull() && MergeTypeWithOld)
  3191. New->setType(Merged);
  3192. return false;
  3193. }
  3194. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3195. ObjCMethodDecl *oldMethod) {
  3196. // Merge the attributes, including deprecated/unavailable
  3197. AvailabilityMergeKind MergeKind =
  3198. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3199. ? AMK_ProtocolImplementation
  3200. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3201. : AMK_Override;
  3202. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3203. // Merge attributes from the parameters.
  3204. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3205. oe = oldMethod->param_end();
  3206. for (ObjCMethodDecl::param_iterator
  3207. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3208. ni != ne && oi != oe; ++ni, ++oi)
  3209. mergeParamDeclAttributes(*ni, *oi, *this);
  3210. CheckObjCMethodOverride(newMethod, oldMethod);
  3211. }
  3212. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3213. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3214. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3215. ? diag::err_redefinition_different_type
  3216. : diag::err_redeclaration_different_type)
  3217. << New->getDeclName() << New->getType() << Old->getType();
  3218. diag::kind PrevDiag;
  3219. SourceLocation OldLocation;
  3220. std::tie(PrevDiag, OldLocation)
  3221. = getNoteDiagForInvalidRedeclaration(Old, New);
  3222. S.Diag(OldLocation, PrevDiag);
  3223. New->setInvalidDecl();
  3224. }
  3225. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3226. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3227. /// emitting diagnostics as appropriate.
  3228. ///
  3229. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3230. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3231. /// is attached.
  3232. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3233. bool MergeTypeWithOld) {
  3234. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3235. return;
  3236. QualType MergedT;
  3237. if (getLangOpts().CPlusPlus) {
  3238. if (New->getType()->isUndeducedType()) {
  3239. // We don't know what the new type is until the initializer is attached.
  3240. return;
  3241. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3242. // These could still be something that needs exception specs checked.
  3243. return MergeVarDeclExceptionSpecs(New, Old);
  3244. }
  3245. // C++ [basic.link]p10:
  3246. // [...] the types specified by all declarations referring to a given
  3247. // object or function shall be identical, except that declarations for an
  3248. // array object can specify array types that differ by the presence or
  3249. // absence of a major array bound (8.3.4).
  3250. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3251. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3252. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3253. // We are merging a variable declaration New into Old. If it has an array
  3254. // bound, and that bound differs from Old's bound, we should diagnose the
  3255. // mismatch.
  3256. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3257. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3258. PrevVD = PrevVD->getPreviousDecl()) {
  3259. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3260. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3261. continue;
  3262. if (!Context.hasSameType(NewArray, PrevVDTy))
  3263. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3264. }
  3265. }
  3266. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3267. if (Context.hasSameType(OldArray->getElementType(),
  3268. NewArray->getElementType()))
  3269. MergedT = New->getType();
  3270. }
  3271. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3272. // has no array bound, it should not inherit one from Old, if Old is not
  3273. // visible.
  3274. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3275. if (Context.hasSameType(OldArray->getElementType(),
  3276. NewArray->getElementType()))
  3277. MergedT = Old->getType();
  3278. }
  3279. }
  3280. else if (New->getType()->isObjCObjectPointerType() &&
  3281. Old->getType()->isObjCObjectPointerType()) {
  3282. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3283. Old->getType());
  3284. }
  3285. } else {
  3286. // C 6.2.7p2:
  3287. // All declarations that refer to the same object or function shall have
  3288. // compatible type.
  3289. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3290. }
  3291. if (MergedT.isNull()) {
  3292. // It's OK if we couldn't merge types if either type is dependent, for a
  3293. // block-scope variable. In other cases (static data members of class
  3294. // templates, variable templates, ...), we require the types to be
  3295. // equivalent.
  3296. // FIXME: The C++ standard doesn't say anything about this.
  3297. if ((New->getType()->isDependentType() ||
  3298. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3299. // If the old type was dependent, we can't merge with it, so the new type
  3300. // becomes dependent for now. We'll reproduce the original type when we
  3301. // instantiate the TypeSourceInfo for the variable.
  3302. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3303. New->setType(Context.DependentTy);
  3304. return;
  3305. }
  3306. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3307. }
  3308. // Don't actually update the type on the new declaration if the old
  3309. // declaration was an extern declaration in a different scope.
  3310. if (MergeTypeWithOld)
  3311. New->setType(MergedT);
  3312. }
  3313. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3314. LookupResult &Previous) {
  3315. // C11 6.2.7p4:
  3316. // For an identifier with internal or external linkage declared
  3317. // in a scope in which a prior declaration of that identifier is
  3318. // visible, if the prior declaration specifies internal or
  3319. // external linkage, the type of the identifier at the later
  3320. // declaration becomes the composite type.
  3321. //
  3322. // If the variable isn't visible, we do not merge with its type.
  3323. if (Previous.isShadowed())
  3324. return false;
  3325. if (S.getLangOpts().CPlusPlus) {
  3326. // C++11 [dcl.array]p3:
  3327. // If there is a preceding declaration of the entity in the same
  3328. // scope in which the bound was specified, an omitted array bound
  3329. // is taken to be the same as in that earlier declaration.
  3330. return NewVD->isPreviousDeclInSameBlockScope() ||
  3331. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3332. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3333. } else {
  3334. // If the old declaration was function-local, don't merge with its
  3335. // type unless we're in the same function.
  3336. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3337. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3338. }
  3339. }
  3340. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3341. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3342. /// situation, merging decls or emitting diagnostics as appropriate.
  3343. ///
  3344. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3345. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3346. /// definitions here, since the initializer hasn't been attached.
  3347. ///
  3348. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3349. // If the new decl is already invalid, don't do any other checking.
  3350. if (New->isInvalidDecl())
  3351. return;
  3352. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3353. return;
  3354. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3355. // Verify the old decl was also a variable or variable template.
  3356. VarDecl *Old = nullptr;
  3357. VarTemplateDecl *OldTemplate = nullptr;
  3358. if (Previous.isSingleResult()) {
  3359. if (NewTemplate) {
  3360. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3361. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3362. if (auto *Shadow =
  3363. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3364. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3365. return New->setInvalidDecl();
  3366. } else {
  3367. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3368. if (auto *Shadow =
  3369. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3370. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3371. return New->setInvalidDecl();
  3372. }
  3373. }
  3374. if (!Old) {
  3375. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3376. << New->getDeclName();
  3377. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3378. New->getLocation());
  3379. return New->setInvalidDecl();
  3380. }
  3381. // Ensure the template parameters are compatible.
  3382. if (NewTemplate &&
  3383. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3384. OldTemplate->getTemplateParameters(),
  3385. /*Complain=*/true, TPL_TemplateMatch))
  3386. return New->setInvalidDecl();
  3387. // C++ [class.mem]p1:
  3388. // A member shall not be declared twice in the member-specification [...]
  3389. //
  3390. // Here, we need only consider static data members.
  3391. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3392. Diag(New->getLocation(), diag::err_duplicate_member)
  3393. << New->getIdentifier();
  3394. Diag(Old->getLocation(), diag::note_previous_declaration);
  3395. New->setInvalidDecl();
  3396. }
  3397. mergeDeclAttributes(New, Old);
  3398. // Warn if an already-declared variable is made a weak_import in a subsequent
  3399. // declaration
  3400. if (New->hasAttr<WeakImportAttr>() &&
  3401. Old->getStorageClass() == SC_None &&
  3402. !Old->hasAttr<WeakImportAttr>()) {
  3403. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3404. notePreviousDefinition(Old, New->getLocation());
  3405. // Remove weak_import attribute on new declaration.
  3406. New->dropAttr<WeakImportAttr>();
  3407. }
  3408. if (New->hasAttr<InternalLinkageAttr>() &&
  3409. !Old->hasAttr<InternalLinkageAttr>()) {
  3410. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3411. << New->getDeclName();
  3412. notePreviousDefinition(Old, New->getLocation());
  3413. New->dropAttr<InternalLinkageAttr>();
  3414. }
  3415. // Merge the types.
  3416. VarDecl *MostRecent = Old->getMostRecentDecl();
  3417. if (MostRecent != Old) {
  3418. MergeVarDeclTypes(New, MostRecent,
  3419. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3420. if (New->isInvalidDecl())
  3421. return;
  3422. }
  3423. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3424. if (New->isInvalidDecl())
  3425. return;
  3426. diag::kind PrevDiag;
  3427. SourceLocation OldLocation;
  3428. std::tie(PrevDiag, OldLocation) =
  3429. getNoteDiagForInvalidRedeclaration(Old, New);
  3430. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3431. if (New->getStorageClass() == SC_Static &&
  3432. !New->isStaticDataMember() &&
  3433. Old->hasExternalFormalLinkage()) {
  3434. if (getLangOpts().MicrosoftExt) {
  3435. Diag(New->getLocation(), diag::ext_static_non_static)
  3436. << New->getDeclName();
  3437. Diag(OldLocation, PrevDiag);
  3438. } else {
  3439. Diag(New->getLocation(), diag::err_static_non_static)
  3440. << New->getDeclName();
  3441. Diag(OldLocation, PrevDiag);
  3442. return New->setInvalidDecl();
  3443. }
  3444. }
  3445. // C99 6.2.2p4:
  3446. // For an identifier declared with the storage-class specifier
  3447. // extern in a scope in which a prior declaration of that
  3448. // identifier is visible,23) if the prior declaration specifies
  3449. // internal or external linkage, the linkage of the identifier at
  3450. // the later declaration is the same as the linkage specified at
  3451. // the prior declaration. If no prior declaration is visible, or
  3452. // if the prior declaration specifies no linkage, then the
  3453. // identifier has external linkage.
  3454. if (New->hasExternalStorage() && Old->hasLinkage())
  3455. /* Okay */;
  3456. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3457. !New->isStaticDataMember() &&
  3458. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3459. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3460. Diag(OldLocation, PrevDiag);
  3461. return New->setInvalidDecl();
  3462. }
  3463. // Check if extern is followed by non-extern and vice-versa.
  3464. if (New->hasExternalStorage() &&
  3465. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3466. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3467. Diag(OldLocation, PrevDiag);
  3468. return New->setInvalidDecl();
  3469. }
  3470. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3471. !New->hasExternalStorage()) {
  3472. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3473. Diag(OldLocation, PrevDiag);
  3474. return New->setInvalidDecl();
  3475. }
  3476. if (CheckRedeclarationModuleOwnership(New, Old))
  3477. return;
  3478. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3479. // FIXME: The test for external storage here seems wrong? We still
  3480. // need to check for mismatches.
  3481. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3482. // Don't complain about out-of-line definitions of static members.
  3483. !(Old->getLexicalDeclContext()->isRecord() &&
  3484. !New->getLexicalDeclContext()->isRecord())) {
  3485. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3486. Diag(OldLocation, PrevDiag);
  3487. return New->setInvalidDecl();
  3488. }
  3489. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3490. if (VarDecl *Def = Old->getDefinition()) {
  3491. // C++1z [dcl.fcn.spec]p4:
  3492. // If the definition of a variable appears in a translation unit before
  3493. // its first declaration as inline, the program is ill-formed.
  3494. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3495. Diag(Def->getLocation(), diag::note_previous_definition);
  3496. }
  3497. }
  3498. // If this redeclaration makes the variable inline, we may need to add it to
  3499. // UndefinedButUsed.
  3500. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3501. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3502. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3503. SourceLocation()));
  3504. if (New->getTLSKind() != Old->getTLSKind()) {
  3505. if (!Old->getTLSKind()) {
  3506. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3507. Diag(OldLocation, PrevDiag);
  3508. } else if (!New->getTLSKind()) {
  3509. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3510. Diag(OldLocation, PrevDiag);
  3511. } else {
  3512. // Do not allow redeclaration to change the variable between requiring
  3513. // static and dynamic initialization.
  3514. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3515. // declaration to determine the kind. Do we need to be compatible here?
  3516. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3517. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3518. Diag(OldLocation, PrevDiag);
  3519. }
  3520. }
  3521. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3522. if (getLangOpts().CPlusPlus &&
  3523. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3524. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3525. Old->getCanonicalDecl()->isConstexpr()) {
  3526. // This definition won't be a definition any more once it's been merged.
  3527. Diag(New->getLocation(),
  3528. diag::warn_deprecated_redundant_constexpr_static_def);
  3529. } else if (VarDecl *Def = Old->getDefinition()) {
  3530. if (checkVarDeclRedefinition(Def, New))
  3531. return;
  3532. }
  3533. }
  3534. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3535. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3536. Diag(OldLocation, PrevDiag);
  3537. New->setInvalidDecl();
  3538. return;
  3539. }
  3540. // Merge "used" flag.
  3541. if (Old->getMostRecentDecl()->isUsed(false))
  3542. New->setIsUsed();
  3543. // Keep a chain of previous declarations.
  3544. New->setPreviousDecl(Old);
  3545. if (NewTemplate)
  3546. NewTemplate->setPreviousDecl(OldTemplate);
  3547. adjustDeclContextForDeclaratorDecl(New, Old);
  3548. // Inherit access appropriately.
  3549. New->setAccess(Old->getAccess());
  3550. if (NewTemplate)
  3551. NewTemplate->setAccess(New->getAccess());
  3552. if (Old->isInline())
  3553. New->setImplicitlyInline();
  3554. }
  3555. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3556. SourceManager &SrcMgr = getSourceManager();
  3557. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3558. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3559. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3560. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3561. auto &HSI = PP.getHeaderSearchInfo();
  3562. StringRef HdrFilename =
  3563. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3564. auto noteFromModuleOrInclude = [&](Module *Mod,
  3565. SourceLocation IncLoc) -> bool {
  3566. // Redefinition errors with modules are common with non modular mapped
  3567. // headers, example: a non-modular header H in module A that also gets
  3568. // included directly in a TU. Pointing twice to the same header/definition
  3569. // is confusing, try to get better diagnostics when modules is on.
  3570. if (IncLoc.isValid()) {
  3571. if (Mod) {
  3572. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3573. << HdrFilename.str() << Mod->getFullModuleName();
  3574. if (!Mod->DefinitionLoc.isInvalid())
  3575. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3576. << Mod->getFullModuleName();
  3577. } else {
  3578. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3579. << HdrFilename.str();
  3580. }
  3581. return true;
  3582. }
  3583. return false;
  3584. };
  3585. // Is it the same file and same offset? Provide more information on why
  3586. // this leads to a redefinition error.
  3587. bool EmittedDiag = false;
  3588. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3589. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3590. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3591. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3592. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3593. // If the header has no guards, emit a note suggesting one.
  3594. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3595. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3596. if (EmittedDiag)
  3597. return;
  3598. }
  3599. // Redefinition coming from different files or couldn't do better above.
  3600. if (Old->getLocation().isValid())
  3601. Diag(Old->getLocation(), diag::note_previous_definition);
  3602. }
  3603. /// We've just determined that \p Old and \p New both appear to be definitions
  3604. /// of the same variable. Either diagnose or fix the problem.
  3605. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3606. if (!hasVisibleDefinition(Old) &&
  3607. (New->getFormalLinkage() == InternalLinkage ||
  3608. New->isInline() ||
  3609. New->getDescribedVarTemplate() ||
  3610. New->getNumTemplateParameterLists() ||
  3611. New->getDeclContext()->isDependentContext())) {
  3612. // The previous definition is hidden, and multiple definitions are
  3613. // permitted (in separate TUs). Demote this to a declaration.
  3614. New->demoteThisDefinitionToDeclaration();
  3615. // Make the canonical definition visible.
  3616. if (auto *OldTD = Old->getDescribedVarTemplate())
  3617. makeMergedDefinitionVisible(OldTD);
  3618. makeMergedDefinitionVisible(Old);
  3619. return false;
  3620. } else {
  3621. Diag(New->getLocation(), diag::err_redefinition) << New;
  3622. notePreviousDefinition(Old, New->getLocation());
  3623. New->setInvalidDecl();
  3624. return true;
  3625. }
  3626. }
  3627. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3628. /// no declarator (e.g. "struct foo;") is parsed.
  3629. Decl *
  3630. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3631. RecordDecl *&AnonRecord) {
  3632. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3633. AnonRecord);
  3634. }
  3635. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3636. // disambiguate entities defined in different scopes.
  3637. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3638. // compatibility.
  3639. // We will pick our mangling number depending on which version of MSVC is being
  3640. // targeted.
  3641. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3642. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3643. ? S->getMSCurManglingNumber()
  3644. : S->getMSLastManglingNumber();
  3645. }
  3646. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3647. if (!Context.getLangOpts().CPlusPlus)
  3648. return;
  3649. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3650. // If this tag is the direct child of a class, number it if
  3651. // it is anonymous.
  3652. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3653. return;
  3654. MangleNumberingContext &MCtx =
  3655. Context.getManglingNumberContext(Tag->getParent());
  3656. Context.setManglingNumber(
  3657. Tag, MCtx.getManglingNumber(
  3658. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3659. return;
  3660. }
  3661. // If this tag isn't a direct child of a class, number it if it is local.
  3662. Decl *ManglingContextDecl;
  3663. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3664. Tag->getDeclContext(), ManglingContextDecl)) {
  3665. Context.setManglingNumber(
  3666. Tag, MCtx->getManglingNumber(
  3667. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3668. }
  3669. }
  3670. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3671. TypedefNameDecl *NewTD) {
  3672. if (TagFromDeclSpec->isInvalidDecl())
  3673. return;
  3674. // Do nothing if the tag already has a name for linkage purposes.
  3675. if (TagFromDeclSpec->hasNameForLinkage())
  3676. return;
  3677. // A well-formed anonymous tag must always be a TUK_Definition.
  3678. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3679. // The type must match the tag exactly; no qualifiers allowed.
  3680. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3681. Context.getTagDeclType(TagFromDeclSpec))) {
  3682. if (getLangOpts().CPlusPlus)
  3683. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3684. return;
  3685. }
  3686. // If we've already computed linkage for the anonymous tag, then
  3687. // adding a typedef name for the anonymous decl can change that
  3688. // linkage, which might be a serious problem. Diagnose this as
  3689. // unsupported and ignore the typedef name. TODO: we should
  3690. // pursue this as a language defect and establish a formal rule
  3691. // for how to handle it.
  3692. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3693. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3694. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3695. tagLoc = getLocForEndOfToken(tagLoc);
  3696. llvm::SmallString<40> textToInsert;
  3697. textToInsert += ' ';
  3698. textToInsert += NewTD->getIdentifier()->getName();
  3699. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3700. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3701. return;
  3702. }
  3703. // Otherwise, set this is the anon-decl typedef for the tag.
  3704. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3705. }
  3706. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3707. switch (T) {
  3708. case DeclSpec::TST_class:
  3709. return 0;
  3710. case DeclSpec::TST_struct:
  3711. return 1;
  3712. case DeclSpec::TST_interface:
  3713. return 2;
  3714. case DeclSpec::TST_union:
  3715. return 3;
  3716. case DeclSpec::TST_enum:
  3717. return 4;
  3718. default:
  3719. llvm_unreachable("unexpected type specifier");
  3720. }
  3721. }
  3722. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3723. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3724. /// parameters to cope with template friend declarations.
  3725. Decl *
  3726. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3727. MultiTemplateParamsArg TemplateParams,
  3728. bool IsExplicitInstantiation,
  3729. RecordDecl *&AnonRecord) {
  3730. Decl *TagD = nullptr;
  3731. TagDecl *Tag = nullptr;
  3732. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3733. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3734. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3735. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3736. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3737. TagD = DS.getRepAsDecl();
  3738. if (!TagD) // We probably had an error
  3739. return nullptr;
  3740. // Note that the above type specs guarantee that the
  3741. // type rep is a Decl, whereas in many of the others
  3742. // it's a Type.
  3743. if (isa<TagDecl>(TagD))
  3744. Tag = cast<TagDecl>(TagD);
  3745. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3746. Tag = CTD->getTemplatedDecl();
  3747. }
  3748. if (Tag) {
  3749. handleTagNumbering(Tag, S);
  3750. Tag->setFreeStanding();
  3751. if (Tag->isInvalidDecl())
  3752. return Tag;
  3753. }
  3754. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3755. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3756. // or incomplete types shall not be restrict-qualified."
  3757. if (TypeQuals & DeclSpec::TQ_restrict)
  3758. Diag(DS.getRestrictSpecLoc(),
  3759. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3760. << DS.getSourceRange();
  3761. }
  3762. if (DS.isInlineSpecified())
  3763. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3764. << getLangOpts().CPlusPlus17;
  3765. if (DS.isConstexprSpecified()) {
  3766. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3767. // and definitions of functions and variables.
  3768. if (Tag)
  3769. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3770. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3771. else
  3772. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3773. // Don't emit warnings after this error.
  3774. return TagD;
  3775. }
  3776. DiagnoseFunctionSpecifiers(DS);
  3777. if (DS.isFriendSpecified()) {
  3778. // If we're dealing with a decl but not a TagDecl, assume that
  3779. // whatever routines created it handled the friendship aspect.
  3780. if (TagD && !Tag)
  3781. return nullptr;
  3782. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3783. }
  3784. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3785. bool IsExplicitSpecialization =
  3786. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3787. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3788. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3789. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3790. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3791. // nested-name-specifier unless it is an explicit instantiation
  3792. // or an explicit specialization.
  3793. //
  3794. // FIXME: We allow class template partial specializations here too, per the
  3795. // obvious intent of DR1819.
  3796. //
  3797. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3798. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3799. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3800. return nullptr;
  3801. }
  3802. // Track whether this decl-specifier declares anything.
  3803. bool DeclaresAnything = true;
  3804. // Handle anonymous struct definitions.
  3805. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3806. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3807. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3808. if (getLangOpts().CPlusPlus ||
  3809. Record->getDeclContext()->isRecord()) {
  3810. // If CurContext is a DeclContext that can contain statements,
  3811. // RecursiveASTVisitor won't visit the decls that
  3812. // BuildAnonymousStructOrUnion() will put into CurContext.
  3813. // Also store them here so that they can be part of the
  3814. // DeclStmt that gets created in this case.
  3815. // FIXME: Also return the IndirectFieldDecls created by
  3816. // BuildAnonymousStructOr union, for the same reason?
  3817. if (CurContext->isFunctionOrMethod())
  3818. AnonRecord = Record;
  3819. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3820. Context.getPrintingPolicy());
  3821. }
  3822. DeclaresAnything = false;
  3823. }
  3824. }
  3825. // C11 6.7.2.1p2:
  3826. // A struct-declaration that does not declare an anonymous structure or
  3827. // anonymous union shall contain a struct-declarator-list.
  3828. //
  3829. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3830. // did not permit a struct-declaration without a struct-declarator-list.
  3831. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3832. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3833. // Check for Microsoft C extension: anonymous struct/union member.
  3834. // Handle 2 kinds of anonymous struct/union:
  3835. // struct STRUCT;
  3836. // union UNION;
  3837. // and
  3838. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3839. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3840. if ((Tag && Tag->getDeclName()) ||
  3841. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3842. RecordDecl *Record = nullptr;
  3843. if (Tag)
  3844. Record = dyn_cast<RecordDecl>(Tag);
  3845. else if (const RecordType *RT =
  3846. DS.getRepAsType().get()->getAsStructureType())
  3847. Record = RT->getDecl();
  3848. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3849. Record = UT->getDecl();
  3850. if (Record && getLangOpts().MicrosoftExt) {
  3851. Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
  3852. << Record->isUnion() << DS.getSourceRange();
  3853. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3854. }
  3855. DeclaresAnything = false;
  3856. }
  3857. }
  3858. // Skip all the checks below if we have a type error.
  3859. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3860. (TagD && TagD->isInvalidDecl()))
  3861. return TagD;
  3862. if (getLangOpts().CPlusPlus &&
  3863. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3864. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3865. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3866. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3867. DeclaresAnything = false;
  3868. if (!DS.isMissingDeclaratorOk()) {
  3869. // Customize diagnostic for a typedef missing a name.
  3870. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3871. Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
  3872. << DS.getSourceRange();
  3873. else
  3874. DeclaresAnything = false;
  3875. }
  3876. if (DS.isModulePrivateSpecified() &&
  3877. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3878. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3879. << Tag->getTagKind()
  3880. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3881. ActOnDocumentableDecl(TagD);
  3882. // C 6.7/2:
  3883. // A declaration [...] shall declare at least a declarator [...], a tag,
  3884. // or the members of an enumeration.
  3885. // C++ [dcl.dcl]p3:
  3886. // [If there are no declarators], and except for the declaration of an
  3887. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3888. // names into the program, or shall redeclare a name introduced by a
  3889. // previous declaration.
  3890. if (!DeclaresAnything) {
  3891. // In C, we allow this as a (popular) extension / bug. Don't bother
  3892. // producing further diagnostics for redundant qualifiers after this.
  3893. Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
  3894. return TagD;
  3895. }
  3896. // C++ [dcl.stc]p1:
  3897. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3898. // init-declarator-list of the declaration shall not be empty.
  3899. // C++ [dcl.fct.spec]p1:
  3900. // If a cv-qualifier appears in a decl-specifier-seq, the
  3901. // init-declarator-list of the declaration shall not be empty.
  3902. //
  3903. // Spurious qualifiers here appear to be valid in C.
  3904. unsigned DiagID = diag::warn_standalone_specifier;
  3905. if (getLangOpts().CPlusPlus)
  3906. DiagID = diag::ext_standalone_specifier;
  3907. // Note that a linkage-specification sets a storage class, but
  3908. // 'extern "C" struct foo;' is actually valid and not theoretically
  3909. // useless.
  3910. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3911. if (SCS == DeclSpec::SCS_mutable)
  3912. // Since mutable is not a viable storage class specifier in C, there is
  3913. // no reason to treat it as an extension. Instead, diagnose as an error.
  3914. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3915. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3916. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3917. << DeclSpec::getSpecifierName(SCS);
  3918. }
  3919. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3920. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3921. << DeclSpec::getSpecifierName(TSCS);
  3922. if (DS.getTypeQualifiers()) {
  3923. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3924. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3925. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3926. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3927. // Restrict is covered above.
  3928. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3929. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3930. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3931. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3932. }
  3933. // Warn about ignored type attributes, for example:
  3934. // __attribute__((aligned)) struct A;
  3935. // Attributes should be placed after tag to apply to type declaration.
  3936. if (!DS.getAttributes().empty()) {
  3937. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3938. if (TypeSpecType == DeclSpec::TST_class ||
  3939. TypeSpecType == DeclSpec::TST_struct ||
  3940. TypeSpecType == DeclSpec::TST_interface ||
  3941. TypeSpecType == DeclSpec::TST_union ||
  3942. TypeSpecType == DeclSpec::TST_enum) {
  3943. for (const ParsedAttr &AL : DS.getAttributes())
  3944. Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
  3945. << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3946. }
  3947. }
  3948. return TagD;
  3949. }
  3950. /// We are trying to inject an anonymous member into the given scope;
  3951. /// check if there's an existing declaration that can't be overloaded.
  3952. ///
  3953. /// \return true if this is a forbidden redeclaration
  3954. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3955. Scope *S,
  3956. DeclContext *Owner,
  3957. DeclarationName Name,
  3958. SourceLocation NameLoc,
  3959. bool IsUnion) {
  3960. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3961. Sema::ForVisibleRedeclaration);
  3962. if (!SemaRef.LookupName(R, S)) return false;
  3963. // Pick a representative declaration.
  3964. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3965. assert(PrevDecl && "Expected a non-null Decl");
  3966. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3967. return false;
  3968. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3969. << IsUnion << Name;
  3970. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3971. return true;
  3972. }
  3973. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3974. /// anonymous struct or union AnonRecord into the owning context Owner
  3975. /// and scope S. This routine will be invoked just after we realize
  3976. /// that an unnamed union or struct is actually an anonymous union or
  3977. /// struct, e.g.,
  3978. ///
  3979. /// @code
  3980. /// union {
  3981. /// int i;
  3982. /// float f;
  3983. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3984. /// // f into the surrounding scope.x
  3985. /// @endcode
  3986. ///
  3987. /// This routine is recursive, injecting the names of nested anonymous
  3988. /// structs/unions into the owning context and scope as well.
  3989. static bool
  3990. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3991. RecordDecl *AnonRecord, AccessSpecifier AS,
  3992. SmallVectorImpl<NamedDecl *> &Chaining) {
  3993. bool Invalid = false;
  3994. // Look every FieldDecl and IndirectFieldDecl with a name.
  3995. for (auto *D : AnonRecord->decls()) {
  3996. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3997. cast<NamedDecl>(D)->getDeclName()) {
  3998. ValueDecl *VD = cast<ValueDecl>(D);
  3999. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  4000. VD->getLocation(),
  4001. AnonRecord->isUnion())) {
  4002. // C++ [class.union]p2:
  4003. // The names of the members of an anonymous union shall be
  4004. // distinct from the names of any other entity in the
  4005. // scope in which the anonymous union is declared.
  4006. Invalid = true;
  4007. } else {
  4008. // C++ [class.union]p2:
  4009. // For the purpose of name lookup, after the anonymous union
  4010. // definition, the members of the anonymous union are
  4011. // considered to have been defined in the scope in which the
  4012. // anonymous union is declared.
  4013. unsigned OldChainingSize = Chaining.size();
  4014. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4015. Chaining.append(IF->chain_begin(), IF->chain_end());
  4016. else
  4017. Chaining.push_back(VD);
  4018. assert(Chaining.size() >= 2);
  4019. NamedDecl **NamedChain =
  4020. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4021. for (unsigned i = 0; i < Chaining.size(); i++)
  4022. NamedChain[i] = Chaining[i];
  4023. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4024. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4025. VD->getType(), {NamedChain, Chaining.size()});
  4026. for (const auto *Attr : VD->attrs())
  4027. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4028. IndirectField->setAccess(AS);
  4029. IndirectField->setImplicit();
  4030. SemaRef.PushOnScopeChains(IndirectField, S);
  4031. // That includes picking up the appropriate access specifier.
  4032. if (AS != AS_none) IndirectField->setAccess(AS);
  4033. Chaining.resize(OldChainingSize);
  4034. }
  4035. }
  4036. }
  4037. return Invalid;
  4038. }
  4039. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4040. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4041. /// illegal input values are mapped to SC_None.
  4042. static StorageClass
  4043. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4044. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4045. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4046. "Parser allowed 'typedef' as storage class VarDecl.");
  4047. switch (StorageClassSpec) {
  4048. case DeclSpec::SCS_unspecified: return SC_None;
  4049. case DeclSpec::SCS_extern:
  4050. if (DS.isExternInLinkageSpec())
  4051. return SC_None;
  4052. return SC_Extern;
  4053. case DeclSpec::SCS_static: return SC_Static;
  4054. case DeclSpec::SCS_auto: return SC_Auto;
  4055. case DeclSpec::SCS_register: return SC_Register;
  4056. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4057. // Illegal SCSs map to None: error reporting is up to the caller.
  4058. case DeclSpec::SCS_mutable: // Fall through.
  4059. case DeclSpec::SCS_typedef: return SC_None;
  4060. }
  4061. llvm_unreachable("unknown storage class specifier");
  4062. }
  4063. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4064. assert(Record->hasInClassInitializer());
  4065. for (const auto *I : Record->decls()) {
  4066. const auto *FD = dyn_cast<FieldDecl>(I);
  4067. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4068. FD = IFD->getAnonField();
  4069. if (FD && FD->hasInClassInitializer())
  4070. return FD->getLocation();
  4071. }
  4072. llvm_unreachable("couldn't find in-class initializer");
  4073. }
  4074. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4075. SourceLocation DefaultInitLoc) {
  4076. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4077. return;
  4078. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4079. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4080. }
  4081. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4082. CXXRecordDecl *AnonUnion) {
  4083. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4084. return;
  4085. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4086. }
  4087. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4088. /// anonymous structure or union. Anonymous unions are a C++ feature
  4089. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4090. /// are a C11 feature and GNU C++ extension.
  4091. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4092. AccessSpecifier AS,
  4093. RecordDecl *Record,
  4094. const PrintingPolicy &Policy) {
  4095. DeclContext *Owner = Record->getDeclContext();
  4096. // Diagnose whether this anonymous struct/union is an extension.
  4097. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4098. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4099. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4100. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4101. else if (!Record->isUnion() && !getLangOpts().C11)
  4102. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4103. // C and C++ require different kinds of checks for anonymous
  4104. // structs/unions.
  4105. bool Invalid = false;
  4106. if (getLangOpts().CPlusPlus) {
  4107. const char *PrevSpec = nullptr;
  4108. unsigned DiagID;
  4109. if (Record->isUnion()) {
  4110. // C++ [class.union]p6:
  4111. // C++17 [class.union.anon]p2:
  4112. // Anonymous unions declared in a named namespace or in the
  4113. // global namespace shall be declared static.
  4114. DeclContext *OwnerScope = Owner->getRedeclContext();
  4115. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4116. (OwnerScope->isTranslationUnit() ||
  4117. (OwnerScope->isNamespace() &&
  4118. !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
  4119. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4120. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4121. // Recover by adding 'static'.
  4122. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4123. PrevSpec, DiagID, Policy);
  4124. }
  4125. // C++ [class.union]p6:
  4126. // A storage class is not allowed in a declaration of an
  4127. // anonymous union in a class scope.
  4128. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4129. isa<RecordDecl>(Owner)) {
  4130. Diag(DS.getStorageClassSpecLoc(),
  4131. diag::err_anonymous_union_with_storage_spec)
  4132. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4133. // Recover by removing the storage specifier.
  4134. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4135. SourceLocation(),
  4136. PrevSpec, DiagID, Context.getPrintingPolicy());
  4137. }
  4138. }
  4139. // Ignore const/volatile/restrict qualifiers.
  4140. if (DS.getTypeQualifiers()) {
  4141. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4142. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4143. << Record->isUnion() << "const"
  4144. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4145. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4146. Diag(DS.getVolatileSpecLoc(),
  4147. diag::ext_anonymous_struct_union_qualified)
  4148. << Record->isUnion() << "volatile"
  4149. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4150. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4151. Diag(DS.getRestrictSpecLoc(),
  4152. diag::ext_anonymous_struct_union_qualified)
  4153. << Record->isUnion() << "restrict"
  4154. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4155. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4156. Diag(DS.getAtomicSpecLoc(),
  4157. diag::ext_anonymous_struct_union_qualified)
  4158. << Record->isUnion() << "_Atomic"
  4159. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4160. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4161. Diag(DS.getUnalignedSpecLoc(),
  4162. diag::ext_anonymous_struct_union_qualified)
  4163. << Record->isUnion() << "__unaligned"
  4164. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4165. DS.ClearTypeQualifiers();
  4166. }
  4167. // C++ [class.union]p2:
  4168. // The member-specification of an anonymous union shall only
  4169. // define non-static data members. [Note: nested types and
  4170. // functions cannot be declared within an anonymous union. ]
  4171. for (auto *Mem : Record->decls()) {
  4172. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4173. // C++ [class.union]p3:
  4174. // An anonymous union shall not have private or protected
  4175. // members (clause 11).
  4176. assert(FD->getAccess() != AS_none);
  4177. if (FD->getAccess() != AS_public) {
  4178. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4179. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4180. Invalid = true;
  4181. }
  4182. // C++ [class.union]p1
  4183. // An object of a class with a non-trivial constructor, a non-trivial
  4184. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4185. // assignment operator cannot be a member of a union, nor can an
  4186. // array of such objects.
  4187. if (CheckNontrivialField(FD))
  4188. Invalid = true;
  4189. } else if (Mem->isImplicit()) {
  4190. // Any implicit members are fine.
  4191. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4192. // This is a type that showed up in an
  4193. // elaborated-type-specifier inside the anonymous struct or
  4194. // union, but which actually declares a type outside of the
  4195. // anonymous struct or union. It's okay.
  4196. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4197. if (!MemRecord->isAnonymousStructOrUnion() &&
  4198. MemRecord->getDeclName()) {
  4199. // Visual C++ allows type definition in anonymous struct or union.
  4200. if (getLangOpts().MicrosoftExt)
  4201. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4202. << Record->isUnion();
  4203. else {
  4204. // This is a nested type declaration.
  4205. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4206. << Record->isUnion();
  4207. Invalid = true;
  4208. }
  4209. } else {
  4210. // This is an anonymous type definition within another anonymous type.
  4211. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4212. // not part of standard C++.
  4213. Diag(MemRecord->getLocation(),
  4214. diag::ext_anonymous_record_with_anonymous_type)
  4215. << Record->isUnion();
  4216. }
  4217. } else if (isa<AccessSpecDecl>(Mem)) {
  4218. // Any access specifier is fine.
  4219. } else if (isa<StaticAssertDecl>(Mem)) {
  4220. // In C++1z, static_assert declarations are also fine.
  4221. } else {
  4222. // We have something that isn't a non-static data
  4223. // member. Complain about it.
  4224. unsigned DK = diag::err_anonymous_record_bad_member;
  4225. if (isa<TypeDecl>(Mem))
  4226. DK = diag::err_anonymous_record_with_type;
  4227. else if (isa<FunctionDecl>(Mem))
  4228. DK = diag::err_anonymous_record_with_function;
  4229. else if (isa<VarDecl>(Mem))
  4230. DK = diag::err_anonymous_record_with_static;
  4231. // Visual C++ allows type definition in anonymous struct or union.
  4232. if (getLangOpts().MicrosoftExt &&
  4233. DK == diag::err_anonymous_record_with_type)
  4234. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4235. << Record->isUnion();
  4236. else {
  4237. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4238. Invalid = true;
  4239. }
  4240. }
  4241. }
  4242. // C++11 [class.union]p8 (DR1460):
  4243. // At most one variant member of a union may have a
  4244. // brace-or-equal-initializer.
  4245. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4246. Owner->isRecord())
  4247. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4248. cast<CXXRecordDecl>(Record));
  4249. }
  4250. if (!Record->isUnion() && !Owner->isRecord()) {
  4251. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4252. << getLangOpts().CPlusPlus;
  4253. Invalid = true;
  4254. }
  4255. // Mock up a declarator.
  4256. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4257. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4258. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4259. // Create a declaration for this anonymous struct/union.
  4260. NamedDecl *Anon = nullptr;
  4261. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4262. Anon = FieldDecl::Create(
  4263. Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
  4264. /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
  4265. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4266. /*InitStyle=*/ICIS_NoInit);
  4267. Anon->setAccess(AS);
  4268. if (getLangOpts().CPlusPlus)
  4269. FieldCollector->Add(cast<FieldDecl>(Anon));
  4270. } else {
  4271. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4272. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4273. if (SCSpec == DeclSpec::SCS_mutable) {
  4274. // mutable can only appear on non-static class members, so it's always
  4275. // an error here
  4276. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4277. Invalid = true;
  4278. SC = SC_None;
  4279. }
  4280. Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
  4281. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4282. Context.getTypeDeclType(Record), TInfo, SC);
  4283. // Default-initialize the implicit variable. This initialization will be
  4284. // trivial in almost all cases, except if a union member has an in-class
  4285. // initializer:
  4286. // union { int n = 0; };
  4287. ActOnUninitializedDecl(Anon);
  4288. }
  4289. Anon->setImplicit();
  4290. // Mark this as an anonymous struct/union type.
  4291. Record->setAnonymousStructOrUnion(true);
  4292. // Add the anonymous struct/union object to the current
  4293. // context. We'll be referencing this object when we refer to one of
  4294. // its members.
  4295. Owner->addDecl(Anon);
  4296. // Inject the members of the anonymous struct/union into the owning
  4297. // context and into the identifier resolver chain for name lookup
  4298. // purposes.
  4299. SmallVector<NamedDecl*, 2> Chain;
  4300. Chain.push_back(Anon);
  4301. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4302. Invalid = true;
  4303. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4304. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4305. Decl *ManglingContextDecl;
  4306. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4307. NewVD->getDeclContext(), ManglingContextDecl)) {
  4308. Context.setManglingNumber(
  4309. NewVD, MCtx->getManglingNumber(
  4310. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4311. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4312. }
  4313. }
  4314. }
  4315. if (Invalid)
  4316. Anon->setInvalidDecl();
  4317. return Anon;
  4318. }
  4319. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4320. /// Microsoft C anonymous structure.
  4321. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4322. /// Example:
  4323. ///
  4324. /// struct A { int a; };
  4325. /// struct B { struct A; int b; };
  4326. ///
  4327. /// void foo() {
  4328. /// B var;
  4329. /// var.a = 3;
  4330. /// }
  4331. ///
  4332. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4333. RecordDecl *Record) {
  4334. assert(Record && "expected a record!");
  4335. // Mock up a declarator.
  4336. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4337. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4338. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4339. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4340. QualType RecTy = Context.getTypeDeclType(Record);
  4341. // Create a declaration for this anonymous struct.
  4342. NamedDecl *Anon =
  4343. FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
  4344. /*IdentifierInfo=*/nullptr, RecTy, TInfo,
  4345. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4346. /*InitStyle=*/ICIS_NoInit);
  4347. Anon->setImplicit();
  4348. // Add the anonymous struct object to the current context.
  4349. CurContext->addDecl(Anon);
  4350. // Inject the members of the anonymous struct into the current
  4351. // context and into the identifier resolver chain for name lookup
  4352. // purposes.
  4353. SmallVector<NamedDecl*, 2> Chain;
  4354. Chain.push_back(Anon);
  4355. RecordDecl *RecordDef = Record->getDefinition();
  4356. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4357. diag::err_field_incomplete) ||
  4358. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4359. AS_none, Chain)) {
  4360. Anon->setInvalidDecl();
  4361. ParentDecl->setInvalidDecl();
  4362. }
  4363. return Anon;
  4364. }
  4365. /// GetNameForDeclarator - Determine the full declaration name for the
  4366. /// given Declarator.
  4367. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4368. return GetNameFromUnqualifiedId(D.getName());
  4369. }
  4370. /// Retrieves the declaration name from a parsed unqualified-id.
  4371. DeclarationNameInfo
  4372. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4373. DeclarationNameInfo NameInfo;
  4374. NameInfo.setLoc(Name.StartLocation);
  4375. switch (Name.getKind()) {
  4376. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4377. case UnqualifiedIdKind::IK_Identifier:
  4378. NameInfo.setName(Name.Identifier);
  4379. return NameInfo;
  4380. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4381. // C++ [temp.deduct.guide]p3:
  4382. // The simple-template-id shall name a class template specialization.
  4383. // The template-name shall be the same identifier as the template-name
  4384. // of the simple-template-id.
  4385. // These together intend to imply that the template-name shall name a
  4386. // class template.
  4387. // FIXME: template<typename T> struct X {};
  4388. // template<typename T> using Y = X<T>;
  4389. // Y(int) -> Y<int>;
  4390. // satisfies these rules but does not name a class template.
  4391. TemplateName TN = Name.TemplateName.get().get();
  4392. auto *Template = TN.getAsTemplateDecl();
  4393. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4394. Diag(Name.StartLocation,
  4395. diag::err_deduction_guide_name_not_class_template)
  4396. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4397. if (Template)
  4398. Diag(Template->getLocation(), diag::note_template_decl_here);
  4399. return DeclarationNameInfo();
  4400. }
  4401. NameInfo.setName(
  4402. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4403. return NameInfo;
  4404. }
  4405. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4406. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4407. Name.OperatorFunctionId.Operator));
  4408. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4409. = Name.OperatorFunctionId.SymbolLocations[0];
  4410. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4411. = Name.EndLocation.getRawEncoding();
  4412. return NameInfo;
  4413. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4414. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4415. Name.Identifier));
  4416. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4417. return NameInfo;
  4418. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4419. TypeSourceInfo *TInfo;
  4420. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4421. if (Ty.isNull())
  4422. return DeclarationNameInfo();
  4423. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4424. Context.getCanonicalType(Ty)));
  4425. NameInfo.setNamedTypeInfo(TInfo);
  4426. return NameInfo;
  4427. }
  4428. case UnqualifiedIdKind::IK_ConstructorName: {
  4429. TypeSourceInfo *TInfo;
  4430. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4431. if (Ty.isNull())
  4432. return DeclarationNameInfo();
  4433. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4434. Context.getCanonicalType(Ty)));
  4435. NameInfo.setNamedTypeInfo(TInfo);
  4436. return NameInfo;
  4437. }
  4438. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4439. // In well-formed code, we can only have a constructor
  4440. // template-id that refers to the current context, so go there
  4441. // to find the actual type being constructed.
  4442. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4443. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4444. return DeclarationNameInfo();
  4445. // Determine the type of the class being constructed.
  4446. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4447. // FIXME: Check two things: that the template-id names the same type as
  4448. // CurClassType, and that the template-id does not occur when the name
  4449. // was qualified.
  4450. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4451. Context.getCanonicalType(CurClassType)));
  4452. // FIXME: should we retrieve TypeSourceInfo?
  4453. NameInfo.setNamedTypeInfo(nullptr);
  4454. return NameInfo;
  4455. }
  4456. case UnqualifiedIdKind::IK_DestructorName: {
  4457. TypeSourceInfo *TInfo;
  4458. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4459. if (Ty.isNull())
  4460. return DeclarationNameInfo();
  4461. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4462. Context.getCanonicalType(Ty)));
  4463. NameInfo.setNamedTypeInfo(TInfo);
  4464. return NameInfo;
  4465. }
  4466. case UnqualifiedIdKind::IK_TemplateId: {
  4467. TemplateName TName = Name.TemplateId->Template.get();
  4468. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4469. return Context.getNameForTemplate(TName, TNameLoc);
  4470. }
  4471. } // switch (Name.getKind())
  4472. llvm_unreachable("Unknown name kind");
  4473. }
  4474. static QualType getCoreType(QualType Ty) {
  4475. do {
  4476. if (Ty->isPointerType() || Ty->isReferenceType())
  4477. Ty = Ty->getPointeeType();
  4478. else if (Ty->isArrayType())
  4479. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4480. else
  4481. return Ty.withoutLocalFastQualifiers();
  4482. } while (true);
  4483. }
  4484. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4485. /// and Definition have "nearly" matching parameters. This heuristic is
  4486. /// used to improve diagnostics in the case where an out-of-line function
  4487. /// definition doesn't match any declaration within the class or namespace.
  4488. /// Also sets Params to the list of indices to the parameters that differ
  4489. /// between the declaration and the definition. If hasSimilarParameters
  4490. /// returns true and Params is empty, then all of the parameters match.
  4491. static bool hasSimilarParameters(ASTContext &Context,
  4492. FunctionDecl *Declaration,
  4493. FunctionDecl *Definition,
  4494. SmallVectorImpl<unsigned> &Params) {
  4495. Params.clear();
  4496. if (Declaration->param_size() != Definition->param_size())
  4497. return false;
  4498. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4499. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4500. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4501. // The parameter types are identical
  4502. if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
  4503. continue;
  4504. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4505. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4506. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4507. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4508. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4509. (DeclTyName && DeclTyName == DefTyName))
  4510. Params.push_back(Idx);
  4511. else // The two parameters aren't even close
  4512. return false;
  4513. }
  4514. return true;
  4515. }
  4516. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4517. /// declarator needs to be rebuilt in the current instantiation.
  4518. /// Any bits of declarator which appear before the name are valid for
  4519. /// consideration here. That's specifically the type in the decl spec
  4520. /// and the base type in any member-pointer chunks.
  4521. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4522. DeclarationName Name) {
  4523. // The types we specifically need to rebuild are:
  4524. // - typenames, typeofs, and decltypes
  4525. // - types which will become injected class names
  4526. // Of course, we also need to rebuild any type referencing such a
  4527. // type. It's safest to just say "dependent", but we call out a
  4528. // few cases here.
  4529. DeclSpec &DS = D.getMutableDeclSpec();
  4530. switch (DS.getTypeSpecType()) {
  4531. case DeclSpec::TST_typename:
  4532. case DeclSpec::TST_typeofType:
  4533. case DeclSpec::TST_underlyingType:
  4534. case DeclSpec::TST_atomic: {
  4535. // Grab the type from the parser.
  4536. TypeSourceInfo *TSI = nullptr;
  4537. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4538. if (T.isNull() || !T->isDependentType()) break;
  4539. // Make sure there's a type source info. This isn't really much
  4540. // of a waste; most dependent types should have type source info
  4541. // attached already.
  4542. if (!TSI)
  4543. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4544. // Rebuild the type in the current instantiation.
  4545. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4546. if (!TSI) return true;
  4547. // Store the new type back in the decl spec.
  4548. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4549. DS.UpdateTypeRep(LocType);
  4550. break;
  4551. }
  4552. case DeclSpec::TST_decltype:
  4553. case DeclSpec::TST_typeofExpr: {
  4554. Expr *E = DS.getRepAsExpr();
  4555. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4556. if (Result.isInvalid()) return true;
  4557. DS.UpdateExprRep(Result.get());
  4558. break;
  4559. }
  4560. default:
  4561. // Nothing to do for these decl specs.
  4562. break;
  4563. }
  4564. // It doesn't matter what order we do this in.
  4565. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4566. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4567. // The only type information in the declarator which can come
  4568. // before the declaration name is the base type of a member
  4569. // pointer.
  4570. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4571. continue;
  4572. // Rebuild the scope specifier in-place.
  4573. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4574. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4575. return true;
  4576. }
  4577. return false;
  4578. }
  4579. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4580. D.setFunctionDefinitionKind(FDK_Declaration);
  4581. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4582. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4583. Dcl && Dcl->getDeclContext()->isFileContext())
  4584. Dcl->setTopLevelDeclInObjCContainer();
  4585. if (getLangOpts().OpenCL)
  4586. setCurrentOpenCLExtensionForDecl(Dcl);
  4587. return Dcl;
  4588. }
  4589. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4590. /// If T is the name of a class, then each of the following shall have a
  4591. /// name different from T:
  4592. /// - every static data member of class T;
  4593. /// - every member function of class T
  4594. /// - every member of class T that is itself a type;
  4595. /// \returns true if the declaration name violates these rules.
  4596. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4597. DeclarationNameInfo NameInfo) {
  4598. DeclarationName Name = NameInfo.getName();
  4599. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4600. while (Record && Record->isAnonymousStructOrUnion())
  4601. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4602. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4603. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4604. return true;
  4605. }
  4606. return false;
  4607. }
  4608. /// Diagnose a declaration whose declarator-id has the given
  4609. /// nested-name-specifier.
  4610. ///
  4611. /// \param SS The nested-name-specifier of the declarator-id.
  4612. ///
  4613. /// \param DC The declaration context to which the nested-name-specifier
  4614. /// resolves.
  4615. ///
  4616. /// \param Name The name of the entity being declared.
  4617. ///
  4618. /// \param Loc The location of the name of the entity being declared.
  4619. ///
  4620. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4621. /// we're declaring an explicit / partial specialization / instantiation.
  4622. ///
  4623. /// \returns true if we cannot safely recover from this error, false otherwise.
  4624. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4625. DeclarationName Name,
  4626. SourceLocation Loc, bool IsTemplateId) {
  4627. DeclContext *Cur = CurContext;
  4628. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4629. Cur = Cur->getParent();
  4630. // If the user provided a superfluous scope specifier that refers back to the
  4631. // class in which the entity is already declared, diagnose and ignore it.
  4632. //
  4633. // class X {
  4634. // void X::f();
  4635. // };
  4636. //
  4637. // Note, it was once ill-formed to give redundant qualification in all
  4638. // contexts, but that rule was removed by DR482.
  4639. if (Cur->Equals(DC)) {
  4640. if (Cur->isRecord()) {
  4641. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4642. : diag::err_member_extra_qualification)
  4643. << Name << FixItHint::CreateRemoval(SS.getRange());
  4644. SS.clear();
  4645. } else {
  4646. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4647. }
  4648. return false;
  4649. }
  4650. // Check whether the qualifying scope encloses the scope of the original
  4651. // declaration. For a template-id, we perform the checks in
  4652. // CheckTemplateSpecializationScope.
  4653. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4654. if (Cur->isRecord())
  4655. Diag(Loc, diag::err_member_qualification)
  4656. << Name << SS.getRange();
  4657. else if (isa<TranslationUnitDecl>(DC))
  4658. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4659. << Name << SS.getRange();
  4660. else if (isa<FunctionDecl>(Cur))
  4661. Diag(Loc, diag::err_invalid_declarator_in_function)
  4662. << Name << SS.getRange();
  4663. else if (isa<BlockDecl>(Cur))
  4664. Diag(Loc, diag::err_invalid_declarator_in_block)
  4665. << Name << SS.getRange();
  4666. else
  4667. Diag(Loc, diag::err_invalid_declarator_scope)
  4668. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4669. return true;
  4670. }
  4671. if (Cur->isRecord()) {
  4672. // Cannot qualify members within a class.
  4673. Diag(Loc, diag::err_member_qualification)
  4674. << Name << SS.getRange();
  4675. SS.clear();
  4676. // C++ constructors and destructors with incorrect scopes can break
  4677. // our AST invariants by having the wrong underlying types. If
  4678. // that's the case, then drop this declaration entirely.
  4679. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4680. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4681. !Context.hasSameType(Name.getCXXNameType(),
  4682. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4683. return true;
  4684. return false;
  4685. }
  4686. // C++11 [dcl.meaning]p1:
  4687. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4688. // not begin with a decltype-specifer"
  4689. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4690. while (SpecLoc.getPrefix())
  4691. SpecLoc = SpecLoc.getPrefix();
  4692. if (dyn_cast_or_null<DecltypeType>(
  4693. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4694. Diag(Loc, diag::err_decltype_in_declarator)
  4695. << SpecLoc.getTypeLoc().getSourceRange();
  4696. return false;
  4697. }
  4698. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4699. MultiTemplateParamsArg TemplateParamLists) {
  4700. // TODO: consider using NameInfo for diagnostic.
  4701. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4702. DeclarationName Name = NameInfo.getName();
  4703. // All of these full declarators require an identifier. If it doesn't have
  4704. // one, the ParsedFreeStandingDeclSpec action should be used.
  4705. if (D.isDecompositionDeclarator()) {
  4706. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4707. } else if (!Name) {
  4708. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4709. Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
  4710. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4711. return nullptr;
  4712. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4713. return nullptr;
  4714. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4715. // we find one that is.
  4716. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4717. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4718. S = S->getParent();
  4719. DeclContext *DC = CurContext;
  4720. if (D.getCXXScopeSpec().isInvalid())
  4721. D.setInvalidType();
  4722. else if (D.getCXXScopeSpec().isSet()) {
  4723. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4724. UPPC_DeclarationQualifier))
  4725. return nullptr;
  4726. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4727. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4728. if (!DC || isa<EnumDecl>(DC)) {
  4729. // If we could not compute the declaration context, it's because the
  4730. // declaration context is dependent but does not refer to a class,
  4731. // class template, or class template partial specialization. Complain
  4732. // and return early, to avoid the coming semantic disaster.
  4733. Diag(D.getIdentifierLoc(),
  4734. diag::err_template_qualified_declarator_no_match)
  4735. << D.getCXXScopeSpec().getScopeRep()
  4736. << D.getCXXScopeSpec().getRange();
  4737. return nullptr;
  4738. }
  4739. bool IsDependentContext = DC->isDependentContext();
  4740. if (!IsDependentContext &&
  4741. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4742. return nullptr;
  4743. // If a class is incomplete, do not parse entities inside it.
  4744. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4745. Diag(D.getIdentifierLoc(),
  4746. diag::err_member_def_undefined_record)
  4747. << Name << DC << D.getCXXScopeSpec().getRange();
  4748. return nullptr;
  4749. }
  4750. if (!D.getDeclSpec().isFriendSpecified()) {
  4751. if (diagnoseQualifiedDeclaration(
  4752. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4753. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4754. if (DC->isRecord())
  4755. return nullptr;
  4756. D.setInvalidType();
  4757. }
  4758. }
  4759. // Check whether we need to rebuild the type of the given
  4760. // declaration in the current instantiation.
  4761. if (EnteringContext && IsDependentContext &&
  4762. TemplateParamLists.size() != 0) {
  4763. ContextRAII SavedContext(*this, DC);
  4764. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4765. D.setInvalidType();
  4766. }
  4767. }
  4768. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4769. QualType R = TInfo->getType();
  4770. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4771. UPPC_DeclarationType))
  4772. D.setInvalidType();
  4773. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4774. forRedeclarationInCurContext());
  4775. // See if this is a redefinition of a variable in the same scope.
  4776. if (!D.getCXXScopeSpec().isSet()) {
  4777. bool IsLinkageLookup = false;
  4778. bool CreateBuiltins = false;
  4779. // If the declaration we're planning to build will be a function
  4780. // or object with linkage, then look for another declaration with
  4781. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4782. //
  4783. // If the declaration we're planning to build will be declared with
  4784. // external linkage in the translation unit, create any builtin with
  4785. // the same name.
  4786. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4787. /* Do nothing*/;
  4788. else if (CurContext->isFunctionOrMethod() &&
  4789. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4790. R->isFunctionType())) {
  4791. IsLinkageLookup = true;
  4792. CreateBuiltins =
  4793. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4794. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4795. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4796. CreateBuiltins = true;
  4797. if (IsLinkageLookup) {
  4798. Previous.clear(LookupRedeclarationWithLinkage);
  4799. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4800. }
  4801. LookupName(Previous, S, CreateBuiltins);
  4802. } else { // Something like "int foo::x;"
  4803. LookupQualifiedName(Previous, DC);
  4804. // C++ [dcl.meaning]p1:
  4805. // When the declarator-id is qualified, the declaration shall refer to a
  4806. // previously declared member of the class or namespace to which the
  4807. // qualifier refers (or, in the case of a namespace, of an element of the
  4808. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4809. // thereof; [...]
  4810. //
  4811. // Note that we already checked the context above, and that we do not have
  4812. // enough information to make sure that Previous contains the declaration
  4813. // we want to match. For example, given:
  4814. //
  4815. // class X {
  4816. // void f();
  4817. // void f(float);
  4818. // };
  4819. //
  4820. // void X::f(int) { } // ill-formed
  4821. //
  4822. // In this case, Previous will point to the overload set
  4823. // containing the two f's declared in X, but neither of them
  4824. // matches.
  4825. // C++ [dcl.meaning]p1:
  4826. // [...] the member shall not merely have been introduced by a
  4827. // using-declaration in the scope of the class or namespace nominated by
  4828. // the nested-name-specifier of the declarator-id.
  4829. RemoveUsingDecls(Previous);
  4830. }
  4831. if (Previous.isSingleResult() &&
  4832. Previous.getFoundDecl()->isTemplateParameter()) {
  4833. // Maybe we will complain about the shadowed template parameter.
  4834. if (!D.isInvalidType())
  4835. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4836. Previous.getFoundDecl());
  4837. // Just pretend that we didn't see the previous declaration.
  4838. Previous.clear();
  4839. }
  4840. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4841. // Forget that the previous declaration is the injected-class-name.
  4842. Previous.clear();
  4843. // In C++, the previous declaration we find might be a tag type
  4844. // (class or enum). In this case, the new declaration will hide the
  4845. // tag type. Note that this applies to functions, function templates, and
  4846. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4847. if (Previous.isSingleTagDecl() &&
  4848. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4849. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4850. Previous.clear();
  4851. // Check that there are no default arguments other than in the parameters
  4852. // of a function declaration (C++ only).
  4853. if (getLangOpts().CPlusPlus)
  4854. CheckExtraCXXDefaultArguments(D);
  4855. NamedDecl *New;
  4856. bool AddToScope = true;
  4857. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4858. if (TemplateParamLists.size()) {
  4859. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4860. return nullptr;
  4861. }
  4862. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4863. } else if (R->isFunctionType()) {
  4864. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4865. TemplateParamLists,
  4866. AddToScope);
  4867. } else {
  4868. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4869. AddToScope);
  4870. }
  4871. if (!New)
  4872. return nullptr;
  4873. // If this has an identifier and is not a function template specialization,
  4874. // add it to the scope stack.
  4875. if (New->getDeclName() && AddToScope)
  4876. PushOnScopeChains(New, S);
  4877. if (isInOpenMPDeclareTargetContext())
  4878. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4879. return New;
  4880. }
  4881. /// Helper method to turn variable array types into constant array
  4882. /// types in certain situations which would otherwise be errors (for
  4883. /// GCC compatibility).
  4884. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4885. ASTContext &Context,
  4886. bool &SizeIsNegative,
  4887. llvm::APSInt &Oversized) {
  4888. // This method tries to turn a variable array into a constant
  4889. // array even when the size isn't an ICE. This is necessary
  4890. // for compatibility with code that depends on gcc's buggy
  4891. // constant expression folding, like struct {char x[(int)(char*)2];}
  4892. SizeIsNegative = false;
  4893. Oversized = 0;
  4894. if (T->isDependentType())
  4895. return QualType();
  4896. QualifierCollector Qs;
  4897. const Type *Ty = Qs.strip(T);
  4898. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4899. QualType Pointee = PTy->getPointeeType();
  4900. QualType FixedType =
  4901. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4902. Oversized);
  4903. if (FixedType.isNull()) return FixedType;
  4904. FixedType = Context.getPointerType(FixedType);
  4905. return Qs.apply(Context, FixedType);
  4906. }
  4907. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4908. QualType Inner = PTy->getInnerType();
  4909. QualType FixedType =
  4910. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4911. Oversized);
  4912. if (FixedType.isNull()) return FixedType;
  4913. FixedType = Context.getParenType(FixedType);
  4914. return Qs.apply(Context, FixedType);
  4915. }
  4916. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4917. if (!VLATy)
  4918. return QualType();
  4919. // FIXME: We should probably handle this case
  4920. if (VLATy->getElementType()->isVariablyModifiedType())
  4921. return QualType();
  4922. Expr::EvalResult Result;
  4923. if (!VLATy->getSizeExpr() ||
  4924. !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
  4925. return QualType();
  4926. llvm::APSInt Res = Result.Val.getInt();
  4927. // Check whether the array size is negative.
  4928. if (Res.isSigned() && Res.isNegative()) {
  4929. SizeIsNegative = true;
  4930. return QualType();
  4931. }
  4932. // Check whether the array is too large to be addressed.
  4933. unsigned ActiveSizeBits
  4934. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4935. Res);
  4936. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4937. Oversized = Res;
  4938. return QualType();
  4939. }
  4940. return Context.getConstantArrayType(VLATy->getElementType(),
  4941. Res, ArrayType::Normal, 0);
  4942. }
  4943. static void
  4944. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4945. SrcTL = SrcTL.getUnqualifiedLoc();
  4946. DstTL = DstTL.getUnqualifiedLoc();
  4947. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4948. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4949. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4950. DstPTL.getPointeeLoc());
  4951. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4952. return;
  4953. }
  4954. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4955. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4956. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4957. DstPTL.getInnerLoc());
  4958. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4959. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4960. return;
  4961. }
  4962. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4963. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4964. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4965. TypeLoc DstElemTL = DstATL.getElementLoc();
  4966. DstElemTL.initializeFullCopy(SrcElemTL);
  4967. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4968. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4969. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4970. }
  4971. /// Helper method to turn variable array types into constant array
  4972. /// types in certain situations which would otherwise be errors (for
  4973. /// GCC compatibility).
  4974. static TypeSourceInfo*
  4975. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4976. ASTContext &Context,
  4977. bool &SizeIsNegative,
  4978. llvm::APSInt &Oversized) {
  4979. QualType FixedTy
  4980. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4981. SizeIsNegative, Oversized);
  4982. if (FixedTy.isNull())
  4983. return nullptr;
  4984. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  4985. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  4986. FixedTInfo->getTypeLoc());
  4987. return FixedTInfo;
  4988. }
  4989. /// Register the given locally-scoped extern "C" declaration so
  4990. /// that it can be found later for redeclarations. We include any extern "C"
  4991. /// declaration that is not visible in the translation unit here, not just
  4992. /// function-scope declarations.
  4993. void
  4994. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  4995. if (!getLangOpts().CPlusPlus &&
  4996. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  4997. // Don't need to track declarations in the TU in C.
  4998. return;
  4999. // Note that we have a locally-scoped external with this name.
  5000. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5001. }
  5002. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5003. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5004. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5005. return Result.empty() ? nullptr : *Result.begin();
  5006. }
  5007. /// Diagnose function specifiers on a declaration of an identifier that
  5008. /// does not identify a function.
  5009. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5010. // FIXME: We should probably indicate the identifier in question to avoid
  5011. // confusion for constructs like "virtual int a(), b;"
  5012. if (DS.isVirtualSpecified())
  5013. Diag(DS.getVirtualSpecLoc(),
  5014. diag::err_virtual_non_function);
  5015. if (DS.isExplicitSpecified())
  5016. Diag(DS.getExplicitSpecLoc(),
  5017. diag::err_explicit_non_function);
  5018. if (DS.isNoreturnSpecified())
  5019. Diag(DS.getNoreturnSpecLoc(),
  5020. diag::err_noreturn_non_function);
  5021. }
  5022. NamedDecl*
  5023. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5024. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5025. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5026. if (D.getCXXScopeSpec().isSet()) {
  5027. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5028. << D.getCXXScopeSpec().getRange();
  5029. D.setInvalidType();
  5030. // Pretend we didn't see the scope specifier.
  5031. DC = CurContext;
  5032. Previous.clear();
  5033. }
  5034. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5035. if (D.getDeclSpec().isInlineSpecified())
  5036. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5037. << getLangOpts().CPlusPlus17;
  5038. if (D.getDeclSpec().isConstexprSpecified())
  5039. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5040. << 1;
  5041. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5042. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5043. Diag(D.getName().StartLocation,
  5044. diag::err_deduction_guide_invalid_specifier)
  5045. << "typedef";
  5046. else
  5047. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5048. << D.getName().getSourceRange();
  5049. return nullptr;
  5050. }
  5051. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5052. if (!NewTD) return nullptr;
  5053. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5054. ProcessDeclAttributes(S, NewTD, D);
  5055. CheckTypedefForVariablyModifiedType(S, NewTD);
  5056. bool Redeclaration = D.isRedeclaration();
  5057. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5058. D.setRedeclaration(Redeclaration);
  5059. return ND;
  5060. }
  5061. void
  5062. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5063. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5064. // then it shall have block scope.
  5065. // Note that variably modified types must be fixed before merging the decl so
  5066. // that redeclarations will match.
  5067. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5068. QualType T = TInfo->getType();
  5069. if (T->isVariablyModifiedType()) {
  5070. setFunctionHasBranchProtectedScope();
  5071. if (S->getFnParent() == nullptr) {
  5072. bool SizeIsNegative;
  5073. llvm::APSInt Oversized;
  5074. TypeSourceInfo *FixedTInfo =
  5075. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5076. SizeIsNegative,
  5077. Oversized);
  5078. if (FixedTInfo) {
  5079. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5080. NewTD->setTypeSourceInfo(FixedTInfo);
  5081. } else {
  5082. if (SizeIsNegative)
  5083. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5084. else if (T->isVariableArrayType())
  5085. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5086. else if (Oversized.getBoolValue())
  5087. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5088. << Oversized.toString(10);
  5089. else
  5090. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5091. NewTD->setInvalidDecl();
  5092. }
  5093. }
  5094. }
  5095. }
  5096. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5097. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5098. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5099. NamedDecl*
  5100. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5101. LookupResult &Previous, bool &Redeclaration) {
  5102. // Find the shadowed declaration before filtering for scope.
  5103. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5104. // Merge the decl with the existing one if appropriate. If the decl is
  5105. // in an outer scope, it isn't the same thing.
  5106. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5107. /*AllowInlineNamespace*/false);
  5108. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5109. if (!Previous.empty()) {
  5110. Redeclaration = true;
  5111. MergeTypedefNameDecl(S, NewTD, Previous);
  5112. }
  5113. if (ShadowedDecl && !Redeclaration)
  5114. CheckShadow(NewTD, ShadowedDecl, Previous);
  5115. // If this is the C FILE type, notify the AST context.
  5116. if (IdentifierInfo *II = NewTD->getIdentifier())
  5117. if (!NewTD->isInvalidDecl() &&
  5118. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5119. if (II->isStr("FILE"))
  5120. Context.setFILEDecl(NewTD);
  5121. else if (II->isStr("jmp_buf"))
  5122. Context.setjmp_bufDecl(NewTD);
  5123. else if (II->isStr("sigjmp_buf"))
  5124. Context.setsigjmp_bufDecl(NewTD);
  5125. else if (II->isStr("ucontext_t"))
  5126. Context.setucontext_tDecl(NewTD);
  5127. }
  5128. return NewTD;
  5129. }
  5130. /// Determines whether the given declaration is an out-of-scope
  5131. /// previous declaration.
  5132. ///
  5133. /// This routine should be invoked when name lookup has found a
  5134. /// previous declaration (PrevDecl) that is not in the scope where a
  5135. /// new declaration by the same name is being introduced. If the new
  5136. /// declaration occurs in a local scope, previous declarations with
  5137. /// linkage may still be considered previous declarations (C99
  5138. /// 6.2.2p4-5, C++ [basic.link]p6).
  5139. ///
  5140. /// \param PrevDecl the previous declaration found by name
  5141. /// lookup
  5142. ///
  5143. /// \param DC the context in which the new declaration is being
  5144. /// declared.
  5145. ///
  5146. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5147. /// for a new delcaration with the same name.
  5148. static bool
  5149. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5150. ASTContext &Context) {
  5151. if (!PrevDecl)
  5152. return false;
  5153. if (!PrevDecl->hasLinkage())
  5154. return false;
  5155. if (Context.getLangOpts().CPlusPlus) {
  5156. // C++ [basic.link]p6:
  5157. // If there is a visible declaration of an entity with linkage
  5158. // having the same name and type, ignoring entities declared
  5159. // outside the innermost enclosing namespace scope, the block
  5160. // scope declaration declares that same entity and receives the
  5161. // linkage of the previous declaration.
  5162. DeclContext *OuterContext = DC->getRedeclContext();
  5163. if (!OuterContext->isFunctionOrMethod())
  5164. // This rule only applies to block-scope declarations.
  5165. return false;
  5166. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5167. if (PrevOuterContext->isRecord())
  5168. // We found a member function: ignore it.
  5169. return false;
  5170. // Find the innermost enclosing namespace for the new and
  5171. // previous declarations.
  5172. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5173. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5174. // The previous declaration is in a different namespace, so it
  5175. // isn't the same function.
  5176. if (!OuterContext->Equals(PrevOuterContext))
  5177. return false;
  5178. }
  5179. return true;
  5180. }
  5181. static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
  5182. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5183. if (!SS.isSet()) return;
  5184. DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
  5185. }
  5186. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5187. QualType type = decl->getType();
  5188. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5189. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5190. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5191. unsigned kind = -1U;
  5192. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5193. if (var->hasAttr<BlocksAttr>())
  5194. kind = 0; // __block
  5195. else if (!var->hasLocalStorage())
  5196. kind = 1; // global
  5197. } else if (isa<ObjCIvarDecl>(decl)) {
  5198. kind = 3; // ivar
  5199. } else if (isa<FieldDecl>(decl)) {
  5200. kind = 2; // field
  5201. }
  5202. if (kind != -1U) {
  5203. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5204. << kind;
  5205. }
  5206. } else if (lifetime == Qualifiers::OCL_None) {
  5207. // Try to infer lifetime.
  5208. if (!type->isObjCLifetimeType())
  5209. return false;
  5210. lifetime = type->getObjCARCImplicitLifetime();
  5211. type = Context.getLifetimeQualifiedType(type, lifetime);
  5212. decl->setType(type);
  5213. }
  5214. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5215. // Thread-local variables cannot have lifetime.
  5216. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5217. var->getTLSKind()) {
  5218. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5219. << var->getType();
  5220. return true;
  5221. }
  5222. }
  5223. return false;
  5224. }
  5225. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5226. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5227. // the wrong linkage.
  5228. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5229. // 'weak' only applies to declarations with external linkage.
  5230. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5231. if (!ND.isExternallyVisible()) {
  5232. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5233. ND.dropAttr<WeakAttr>();
  5234. }
  5235. }
  5236. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5237. if (ND.isExternallyVisible()) {
  5238. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5239. ND.dropAttr<WeakRefAttr>();
  5240. ND.dropAttr<AliasAttr>();
  5241. }
  5242. }
  5243. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5244. if (VD->hasInit()) {
  5245. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5246. assert(VD->isThisDeclarationADefinition() &&
  5247. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5248. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5249. VD->dropAttr<AliasAttr>();
  5250. }
  5251. }
  5252. }
  5253. // 'selectany' only applies to externally visible variable declarations.
  5254. // It does not apply to functions.
  5255. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5256. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5257. S.Diag(Attr->getLocation(),
  5258. diag::err_attribute_selectany_non_extern_data);
  5259. ND.dropAttr<SelectAnyAttr>();
  5260. }
  5261. }
  5262. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5263. // dll attributes require external linkage. Static locals may have external
  5264. // linkage but still cannot be explicitly imported or exported.
  5265. auto *VD = dyn_cast<VarDecl>(&ND);
  5266. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5267. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5268. << &ND << Attr;
  5269. ND.setInvalidDecl();
  5270. }
  5271. }
  5272. // Virtual functions cannot be marked as 'notail'.
  5273. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5274. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5275. if (MD->isVirtual()) {
  5276. S.Diag(ND.getLocation(),
  5277. diag::err_invalid_attribute_on_virtual_function)
  5278. << Attr;
  5279. ND.dropAttr<NotTailCalledAttr>();
  5280. }
  5281. // Check the attributes on the function type, if any.
  5282. if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
  5283. // Don't declare this variable in the second operand of the for-statement;
  5284. // GCC miscompiles that by ending its lifetime before evaluating the
  5285. // third operand. See gcc.gnu.org/PR86769.
  5286. AttributedTypeLoc ATL;
  5287. for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
  5288. (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
  5289. TL = ATL.getModifiedLoc()) {
  5290. // The [[lifetimebound]] attribute can be applied to the implicit object
  5291. // parameter of a non-static member function (other than a ctor or dtor)
  5292. // by applying it to the function type.
  5293. if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
  5294. const auto *MD = dyn_cast<CXXMethodDecl>(FD);
  5295. if (!MD || MD->isStatic()) {
  5296. S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
  5297. << !MD << A->getRange();
  5298. } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
  5299. S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
  5300. << isa<CXXDestructorDecl>(MD) << A->getRange();
  5301. }
  5302. }
  5303. }
  5304. }
  5305. }
  5306. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5307. NamedDecl *NewDecl,
  5308. bool IsSpecialization,
  5309. bool IsDefinition) {
  5310. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5311. return;
  5312. bool IsTemplate = false;
  5313. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5314. OldDecl = OldTD->getTemplatedDecl();
  5315. IsTemplate = true;
  5316. if (!IsSpecialization)
  5317. IsDefinition = false;
  5318. }
  5319. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5320. NewDecl = NewTD->getTemplatedDecl();
  5321. IsTemplate = true;
  5322. }
  5323. if (!OldDecl || !NewDecl)
  5324. return;
  5325. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5326. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5327. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5328. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5329. // dllimport and dllexport are inheritable attributes so we have to exclude
  5330. // inherited attribute instances.
  5331. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5332. (NewExportAttr && !NewExportAttr->isInherited());
  5333. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5334. // the only exception being explicit specializations.
  5335. // Implicitly generated declarations are also excluded for now because there
  5336. // is no other way to switch these to use dllimport or dllexport.
  5337. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5338. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5339. // Allow with a warning for free functions and global variables.
  5340. bool JustWarn = false;
  5341. if (!OldDecl->isCXXClassMember()) {
  5342. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5343. if (VD && !VD->getDescribedVarTemplate())
  5344. JustWarn = true;
  5345. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5346. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5347. JustWarn = true;
  5348. }
  5349. // We cannot change a declaration that's been used because IR has already
  5350. // been emitted. Dllimported functions will still work though (modulo
  5351. // address equality) as they can use the thunk.
  5352. if (OldDecl->isUsed())
  5353. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5354. JustWarn = false;
  5355. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5356. : diag::err_attribute_dll_redeclaration;
  5357. S.Diag(NewDecl->getLocation(), DiagID)
  5358. << NewDecl
  5359. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5360. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5361. if (!JustWarn) {
  5362. NewDecl->setInvalidDecl();
  5363. return;
  5364. }
  5365. }
  5366. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5367. // exceptions being inline function definitions (except for function
  5368. // templates), local extern declarations, qualified friend declarations or
  5369. // special MSVC extension: in the last case, the declaration is treated as if
  5370. // it were marked dllexport.
  5371. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5372. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5373. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5374. // Ignore static data because out-of-line definitions are diagnosed
  5375. // separately.
  5376. IsStaticDataMember = VD->isStaticDataMember();
  5377. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5378. VarDecl::DeclarationOnly;
  5379. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5380. IsInline = FD->isInlined();
  5381. IsQualifiedFriend = FD->getQualifier() &&
  5382. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5383. }
  5384. if (OldImportAttr && !HasNewAttr &&
  5385. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5386. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5387. if (IsMicrosoft && IsDefinition) {
  5388. S.Diag(NewDecl->getLocation(),
  5389. diag::warn_redeclaration_without_import_attribute)
  5390. << NewDecl;
  5391. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5392. NewDecl->dropAttr<DLLImportAttr>();
  5393. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5394. NewImportAttr->getRange(), S.Context,
  5395. NewImportAttr->getSpellingListIndex()));
  5396. } else {
  5397. S.Diag(NewDecl->getLocation(),
  5398. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5399. << NewDecl << OldImportAttr;
  5400. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5401. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5402. OldDecl->dropAttr<DLLImportAttr>();
  5403. NewDecl->dropAttr<DLLImportAttr>();
  5404. }
  5405. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5406. // In MinGW, seeing a function declared inline drops the dllimport
  5407. // attribute.
  5408. OldDecl->dropAttr<DLLImportAttr>();
  5409. NewDecl->dropAttr<DLLImportAttr>();
  5410. S.Diag(NewDecl->getLocation(),
  5411. diag::warn_dllimport_dropped_from_inline_function)
  5412. << NewDecl << OldImportAttr;
  5413. }
  5414. // A specialization of a class template member function is processed here
  5415. // since it's a redeclaration. If the parent class is dllexport, the
  5416. // specialization inherits that attribute. This doesn't happen automatically
  5417. // since the parent class isn't instantiated until later.
  5418. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5419. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5420. !NewImportAttr && !NewExportAttr) {
  5421. if (const DLLExportAttr *ParentExportAttr =
  5422. MD->getParent()->getAttr<DLLExportAttr>()) {
  5423. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5424. NewAttr->setInherited(true);
  5425. NewDecl->addAttr(NewAttr);
  5426. }
  5427. }
  5428. }
  5429. }
  5430. /// Given that we are within the definition of the given function,
  5431. /// will that definition behave like C99's 'inline', where the
  5432. /// definition is discarded except for optimization purposes?
  5433. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5434. // Try to avoid calling GetGVALinkageForFunction.
  5435. // All cases of this require the 'inline' keyword.
  5436. if (!FD->isInlined()) return false;
  5437. // This is only possible in C++ with the gnu_inline attribute.
  5438. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5439. return false;
  5440. // Okay, go ahead and call the relatively-more-expensive function.
  5441. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5442. }
  5443. /// Determine whether a variable is extern "C" prior to attaching
  5444. /// an initializer. We can't just call isExternC() here, because that
  5445. /// will also compute and cache whether the declaration is externally
  5446. /// visible, which might change when we attach the initializer.
  5447. ///
  5448. /// This can only be used if the declaration is known to not be a
  5449. /// redeclaration of an internal linkage declaration.
  5450. ///
  5451. /// For instance:
  5452. ///
  5453. /// auto x = []{};
  5454. ///
  5455. /// Attaching the initializer here makes this declaration not externally
  5456. /// visible, because its type has internal linkage.
  5457. ///
  5458. /// FIXME: This is a hack.
  5459. template<typename T>
  5460. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5461. if (S.getLangOpts().CPlusPlus) {
  5462. // In C++, the overloadable attribute negates the effects of extern "C".
  5463. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5464. return false;
  5465. // So do CUDA's host/device attributes.
  5466. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5467. D->template hasAttr<CUDAHostAttr>()))
  5468. return false;
  5469. }
  5470. return D->isExternC();
  5471. }
  5472. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5473. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5474. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
  5475. isa<OMPDeclareMapperDecl>(DC))
  5476. return VD->hasExternalStorage();
  5477. if (DC->isFileContext())
  5478. return true;
  5479. if (DC->isRecord())
  5480. return false;
  5481. llvm_unreachable("Unexpected context");
  5482. }
  5483. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5484. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5485. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5486. isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
  5487. return true;
  5488. if (DC->isRecord())
  5489. return false;
  5490. llvm_unreachable("Unexpected context");
  5491. }
  5492. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5493. ParsedAttr::Kind Kind) {
  5494. // Check decl attributes on the DeclSpec.
  5495. if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
  5496. return true;
  5497. // Walk the declarator structure, checking decl attributes that were in a type
  5498. // position to the decl itself.
  5499. for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
  5500. if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
  5501. return true;
  5502. }
  5503. // Finally, check attributes on the decl itself.
  5504. return PD.getAttributes().hasAttribute(Kind);
  5505. }
  5506. /// Adjust the \c DeclContext for a function or variable that might be a
  5507. /// function-local external declaration.
  5508. bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
  5509. if (!DC->isFunctionOrMethod())
  5510. return false;
  5511. // If this is a local extern function or variable declared within a function
  5512. // template, don't add it into the enclosing namespace scope until it is
  5513. // instantiated; it might have a dependent type right now.
  5514. if (DC->isDependentContext())
  5515. return true;
  5516. // C++11 [basic.link]p7:
  5517. // When a block scope declaration of an entity with linkage is not found to
  5518. // refer to some other declaration, then that entity is a member of the
  5519. // innermost enclosing namespace.
  5520. //
  5521. // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
  5522. // semantically-enclosing namespace, not a lexically-enclosing one.
  5523. while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
  5524. DC = DC->getParent();
  5525. return true;
  5526. }
  5527. /// Returns true if given declaration has external C language linkage.
  5528. static bool isDeclExternC(const Decl *D) {
  5529. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  5530. return FD->isExternC();
  5531. if (const auto *VD = dyn_cast<VarDecl>(D))
  5532. return VD->isExternC();
  5533. llvm_unreachable("Unknown type of decl!");
  5534. }
  5535. NamedDecl *Sema::ActOnVariableDeclarator(
  5536. Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
  5537. LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
  5538. bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
  5539. QualType R = TInfo->getType();
  5540. DeclarationName Name = GetNameForDeclarator(D).getName();
  5541. IdentifierInfo *II = Name.getAsIdentifierInfo();
  5542. if (D.isDecompositionDeclarator()) {
  5543. // Take the name of the first declarator as our name for diagnostic
  5544. // purposes.
  5545. auto &Decomp = D.getDecompositionDeclarator();
  5546. if (!Decomp.bindings().empty()) {
  5547. II = Decomp.bindings()[0].Name;
  5548. Name = II;
  5549. }
  5550. } else if (!II) {
  5551. Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
  5552. return nullptr;
  5553. }
  5554. if (getLangOpts().OpenCL) {
  5555. // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
  5556. // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
  5557. // argument.
  5558. if (R->isImageType() || R->isPipeType()) {
  5559. Diag(D.getIdentifierLoc(),
  5560. diag::err_opencl_type_can_only_be_used_as_function_parameter)
  5561. << R;
  5562. D.setInvalidType();
  5563. return nullptr;
  5564. }
  5565. // OpenCL v1.2 s6.9.r:
  5566. // The event type cannot be used to declare a program scope variable.
  5567. // OpenCL v2.0 s6.9.q:
  5568. // The clk_event_t and reserve_id_t types cannot be declared in program scope.
  5569. if (NULL == S->getParent()) {
  5570. if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
  5571. Diag(D.getIdentifierLoc(),
  5572. diag::err_invalid_type_for_program_scope_var) << R;
  5573. D.setInvalidType();
  5574. return nullptr;
  5575. }
  5576. }
  5577. // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
  5578. QualType NR = R;
  5579. while (NR->isPointerType()) {
  5580. if (NR->isFunctionPointerType()) {
  5581. Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
  5582. D.setInvalidType();
  5583. break;
  5584. }
  5585. NR = NR->getPointeeType();
  5586. }
  5587. if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  5588. // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
  5589. // half array type (unless the cl_khr_fp16 extension is enabled).
  5590. if (Context.getBaseElementType(R)->isHalfType()) {
  5591. Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
  5592. D.setInvalidType();
  5593. }
  5594. }
  5595. if (R->isSamplerT()) {
  5596. // OpenCL v1.2 s6.9.b p4:
  5597. // The sampler type cannot be used with the __local and __global address
  5598. // space qualifiers.
  5599. if (R.getAddressSpace() == LangAS::opencl_local ||
  5600. R.getAddressSpace() == LangAS::opencl_global) {
  5601. Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
  5602. }
  5603. // OpenCL v1.2 s6.12.14.1:
  5604. // A global sampler must be declared with either the constant address
  5605. // space qualifier or with the const qualifier.
  5606. if (DC->isTranslationUnit() &&
  5607. !(R.getAddressSpace() == LangAS::opencl_constant ||
  5608. R.isConstQualified())) {
  5609. Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
  5610. D.setInvalidType();
  5611. }
  5612. }
  5613. // OpenCL v1.2 s6.9.r:
  5614. // The event type cannot be used with the __local, __constant and __global
  5615. // address space qualifiers.
  5616. if (R->isEventT()) {
  5617. if (R.getAddressSpace() != LangAS::opencl_private) {
  5618. Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
  5619. D.setInvalidType();
  5620. }
  5621. }
  5622. // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
  5623. // supported. OpenCL C does not support thread_local either, and
  5624. // also reject all other thread storage class specifiers.
  5625. DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
  5626. if (TSC != TSCS_unspecified) {
  5627. bool IsCXX = getLangOpts().OpenCLCPlusPlus;
  5628. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5629. diag::err_opencl_unknown_type_specifier)
  5630. << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
  5631. << DeclSpec::getSpecifierName(TSC) << 1;
  5632. D.setInvalidType();
  5633. return nullptr;
  5634. }
  5635. }
  5636. DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
  5637. StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
  5638. // dllimport globals without explicit storage class are treated as extern. We
  5639. // have to change the storage class this early to get the right DeclContext.
  5640. if (SC == SC_None && !DC->isRecord() &&
  5641. hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
  5642. !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
  5643. SC = SC_Extern;
  5644. DeclContext *OriginalDC = DC;
  5645. bool IsLocalExternDecl = SC == SC_Extern &&
  5646. adjustContextForLocalExternDecl(DC);
  5647. if (SCSpec == DeclSpec::SCS_mutable) {
  5648. // mutable can only appear on non-static class members, so it's always
  5649. // an error here
  5650. Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
  5651. D.setInvalidType();
  5652. SC = SC_None;
  5653. }
  5654. if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
  5655. !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
  5656. D.getDeclSpec().getStorageClassSpecLoc())) {
  5657. // In C++11, the 'register' storage class specifier is deprecated.
  5658. // Suppress the warning in system macros, it's used in macros in some
  5659. // popular C system headers, such as in glibc's htonl() macro.
  5660. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5661. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  5662. : diag::warn_deprecated_register)
  5663. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5664. }
  5665. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5666. if (!DC->isRecord() && S->getFnParent() == nullptr) {
  5667. // C99 6.9p2: The storage-class specifiers auto and register shall not
  5668. // appear in the declaration specifiers in an external declaration.
  5669. // Global Register+Asm is a GNU extension we support.
  5670. if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
  5671. Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
  5672. D.setInvalidType();
  5673. }
  5674. }
  5675. bool IsMemberSpecialization = false;
  5676. bool IsVariableTemplateSpecialization = false;
  5677. bool IsPartialSpecialization = false;
  5678. bool IsVariableTemplate = false;
  5679. VarDecl *NewVD = nullptr;
  5680. VarTemplateDecl *NewTemplate = nullptr;
  5681. TemplateParameterList *TemplateParams = nullptr;
  5682. if (!getLangOpts().CPlusPlus) {
  5683. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
  5684. II, R, TInfo, SC);
  5685. if (R->getContainedDeducedType())
  5686. ParsingInitForAutoVars.insert(NewVD);
  5687. if (D.isInvalidType())
  5688. NewVD->setInvalidDecl();
  5689. } else {
  5690. bool Invalid = false;
  5691. if (DC->isRecord() && !CurContext->isRecord()) {
  5692. // This is an out-of-line definition of a static data member.
  5693. switch (SC) {
  5694. case SC_None:
  5695. break;
  5696. case SC_Static:
  5697. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5698. diag::err_static_out_of_line)
  5699. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5700. break;
  5701. case SC_Auto:
  5702. case SC_Register:
  5703. case SC_Extern:
  5704. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5705. // to names of variables declared in a block or to function parameters.
  5706. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5707. // of class members
  5708. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5709. diag::err_storage_class_for_static_member)
  5710. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5711. break;
  5712. case SC_PrivateExtern:
  5713. llvm_unreachable("C storage class in c++!");
  5714. }
  5715. }
  5716. if (SC == SC_Static && CurContext->isRecord()) {
  5717. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5718. if (RD->isLocalClass())
  5719. Diag(D.getIdentifierLoc(),
  5720. diag::err_static_data_member_not_allowed_in_local_class)
  5721. << Name << RD->getDeclName();
  5722. // C++98 [class.union]p1: If a union contains a static data member,
  5723. // the program is ill-formed. C++11 drops this restriction.
  5724. if (RD->isUnion())
  5725. Diag(D.getIdentifierLoc(),
  5726. getLangOpts().CPlusPlus11
  5727. ? diag::warn_cxx98_compat_static_data_member_in_union
  5728. : diag::ext_static_data_member_in_union) << Name;
  5729. // We conservatively disallow static data members in anonymous structs.
  5730. else if (!RD->getDeclName())
  5731. Diag(D.getIdentifierLoc(),
  5732. diag::err_static_data_member_not_allowed_in_anon_struct)
  5733. << Name << RD->isUnion();
  5734. }
  5735. }
  5736. // Match up the template parameter lists with the scope specifier, then
  5737. // determine whether we have a template or a template specialization.
  5738. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5739. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  5740. D.getCXXScopeSpec(),
  5741. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5742. ? D.getName().TemplateId
  5743. : nullptr,
  5744. TemplateParamLists,
  5745. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5746. if (TemplateParams) {
  5747. if (!TemplateParams->size() &&
  5748. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5749. // There is an extraneous 'template<>' for this variable. Complain
  5750. // about it, but allow the declaration of the variable.
  5751. Diag(TemplateParams->getTemplateLoc(),
  5752. diag::err_template_variable_noparams)
  5753. << II
  5754. << SourceRange(TemplateParams->getTemplateLoc(),
  5755. TemplateParams->getRAngleLoc());
  5756. TemplateParams = nullptr;
  5757. } else {
  5758. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5759. // This is an explicit specialization or a partial specialization.
  5760. // FIXME: Check that we can declare a specialization here.
  5761. IsVariableTemplateSpecialization = true;
  5762. IsPartialSpecialization = TemplateParams->size() > 0;
  5763. } else { // if (TemplateParams->size() > 0)
  5764. // This is a template declaration.
  5765. IsVariableTemplate = true;
  5766. // Check that we can declare a template here.
  5767. if (CheckTemplateDeclScope(S, TemplateParams))
  5768. return nullptr;
  5769. // Only C++1y supports variable templates (N3651).
  5770. Diag(D.getIdentifierLoc(),
  5771. getLangOpts().CPlusPlus14
  5772. ? diag::warn_cxx11_compat_variable_template
  5773. : diag::ext_variable_template);
  5774. }
  5775. }
  5776. } else {
  5777. assert((Invalid ||
  5778. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5779. "should have a 'template<>' for this decl");
  5780. }
  5781. if (IsVariableTemplateSpecialization) {
  5782. SourceLocation TemplateKWLoc =
  5783. TemplateParamLists.size() > 0
  5784. ? TemplateParamLists[0]->getTemplateLoc()
  5785. : SourceLocation();
  5786. DeclResult Res = ActOnVarTemplateSpecialization(
  5787. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5788. IsPartialSpecialization);
  5789. if (Res.isInvalid())
  5790. return nullptr;
  5791. NewVD = cast<VarDecl>(Res.get());
  5792. AddToScope = false;
  5793. } else if (D.isDecompositionDeclarator()) {
  5794. NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
  5795. D.getIdentifierLoc(), R, TInfo, SC,
  5796. Bindings);
  5797. } else
  5798. NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
  5799. D.getIdentifierLoc(), II, R, TInfo, SC);
  5800. // If this is supposed to be a variable template, create it as such.
  5801. if (IsVariableTemplate) {
  5802. NewTemplate =
  5803. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5804. TemplateParams, NewVD);
  5805. NewVD->setDescribedVarTemplate(NewTemplate);
  5806. }
  5807. // If this decl has an auto type in need of deduction, make a note of the
  5808. // Decl so we can diagnose uses of it in its own initializer.
  5809. if (R->getContainedDeducedType())
  5810. ParsingInitForAutoVars.insert(NewVD);
  5811. if (D.isInvalidType() || Invalid) {
  5812. NewVD->setInvalidDecl();
  5813. if (NewTemplate)
  5814. NewTemplate->setInvalidDecl();
  5815. }
  5816. SetNestedNameSpecifier(*this, NewVD, D);
  5817. // If we have any template parameter lists that don't directly belong to
  5818. // the variable (matching the scope specifier), store them.
  5819. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5820. if (TemplateParamLists.size() > VDTemplateParamLists)
  5821. NewVD->setTemplateParameterListsInfo(
  5822. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5823. if (D.getDeclSpec().isConstexprSpecified()) {
  5824. NewVD->setConstexpr(true);
  5825. // C++1z [dcl.spec.constexpr]p1:
  5826. // A static data member declared with the constexpr specifier is
  5827. // implicitly an inline variable.
  5828. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5829. NewVD->setImplicitlyInline();
  5830. }
  5831. }
  5832. if (D.getDeclSpec().isInlineSpecified()) {
  5833. if (!getLangOpts().CPlusPlus) {
  5834. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5835. << 0;
  5836. } else if (CurContext->isFunctionOrMethod()) {
  5837. // 'inline' is not allowed on block scope variable declaration.
  5838. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5839. diag::err_inline_declaration_block_scope) << Name
  5840. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5841. } else {
  5842. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5843. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5844. : diag::ext_inline_variable);
  5845. NewVD->setInlineSpecified();
  5846. }
  5847. }
  5848. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5849. // lexical context will be different from the semantic context.
  5850. NewVD->setLexicalDeclContext(CurContext);
  5851. if (NewTemplate)
  5852. NewTemplate->setLexicalDeclContext(CurContext);
  5853. if (IsLocalExternDecl) {
  5854. if (D.isDecompositionDeclarator())
  5855. for (auto *B : Bindings)
  5856. B->setLocalExternDecl();
  5857. else
  5858. NewVD->setLocalExternDecl();
  5859. }
  5860. bool EmitTLSUnsupportedError = false;
  5861. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5862. // C++11 [dcl.stc]p4:
  5863. // When thread_local is applied to a variable of block scope the
  5864. // storage-class-specifier static is implied if it does not appear
  5865. // explicitly.
  5866. // Core issue: 'static' is not implied if the variable is declared
  5867. // 'extern'.
  5868. if (NewVD->hasLocalStorage() &&
  5869. (SCSpec != DeclSpec::SCS_unspecified ||
  5870. TSCS != DeclSpec::TSCS_thread_local ||
  5871. !DC->isFunctionOrMethod()))
  5872. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5873. diag::err_thread_non_global)
  5874. << DeclSpec::getSpecifierName(TSCS);
  5875. else if (!Context.getTargetInfo().isTLSSupported()) {
  5876. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5877. // Postpone error emission until we've collected attributes required to
  5878. // figure out whether it's a host or device variable and whether the
  5879. // error should be ignored.
  5880. EmitTLSUnsupportedError = true;
  5881. // We still need to mark the variable as TLS so it shows up in AST with
  5882. // proper storage class for other tools to use even if we're not going
  5883. // to emit any code for it.
  5884. NewVD->setTSCSpec(TSCS);
  5885. } else
  5886. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5887. diag::err_thread_unsupported);
  5888. } else
  5889. NewVD->setTSCSpec(TSCS);
  5890. }
  5891. // C99 6.7.4p3
  5892. // An inline definition of a function with external linkage shall
  5893. // not contain a definition of a modifiable object with static or
  5894. // thread storage duration...
  5895. // We only apply this when the function is required to be defined
  5896. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5897. // that a local variable with thread storage duration still has to
  5898. // be marked 'static'. Also note that it's possible to get these
  5899. // semantics in C++ using __attribute__((gnu_inline)).
  5900. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5901. !NewVD->getType().isConstQualified()) {
  5902. FunctionDecl *CurFD = getCurFunctionDecl();
  5903. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5904. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5905. diag::warn_static_local_in_extern_inline);
  5906. MaybeSuggestAddingStaticToDecl(CurFD);
  5907. }
  5908. }
  5909. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5910. if (IsVariableTemplateSpecialization)
  5911. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5912. << (IsPartialSpecialization ? 1 : 0)
  5913. << FixItHint::CreateRemoval(
  5914. D.getDeclSpec().getModulePrivateSpecLoc());
  5915. else if (IsMemberSpecialization)
  5916. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5917. << 2
  5918. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5919. else if (NewVD->hasLocalStorage())
  5920. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5921. << 0 << NewVD->getDeclName()
  5922. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5923. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5924. else {
  5925. NewVD->setModulePrivate();
  5926. if (NewTemplate)
  5927. NewTemplate->setModulePrivate();
  5928. for (auto *B : Bindings)
  5929. B->setModulePrivate();
  5930. }
  5931. }
  5932. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5933. ProcessDeclAttributes(S, NewVD, D);
  5934. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5935. if (EmitTLSUnsupportedError &&
  5936. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5937. (getLangOpts().OpenMPIsDevice &&
  5938. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5939. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5940. diag::err_thread_unsupported);
  5941. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5942. // storage [duration]."
  5943. if (SC == SC_None && S->getFnParent() != nullptr &&
  5944. (NewVD->hasAttr<CUDASharedAttr>() ||
  5945. NewVD->hasAttr<CUDAConstantAttr>())) {
  5946. NewVD->setStorageClass(SC_Static);
  5947. }
  5948. }
  5949. // Ensure that dllimport globals without explicit storage class are treated as
  5950. // extern. The storage class is set above using parsed attributes. Now we can
  5951. // check the VarDecl itself.
  5952. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5953. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5954. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5955. // In auto-retain/release, infer strong retension for variables of
  5956. // retainable type.
  5957. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5958. NewVD->setInvalidDecl();
  5959. // Handle GNU asm-label extension (encoded as an attribute).
  5960. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5961. // The parser guarantees this is a string.
  5962. StringLiteral *SE = cast<StringLiteral>(E);
  5963. StringRef Label = SE->getString();
  5964. if (S->getFnParent() != nullptr) {
  5965. switch (SC) {
  5966. case SC_None:
  5967. case SC_Auto:
  5968. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5969. break;
  5970. case SC_Register:
  5971. // Local Named register
  5972. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5973. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5974. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5975. break;
  5976. case SC_Static:
  5977. case SC_Extern:
  5978. case SC_PrivateExtern:
  5979. break;
  5980. }
  5981. } else if (SC == SC_Register) {
  5982. // Global Named register
  5983. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5984. const auto &TI = Context.getTargetInfo();
  5985. bool HasSizeMismatch;
  5986. if (!TI.isValidGCCRegisterName(Label))
  5987. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5988. else if (!TI.validateGlobalRegisterVariable(Label,
  5989. Context.getTypeSize(R),
  5990. HasSizeMismatch))
  5991. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5992. else if (HasSizeMismatch)
  5993. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5994. }
  5995. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5996. Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
  5997. NewVD->setInvalidDecl(true);
  5998. }
  5999. }
  6000. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6001. Context, Label, 0));
  6002. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6003. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6004. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6005. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6006. if (isDeclExternC(NewVD)) {
  6007. NewVD->addAttr(I->second);
  6008. ExtnameUndeclaredIdentifiers.erase(I);
  6009. } else
  6010. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6011. << /*Variable*/1 << NewVD;
  6012. }
  6013. }
  6014. // Find the shadowed declaration before filtering for scope.
  6015. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6016. ? getShadowedDeclaration(NewVD, Previous)
  6017. : nullptr;
  6018. // Don't consider existing declarations that are in a different
  6019. // scope and are out-of-semantic-context declarations (if the new
  6020. // declaration has linkage).
  6021. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6022. D.getCXXScopeSpec().isNotEmpty() ||
  6023. IsMemberSpecialization ||
  6024. IsVariableTemplateSpecialization);
  6025. // Check whether the previous declaration is in the same block scope. This
  6026. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6027. if (getLangOpts().CPlusPlus &&
  6028. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6029. NewVD->setPreviousDeclInSameBlockScope(
  6030. Previous.isSingleResult() && !Previous.isShadowed() &&
  6031. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6032. if (!getLangOpts().CPlusPlus) {
  6033. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6034. } else {
  6035. // If this is an explicit specialization of a static data member, check it.
  6036. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6037. CheckMemberSpecialization(NewVD, Previous))
  6038. NewVD->setInvalidDecl();
  6039. // Merge the decl with the existing one if appropriate.
  6040. if (!Previous.empty()) {
  6041. if (Previous.isSingleResult() &&
  6042. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6043. D.getCXXScopeSpec().isSet()) {
  6044. // The user tried to define a non-static data member
  6045. // out-of-line (C++ [dcl.meaning]p1).
  6046. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6047. << D.getCXXScopeSpec().getRange();
  6048. Previous.clear();
  6049. NewVD->setInvalidDecl();
  6050. }
  6051. } else if (D.getCXXScopeSpec().isSet()) {
  6052. // No previous declaration in the qualifying scope.
  6053. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6054. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6055. << D.getCXXScopeSpec().getRange();
  6056. NewVD->setInvalidDecl();
  6057. }
  6058. if (!IsVariableTemplateSpecialization)
  6059. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6060. if (NewTemplate) {
  6061. VarTemplateDecl *PrevVarTemplate =
  6062. NewVD->getPreviousDecl()
  6063. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6064. : nullptr;
  6065. // Check the template parameter list of this declaration, possibly
  6066. // merging in the template parameter list from the previous variable
  6067. // template declaration.
  6068. if (CheckTemplateParameterList(
  6069. TemplateParams,
  6070. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6071. : nullptr,
  6072. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6073. DC->isDependentContext())
  6074. ? TPC_ClassTemplateMember
  6075. : TPC_VarTemplate))
  6076. NewVD->setInvalidDecl();
  6077. // If we are providing an explicit specialization of a static variable
  6078. // template, make a note of that.
  6079. if (PrevVarTemplate &&
  6080. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6081. PrevVarTemplate->setMemberSpecialization();
  6082. }
  6083. }
  6084. // Diagnose shadowed variables iff this isn't a redeclaration.
  6085. if (ShadowedDecl && !D.isRedeclaration())
  6086. CheckShadow(NewVD, ShadowedDecl, Previous);
  6087. ProcessPragmaWeak(S, NewVD);
  6088. // If this is the first declaration of an extern C variable, update
  6089. // the map of such variables.
  6090. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6091. isIncompleteDeclExternC(*this, NewVD))
  6092. RegisterLocallyScopedExternCDecl(NewVD, S);
  6093. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6094. Decl *ManglingContextDecl;
  6095. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6096. NewVD->getDeclContext(), ManglingContextDecl)) {
  6097. Context.setManglingNumber(
  6098. NewVD, MCtx->getManglingNumber(
  6099. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6100. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6101. }
  6102. }
  6103. // Special handling of variable named 'main'.
  6104. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6105. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6106. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6107. // C++ [basic.start.main]p3
  6108. // A program that declares a variable main at global scope is ill-formed.
  6109. if (getLangOpts().CPlusPlus)
  6110. Diag(D.getBeginLoc(), diag::err_main_global_variable);
  6111. // In C, and external-linkage variable named main results in undefined
  6112. // behavior.
  6113. else if (NewVD->hasExternalFormalLinkage())
  6114. Diag(D.getBeginLoc(), diag::warn_main_redefined);
  6115. }
  6116. if (D.isRedeclaration() && !Previous.empty()) {
  6117. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6118. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6119. D.isFunctionDefinition());
  6120. }
  6121. if (NewTemplate) {
  6122. if (NewVD->isInvalidDecl())
  6123. NewTemplate->setInvalidDecl();
  6124. ActOnDocumentableDecl(NewTemplate);
  6125. return NewTemplate;
  6126. }
  6127. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6128. CompleteMemberSpecialization(NewVD, Previous);
  6129. return NewVD;
  6130. }
  6131. /// Enum describing the %select options in diag::warn_decl_shadow.
  6132. enum ShadowedDeclKind {
  6133. SDK_Local,
  6134. SDK_Global,
  6135. SDK_StaticMember,
  6136. SDK_Field,
  6137. SDK_Typedef,
  6138. SDK_Using
  6139. };
  6140. /// Determine what kind of declaration we're shadowing.
  6141. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6142. const DeclContext *OldDC) {
  6143. if (isa<TypeAliasDecl>(ShadowedDecl))
  6144. return SDK_Using;
  6145. else if (isa<TypedefDecl>(ShadowedDecl))
  6146. return SDK_Typedef;
  6147. else if (isa<RecordDecl>(OldDC))
  6148. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6149. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6150. }
  6151. /// Return the location of the capture if the given lambda captures the given
  6152. /// variable \p VD, or an invalid source location otherwise.
  6153. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6154. const VarDecl *VD) {
  6155. for (const Capture &Capture : LSI->Captures) {
  6156. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6157. return Capture.getLocation();
  6158. }
  6159. return SourceLocation();
  6160. }
  6161. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6162. const LookupResult &R) {
  6163. // Only diagnose if we're shadowing an unambiguous field or variable.
  6164. if (R.getResultKind() != LookupResult::Found)
  6165. return false;
  6166. // Return false if warning is ignored.
  6167. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6168. }
  6169. /// Return the declaration shadowed by the given variable \p D, or null
  6170. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6171. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6172. const LookupResult &R) {
  6173. if (!shouldWarnIfShadowedDecl(Diags, R))
  6174. return nullptr;
  6175. // Don't diagnose declarations at file scope.
  6176. if (D->hasGlobalStorage())
  6177. return nullptr;
  6178. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6179. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6180. ? ShadowedDecl
  6181. : nullptr;
  6182. }
  6183. /// Return the declaration shadowed by the given typedef \p D, or null
  6184. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6185. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6186. const LookupResult &R) {
  6187. // Don't warn if typedef declaration is part of a class
  6188. if (D->getDeclContext()->isRecord())
  6189. return nullptr;
  6190. if (!shouldWarnIfShadowedDecl(Diags, R))
  6191. return nullptr;
  6192. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6193. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6194. }
  6195. /// Diagnose variable or built-in function shadowing. Implements
  6196. /// -Wshadow.
  6197. ///
  6198. /// This method is called whenever a VarDecl is added to a "useful"
  6199. /// scope.
  6200. ///
  6201. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6202. /// \param R the lookup of the name
  6203. ///
  6204. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6205. const LookupResult &R) {
  6206. DeclContext *NewDC = D->getDeclContext();
  6207. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6208. // Fields are not shadowed by variables in C++ static methods.
  6209. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6210. if (MD->isStatic())
  6211. return;
  6212. // Fields shadowed by constructor parameters are a special case. Usually
  6213. // the constructor initializes the field with the parameter.
  6214. if (isa<CXXConstructorDecl>(NewDC))
  6215. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6216. // Remember that this was shadowed so we can either warn about its
  6217. // modification or its existence depending on warning settings.
  6218. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6219. return;
  6220. }
  6221. }
  6222. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6223. if (shadowedVar->isExternC()) {
  6224. // For shadowing external vars, make sure that we point to the global
  6225. // declaration, not a locally scoped extern declaration.
  6226. for (auto I : shadowedVar->redecls())
  6227. if (I->isFileVarDecl()) {
  6228. ShadowedDecl = I;
  6229. break;
  6230. }
  6231. }
  6232. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6233. unsigned WarningDiag = diag::warn_decl_shadow;
  6234. SourceLocation CaptureLoc;
  6235. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6236. isa<CXXMethodDecl>(NewDC)) {
  6237. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6238. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6239. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6240. // Try to avoid warnings for lambdas with an explicit capture list.
  6241. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6242. // Warn only when the lambda captures the shadowed decl explicitly.
  6243. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6244. if (CaptureLoc.isInvalid())
  6245. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6246. } else {
  6247. // Remember that this was shadowed so we can avoid the warning if the
  6248. // shadowed decl isn't captured and the warning settings allow it.
  6249. cast<LambdaScopeInfo>(getCurFunction())
  6250. ->ShadowingDecls.push_back(
  6251. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6252. return;
  6253. }
  6254. }
  6255. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6256. // A variable can't shadow a local variable in an enclosing scope, if
  6257. // they are separated by a non-capturing declaration context.
  6258. for (DeclContext *ParentDC = NewDC;
  6259. ParentDC && !ParentDC->Equals(OldDC);
  6260. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6261. // Only block literals, captured statements, and lambda expressions
  6262. // can capture; other scopes don't.
  6263. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6264. !isLambdaCallOperator(ParentDC)) {
  6265. return;
  6266. }
  6267. }
  6268. }
  6269. }
  6270. }
  6271. // Only warn about certain kinds of shadowing for class members.
  6272. if (NewDC && NewDC->isRecord()) {
  6273. // In particular, don't warn about shadowing non-class members.
  6274. if (!OldDC->isRecord())
  6275. return;
  6276. // TODO: should we warn about static data members shadowing
  6277. // static data members from base classes?
  6278. // TODO: don't diagnose for inaccessible shadowed members.
  6279. // This is hard to do perfectly because we might friend the
  6280. // shadowing context, but that's just a false negative.
  6281. }
  6282. DeclarationName Name = R.getLookupName();
  6283. // Emit warning and note.
  6284. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6285. return;
  6286. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6287. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6288. if (!CaptureLoc.isInvalid())
  6289. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6290. << Name << /*explicitly*/ 1;
  6291. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6292. }
  6293. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6294. /// when these variables are captured by the lambda.
  6295. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6296. for (const auto &Shadow : LSI->ShadowingDecls) {
  6297. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6298. // Try to avoid the warning when the shadowed decl isn't captured.
  6299. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6300. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6301. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6302. ? diag::warn_decl_shadow_uncaptured_local
  6303. : diag::warn_decl_shadow)
  6304. << Shadow.VD->getDeclName()
  6305. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6306. if (!CaptureLoc.isInvalid())
  6307. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6308. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6309. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6310. }
  6311. }
  6312. /// Check -Wshadow without the advantage of a previous lookup.
  6313. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6314. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6315. return;
  6316. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6317. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6318. LookupName(R, S);
  6319. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6320. CheckShadow(D, ShadowedDecl, R);
  6321. }
  6322. /// Check if 'E', which is an expression that is about to be modified, refers
  6323. /// to a constructor parameter that shadows a field.
  6324. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6325. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6326. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6327. return;
  6328. E = E->IgnoreParenImpCasts();
  6329. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6330. if (!DRE)
  6331. return;
  6332. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6333. auto I = ShadowingDecls.find(D);
  6334. if (I == ShadowingDecls.end())
  6335. return;
  6336. const NamedDecl *ShadowedDecl = I->second;
  6337. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6338. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6339. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6340. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6341. // Avoid issuing multiple warnings about the same decl.
  6342. ShadowingDecls.erase(I);
  6343. }
  6344. /// Check for conflict between this global or extern "C" declaration and
  6345. /// previous global or extern "C" declarations. This is only used in C++.
  6346. template<typename T>
  6347. static bool checkGlobalOrExternCConflict(
  6348. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6349. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6350. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6351. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6352. // The common case: this global doesn't conflict with any extern "C"
  6353. // declaration.
  6354. return false;
  6355. }
  6356. if (Prev) {
  6357. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6358. // Both the old and new declarations have C language linkage. This is a
  6359. // redeclaration.
  6360. Previous.clear();
  6361. Previous.addDecl(Prev);
  6362. return true;
  6363. }
  6364. // This is a global, non-extern "C" declaration, and there is a previous
  6365. // non-global extern "C" declaration. Diagnose if this is a variable
  6366. // declaration.
  6367. if (!isa<VarDecl>(ND))
  6368. return false;
  6369. } else {
  6370. // The declaration is extern "C". Check for any declaration in the
  6371. // translation unit which might conflict.
  6372. if (IsGlobal) {
  6373. // We have already performed the lookup into the translation unit.
  6374. IsGlobal = false;
  6375. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6376. I != E; ++I) {
  6377. if (isa<VarDecl>(*I)) {
  6378. Prev = *I;
  6379. break;
  6380. }
  6381. }
  6382. } else {
  6383. DeclContext::lookup_result R =
  6384. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6385. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6386. I != E; ++I) {
  6387. if (isa<VarDecl>(*I)) {
  6388. Prev = *I;
  6389. break;
  6390. }
  6391. // FIXME: If we have any other entity with this name in global scope,
  6392. // the declaration is ill-formed, but that is a defect: it breaks the
  6393. // 'stat' hack, for instance. Only variables can have mangled name
  6394. // clashes with extern "C" declarations, so only they deserve a
  6395. // diagnostic.
  6396. }
  6397. }
  6398. if (!Prev)
  6399. return false;
  6400. }
  6401. // Use the first declaration's location to ensure we point at something which
  6402. // is lexically inside an extern "C" linkage-spec.
  6403. assert(Prev && "should have found a previous declaration to diagnose");
  6404. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6405. Prev = FD->getFirstDecl();
  6406. else
  6407. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6408. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6409. << IsGlobal << ND;
  6410. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6411. << IsGlobal;
  6412. return false;
  6413. }
  6414. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6415. /// if we have found that this is a redeclaration of some prior entity.
  6416. ///
  6417. /// Per C++ [dcl.link]p6:
  6418. /// Two declarations [for a function or variable] with C language linkage
  6419. /// with the same name that appear in different scopes refer to the same
  6420. /// [entity]. An entity with C language linkage shall not be declared with
  6421. /// the same name as an entity in global scope.
  6422. template<typename T>
  6423. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6424. LookupResult &Previous) {
  6425. if (!S.getLangOpts().CPlusPlus) {
  6426. // In C, when declaring a global variable, look for a corresponding 'extern'
  6427. // variable declared in function scope. We don't need this in C++, because
  6428. // we find local extern decls in the surrounding file-scope DeclContext.
  6429. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6430. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6431. Previous.clear();
  6432. Previous.addDecl(Prev);
  6433. return true;
  6434. }
  6435. }
  6436. return false;
  6437. }
  6438. // A declaration in the translation unit can conflict with an extern "C"
  6439. // declaration.
  6440. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6441. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6442. // An extern "C" declaration can conflict with a declaration in the
  6443. // translation unit or can be a redeclaration of an extern "C" declaration
  6444. // in another scope.
  6445. if (isIncompleteDeclExternC(S,ND))
  6446. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6447. // Neither global nor extern "C": nothing to do.
  6448. return false;
  6449. }
  6450. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6451. // If the decl is already known invalid, don't check it.
  6452. if (NewVD->isInvalidDecl())
  6453. return;
  6454. QualType T = NewVD->getType();
  6455. // Defer checking an 'auto' type until its initializer is attached.
  6456. if (T->isUndeducedType())
  6457. return;
  6458. if (NewVD->hasAttrs())
  6459. CheckAlignasUnderalignment(NewVD);
  6460. if (T->isObjCObjectType()) {
  6461. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6462. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6463. T = Context.getObjCObjectPointerType(T);
  6464. NewVD->setType(T);
  6465. }
  6466. // Emit an error if an address space was applied to decl with local storage.
  6467. // This includes arrays of objects with address space qualifiers, but not
  6468. // automatic variables that point to other address spaces.
  6469. // ISO/IEC TR 18037 S5.1.2
  6470. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6471. T.getAddressSpace() != LangAS::Default) {
  6472. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6473. NewVD->setInvalidDecl();
  6474. return;
  6475. }
  6476. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6477. // scope.
  6478. if (getLangOpts().OpenCLVersion == 120 &&
  6479. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6480. NewVD->isStaticLocal()) {
  6481. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6482. NewVD->setInvalidDecl();
  6483. return;
  6484. }
  6485. if (getLangOpts().OpenCL) {
  6486. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6487. if (NewVD->hasAttr<BlocksAttr>()) {
  6488. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6489. return;
  6490. }
  6491. if (T->isBlockPointerType()) {
  6492. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6493. // can't use 'extern' storage class.
  6494. if (!T.isConstQualified()) {
  6495. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6496. << 0 /*const*/;
  6497. NewVD->setInvalidDecl();
  6498. return;
  6499. }
  6500. if (NewVD->hasExternalStorage()) {
  6501. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6502. NewVD->setInvalidDecl();
  6503. return;
  6504. }
  6505. }
  6506. // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
  6507. // __constant address space.
  6508. // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
  6509. // variables inside a function can also be declared in the global
  6510. // address space.
  6511. // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
  6512. // address space additionally.
  6513. // FIXME: Add local AS for OpenCL C++.
  6514. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6515. NewVD->hasExternalStorage()) {
  6516. if (!T->isSamplerT() &&
  6517. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6518. (T.getAddressSpace() == LangAS::opencl_global &&
  6519. (getLangOpts().OpenCLVersion == 200 ||
  6520. getLangOpts().OpenCLCPlusPlus)))) {
  6521. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6522. if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
  6523. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6524. << Scope << "global or constant";
  6525. else
  6526. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6527. << Scope << "constant";
  6528. NewVD->setInvalidDecl();
  6529. return;
  6530. }
  6531. } else {
  6532. if (T.getAddressSpace() == LangAS::opencl_global) {
  6533. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6534. << 1 /*is any function*/ << "global";
  6535. NewVD->setInvalidDecl();
  6536. return;
  6537. }
  6538. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6539. T.getAddressSpace() == LangAS::opencl_local) {
  6540. FunctionDecl *FD = getCurFunctionDecl();
  6541. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6542. // in functions.
  6543. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6544. if (T.getAddressSpace() == LangAS::opencl_constant)
  6545. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6546. << 0 /*non-kernel only*/ << "constant";
  6547. else
  6548. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6549. << 0 /*non-kernel only*/ << "local";
  6550. NewVD->setInvalidDecl();
  6551. return;
  6552. }
  6553. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6554. // in the outermost scope of a kernel function.
  6555. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6556. if (!getCurScope()->isFunctionScope()) {
  6557. if (T.getAddressSpace() == LangAS::opencl_constant)
  6558. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6559. << "constant";
  6560. else
  6561. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6562. << "local";
  6563. NewVD->setInvalidDecl();
  6564. return;
  6565. }
  6566. }
  6567. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6568. // Do not allow other address spaces on automatic variable.
  6569. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6570. NewVD->setInvalidDecl();
  6571. return;
  6572. }
  6573. }
  6574. }
  6575. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6576. && !NewVD->hasAttr<BlocksAttr>()) {
  6577. if (getLangOpts().getGC() != LangOptions::NonGC)
  6578. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6579. else {
  6580. assert(!getLangOpts().ObjCAutoRefCount);
  6581. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6582. }
  6583. }
  6584. bool isVM = T->isVariablyModifiedType();
  6585. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6586. NewVD->hasAttr<BlocksAttr>())
  6587. setFunctionHasBranchProtectedScope();
  6588. if ((isVM && NewVD->hasLinkage()) ||
  6589. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6590. bool SizeIsNegative;
  6591. llvm::APSInt Oversized;
  6592. TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
  6593. NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
  6594. QualType FixedT;
  6595. if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
  6596. FixedT = FixedTInfo->getType();
  6597. else if (FixedTInfo) {
  6598. // Type and type-as-written are canonically different. We need to fix up
  6599. // both types separately.
  6600. FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
  6601. Oversized);
  6602. }
  6603. if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
  6604. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6605. // FIXME: This won't give the correct result for
  6606. // int a[10][n];
  6607. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6608. if (NewVD->isFileVarDecl())
  6609. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6610. << SizeRange;
  6611. else if (NewVD->isStaticLocal())
  6612. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6613. << SizeRange;
  6614. else
  6615. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6616. << SizeRange;
  6617. NewVD->setInvalidDecl();
  6618. return;
  6619. }
  6620. if (!FixedTInfo) {
  6621. if (NewVD->isFileVarDecl())
  6622. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6623. else
  6624. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6625. NewVD->setInvalidDecl();
  6626. return;
  6627. }
  6628. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6629. NewVD->setType(FixedT);
  6630. NewVD->setTypeSourceInfo(FixedTInfo);
  6631. }
  6632. if (T->isVoidType()) {
  6633. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6634. // of objects and functions.
  6635. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6636. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6637. << T;
  6638. NewVD->setInvalidDecl();
  6639. return;
  6640. }
  6641. }
  6642. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6643. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6644. NewVD->setInvalidDecl();
  6645. return;
  6646. }
  6647. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6648. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6649. NewVD->setInvalidDecl();
  6650. return;
  6651. }
  6652. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6653. RequireLiteralType(NewVD->getLocation(), T,
  6654. diag::err_constexpr_var_non_literal)) {
  6655. NewVD->setInvalidDecl();
  6656. return;
  6657. }
  6658. }
  6659. /// Perform semantic checking on a newly-created variable
  6660. /// declaration.
  6661. ///
  6662. /// This routine performs all of the type-checking required for a
  6663. /// variable declaration once it has been built. It is used both to
  6664. /// check variables after they have been parsed and their declarators
  6665. /// have been translated into a declaration, and to check variables
  6666. /// that have been instantiated from a template.
  6667. ///
  6668. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6669. ///
  6670. /// Returns true if the variable declaration is a redeclaration.
  6671. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6672. CheckVariableDeclarationType(NewVD);
  6673. // If the decl is already known invalid, don't check it.
  6674. if (NewVD->isInvalidDecl())
  6675. return false;
  6676. // If we did not find anything by this name, look for a non-visible
  6677. // extern "C" declaration with the same name.
  6678. if (Previous.empty() &&
  6679. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6680. Previous.setShadowed();
  6681. if (!Previous.empty()) {
  6682. MergeVarDecl(NewVD, Previous);
  6683. return true;
  6684. }
  6685. return false;
  6686. }
  6687. namespace {
  6688. struct FindOverriddenMethod {
  6689. Sema *S;
  6690. CXXMethodDecl *Method;
  6691. /// Member lookup function that determines whether a given C++
  6692. /// method overrides a method in a base class, to be used with
  6693. /// CXXRecordDecl::lookupInBases().
  6694. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6695. RecordDecl *BaseRecord =
  6696. Specifier->getType()->getAs<RecordType>()->getDecl();
  6697. DeclarationName Name = Method->getDeclName();
  6698. // FIXME: Do we care about other names here too?
  6699. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6700. // We really want to find the base class destructor here.
  6701. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6702. CanQualType CT = S->Context.getCanonicalType(T);
  6703. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6704. }
  6705. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6706. Path.Decls = Path.Decls.slice(1)) {
  6707. NamedDecl *D = Path.Decls.front();
  6708. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6709. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6710. return true;
  6711. }
  6712. }
  6713. return false;
  6714. }
  6715. };
  6716. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6717. } // end anonymous namespace
  6718. /// Report an error regarding overriding, along with any relevant
  6719. /// overridden methods.
  6720. ///
  6721. /// \param DiagID the primary error to report.
  6722. /// \param MD the overriding method.
  6723. /// \param OEK which overrides to include as notes.
  6724. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6725. OverrideErrorKind OEK = OEK_All) {
  6726. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6727. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6728. // This check (& the OEK parameter) could be replaced by a predicate, but
  6729. // without lambdas that would be overkill. This is still nicer than writing
  6730. // out the diag loop 3 times.
  6731. if ((OEK == OEK_All) ||
  6732. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6733. (OEK == OEK_Deleted && O->isDeleted()))
  6734. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6735. }
  6736. }
  6737. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6738. /// and if so, check that it's a valid override and remember it.
  6739. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6740. // Look for methods in base classes that this method might override.
  6741. CXXBasePaths Paths;
  6742. FindOverriddenMethod FOM;
  6743. FOM.Method = MD;
  6744. FOM.S = this;
  6745. bool hasDeletedOverridenMethods = false;
  6746. bool hasNonDeletedOverridenMethods = false;
  6747. bool AddedAny = false;
  6748. if (DC->lookupInBases(FOM, Paths)) {
  6749. for (auto *I : Paths.found_decls()) {
  6750. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6751. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6752. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6753. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6754. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6755. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6756. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6757. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6758. AddedAny = true;
  6759. }
  6760. }
  6761. }
  6762. }
  6763. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6764. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6765. }
  6766. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6767. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6768. }
  6769. return AddedAny;
  6770. }
  6771. namespace {
  6772. // Struct for holding all of the extra arguments needed by
  6773. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6774. struct ActOnFDArgs {
  6775. Scope *S;
  6776. Declarator &D;
  6777. MultiTemplateParamsArg TemplateParamLists;
  6778. bool AddToScope;
  6779. };
  6780. } // end anonymous namespace
  6781. namespace {
  6782. // Callback to only accept typo corrections that have a non-zero edit distance.
  6783. // Also only accept corrections that have the same parent decl.
  6784. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6785. public:
  6786. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6787. CXXRecordDecl *Parent)
  6788. : Context(Context), OriginalFD(TypoFD),
  6789. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6790. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6791. if (candidate.getEditDistance() == 0)
  6792. return false;
  6793. SmallVector<unsigned, 1> MismatchedParams;
  6794. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6795. CDeclEnd = candidate.end();
  6796. CDecl != CDeclEnd; ++CDecl) {
  6797. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6798. if (FD && !FD->hasBody() &&
  6799. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6800. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6801. CXXRecordDecl *Parent = MD->getParent();
  6802. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6803. return true;
  6804. } else if (!ExpectedParent) {
  6805. return true;
  6806. }
  6807. }
  6808. }
  6809. return false;
  6810. }
  6811. private:
  6812. ASTContext &Context;
  6813. FunctionDecl *OriginalFD;
  6814. CXXRecordDecl *ExpectedParent;
  6815. };
  6816. } // end anonymous namespace
  6817. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6818. TypoCorrectedFunctionDefinitions.insert(F);
  6819. }
  6820. /// Generate diagnostics for an invalid function redeclaration.
  6821. ///
  6822. /// This routine handles generating the diagnostic messages for an invalid
  6823. /// function redeclaration, including finding possible similar declarations
  6824. /// or performing typo correction if there are no previous declarations with
  6825. /// the same name.
  6826. ///
  6827. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6828. /// the new declaration name does not cause new errors.
  6829. static NamedDecl *DiagnoseInvalidRedeclaration(
  6830. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6831. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6832. DeclarationName Name = NewFD->getDeclName();
  6833. DeclContext *NewDC = NewFD->getDeclContext();
  6834. SmallVector<unsigned, 1> MismatchedParams;
  6835. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6836. TypoCorrection Correction;
  6837. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6838. unsigned DiagMsg =
  6839. IsLocalFriend ? diag::err_no_matching_local_friend :
  6840. NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
  6841. diag::err_member_decl_does_not_match;
  6842. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6843. IsLocalFriend ? Sema::LookupLocalFriendName
  6844. : Sema::LookupOrdinaryName,
  6845. Sema::ForVisibleRedeclaration);
  6846. NewFD->setInvalidDecl();
  6847. if (IsLocalFriend)
  6848. SemaRef.LookupName(Prev, S);
  6849. else
  6850. SemaRef.LookupQualifiedName(Prev, NewDC);
  6851. assert(!Prev.isAmbiguous() &&
  6852. "Cannot have an ambiguity in previous-declaration lookup");
  6853. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6854. if (!Prev.empty()) {
  6855. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6856. Func != FuncEnd; ++Func) {
  6857. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6858. if (FD &&
  6859. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6860. // Add 1 to the index so that 0 can mean the mismatch didn't
  6861. // involve a parameter
  6862. unsigned ParamNum =
  6863. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6864. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6865. }
  6866. }
  6867. // If the qualified name lookup yielded nothing, try typo correction
  6868. } else if ((Correction = SemaRef.CorrectTypo(
  6869. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6870. &ExtraArgs.D.getCXXScopeSpec(),
  6871. llvm::make_unique<DifferentNameValidatorCCC>(
  6872. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6873. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6874. // Set up everything for the call to ActOnFunctionDeclarator
  6875. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6876. ExtraArgs.D.getIdentifierLoc());
  6877. Previous.clear();
  6878. Previous.setLookupName(Correction.getCorrection());
  6879. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6880. CDeclEnd = Correction.end();
  6881. CDecl != CDeclEnd; ++CDecl) {
  6882. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6883. if (FD && !FD->hasBody() &&
  6884. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6885. Previous.addDecl(FD);
  6886. }
  6887. }
  6888. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6889. NamedDecl *Result;
  6890. // Retry building the function declaration with the new previous
  6891. // declarations, and with errors suppressed.
  6892. {
  6893. // Trap errors.
  6894. Sema::SFINAETrap Trap(SemaRef);
  6895. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6896. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6897. // eliminate the need for the parameter pack ExtraArgs.
  6898. Result = SemaRef.ActOnFunctionDeclarator(
  6899. ExtraArgs.S, ExtraArgs.D,
  6900. Correction.getCorrectionDecl()->getDeclContext(),
  6901. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6902. ExtraArgs.AddToScope);
  6903. if (Trap.hasErrorOccurred())
  6904. Result = nullptr;
  6905. }
  6906. if (Result) {
  6907. // Determine which correction we picked.
  6908. Decl *Canonical = Result->getCanonicalDecl();
  6909. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6910. I != E; ++I)
  6911. if ((*I)->getCanonicalDecl() == Canonical)
  6912. Correction.setCorrectionDecl(*I);
  6913. // Let Sema know about the correction.
  6914. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6915. SemaRef.diagnoseTypo(
  6916. Correction,
  6917. SemaRef.PDiag(IsLocalFriend
  6918. ? diag::err_no_matching_local_friend_suggest
  6919. : diag::err_member_decl_does_not_match_suggest)
  6920. << Name << NewDC << IsDefinition);
  6921. return Result;
  6922. }
  6923. // Pretend the typo correction never occurred
  6924. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6925. ExtraArgs.D.getIdentifierLoc());
  6926. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6927. Previous.clear();
  6928. Previous.setLookupName(Name);
  6929. }
  6930. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6931. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6932. bool NewFDisConst = false;
  6933. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6934. NewFDisConst = NewMD->isConst();
  6935. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6936. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6937. NearMatch != NearMatchEnd; ++NearMatch) {
  6938. FunctionDecl *FD = NearMatch->first;
  6939. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6940. bool FDisConst = MD && MD->isConst();
  6941. bool IsMember = MD || !IsLocalFriend;
  6942. // FIXME: These notes are poorly worded for the local friend case.
  6943. if (unsigned Idx = NearMatch->second) {
  6944. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6945. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6946. if (Loc.isInvalid()) Loc = FD->getLocation();
  6947. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6948. : diag::note_local_decl_close_param_match)
  6949. << Idx << FDParam->getType()
  6950. << NewFD->getParamDecl(Idx - 1)->getType();
  6951. } else if (FDisConst != NewFDisConst) {
  6952. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6953. << NewFDisConst << FD->getSourceRange().getEnd();
  6954. } else
  6955. SemaRef.Diag(FD->getLocation(),
  6956. IsMember ? diag::note_member_def_close_match
  6957. : diag::note_local_decl_close_match);
  6958. }
  6959. return nullptr;
  6960. }
  6961. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6962. switch (D.getDeclSpec().getStorageClassSpec()) {
  6963. default: llvm_unreachable("Unknown storage class!");
  6964. case DeclSpec::SCS_auto:
  6965. case DeclSpec::SCS_register:
  6966. case DeclSpec::SCS_mutable:
  6967. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6968. diag::err_typecheck_sclass_func);
  6969. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6970. D.setInvalidType();
  6971. break;
  6972. case DeclSpec::SCS_unspecified: break;
  6973. case DeclSpec::SCS_extern:
  6974. if (D.getDeclSpec().isExternInLinkageSpec())
  6975. return SC_None;
  6976. return SC_Extern;
  6977. case DeclSpec::SCS_static: {
  6978. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6979. // C99 6.7.1p5:
  6980. // The declaration of an identifier for a function that has
  6981. // block scope shall have no explicit storage-class specifier
  6982. // other than extern
  6983. // See also (C++ [dcl.stc]p4).
  6984. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6985. diag::err_static_block_func);
  6986. break;
  6987. } else
  6988. return SC_Static;
  6989. }
  6990. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6991. }
  6992. // No explicit storage class has already been returned
  6993. return SC_None;
  6994. }
  6995. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6996. DeclContext *DC, QualType &R,
  6997. TypeSourceInfo *TInfo,
  6998. StorageClass SC,
  6999. bool &IsVirtualOkay) {
  7000. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  7001. DeclarationName Name = NameInfo.getName();
  7002. FunctionDecl *NewFD = nullptr;
  7003. bool isInline = D.getDeclSpec().isInlineSpecified();
  7004. if (!SemaRef.getLangOpts().CPlusPlus) {
  7005. // Determine whether the function was written with a
  7006. // prototype. This true when:
  7007. // - there is a prototype in the declarator, or
  7008. // - the type R of the function is some kind of typedef or other non-
  7009. // attributed reference to a type name (which eventually refers to a
  7010. // function type).
  7011. bool HasPrototype =
  7012. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7013. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7014. NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7015. R, TInfo, SC, isInline, HasPrototype, false);
  7016. if (D.isInvalidType())
  7017. NewFD->setInvalidDecl();
  7018. return NewFD;
  7019. }
  7020. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7021. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7022. // Check that the return type is not an abstract class type.
  7023. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7024. // the class has been completely parsed.
  7025. if (!DC->isRecord() &&
  7026. SemaRef.RequireNonAbstractType(
  7027. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7028. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7029. D.setInvalidType();
  7030. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7031. // This is a C++ constructor declaration.
  7032. assert(DC->isRecord() &&
  7033. "Constructors can only be declared in a member context");
  7034. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7035. return CXXConstructorDecl::Create(
  7036. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7037. TInfo, isExplicit, isInline,
  7038. /*isImplicitlyDeclared=*/false, isConstexpr);
  7039. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7040. // This is a C++ destructor declaration.
  7041. if (DC->isRecord()) {
  7042. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7043. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7044. CXXDestructorDecl *NewDD =
  7045. CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
  7046. NameInfo, R, TInfo, isInline,
  7047. /*isImplicitlyDeclared=*/false);
  7048. // If the destructor needs an implicit exception specification, set it
  7049. // now. FIXME: It'd be nice to be able to create the right type to start
  7050. // with, but the type needs to reference the destructor declaration.
  7051. if (SemaRef.getLangOpts().CPlusPlus11)
  7052. SemaRef.AdjustDestructorExceptionSpec(NewDD);
  7053. IsVirtualOkay = true;
  7054. return NewDD;
  7055. } else {
  7056. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7057. D.setInvalidType();
  7058. // Create a FunctionDecl to satisfy the function definition parsing
  7059. // code path.
  7060. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7061. D.getIdentifierLoc(), Name, R, TInfo, SC,
  7062. isInline,
  7063. /*hasPrototype=*/true, isConstexpr);
  7064. }
  7065. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7066. if (!DC->isRecord()) {
  7067. SemaRef.Diag(D.getIdentifierLoc(),
  7068. diag::err_conv_function_not_member);
  7069. return nullptr;
  7070. }
  7071. SemaRef.CheckConversionDeclarator(D, R, SC);
  7072. IsVirtualOkay = true;
  7073. return CXXConversionDecl::Create(
  7074. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7075. TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
  7076. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7077. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7078. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
  7079. isExplicit, NameInfo, R, TInfo,
  7080. D.getEndLoc());
  7081. } else if (DC->isRecord()) {
  7082. // If the name of the function is the same as the name of the record,
  7083. // then this must be an invalid constructor that has a return type.
  7084. // (The parser checks for a return type and makes the declarator a
  7085. // constructor if it has no return type).
  7086. if (Name.getAsIdentifierInfo() &&
  7087. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7088. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7089. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7090. << SourceRange(D.getIdentifierLoc());
  7091. return nullptr;
  7092. }
  7093. // This is a C++ method declaration.
  7094. CXXMethodDecl *Ret = CXXMethodDecl::Create(
  7095. SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
  7096. TInfo, SC, isInline, isConstexpr, SourceLocation());
  7097. IsVirtualOkay = !Ret->isStatic();
  7098. return Ret;
  7099. } else {
  7100. bool isFriend =
  7101. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7102. if (!isFriend && SemaRef.CurContext->isRecord())
  7103. return nullptr;
  7104. // Determine whether the function was written with a
  7105. // prototype. This true when:
  7106. // - we're in C++ (where every function has a prototype),
  7107. return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
  7108. R, TInfo, SC, isInline, true /*HasPrototype*/,
  7109. isConstexpr);
  7110. }
  7111. }
  7112. enum OpenCLParamType {
  7113. ValidKernelParam,
  7114. PtrPtrKernelParam,
  7115. PtrKernelParam,
  7116. InvalidAddrSpacePtrKernelParam,
  7117. InvalidKernelParam,
  7118. RecordKernelParam
  7119. };
  7120. static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
  7121. // Size dependent types are just typedefs to normal integer types
  7122. // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
  7123. // integers other than by their names.
  7124. StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
  7125. // Remove typedefs one by one until we reach a typedef
  7126. // for a size dependent type.
  7127. QualType DesugaredTy = Ty;
  7128. do {
  7129. ArrayRef<StringRef> Names(SizeTypeNames);
  7130. auto Match =
  7131. std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
  7132. if (Names.end() != Match)
  7133. return true;
  7134. Ty = DesugaredTy;
  7135. DesugaredTy = Ty.getSingleStepDesugaredType(C);
  7136. } while (DesugaredTy != Ty);
  7137. return false;
  7138. }
  7139. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7140. if (PT->isPointerType()) {
  7141. QualType PointeeType = PT->getPointeeType();
  7142. if (PointeeType->isPointerType())
  7143. return PtrPtrKernelParam;
  7144. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7145. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7146. PointeeType.getAddressSpace() == LangAS::Default)
  7147. return InvalidAddrSpacePtrKernelParam;
  7148. return PtrKernelParam;
  7149. }
  7150. // OpenCL v1.2 s6.9.k:
  7151. // Arguments to kernel functions in a program cannot be declared with the
  7152. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7153. // uintptr_t or a struct and/or union that contain fields declared to be one
  7154. // of these built-in scalar types.
  7155. if (isOpenCLSizeDependentType(S.getASTContext(), PT))
  7156. return InvalidKernelParam;
  7157. if (PT->isImageType())
  7158. return PtrKernelParam;
  7159. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7160. return InvalidKernelParam;
  7161. // OpenCL extension spec v1.2 s9.5:
  7162. // This extension adds support for half scalar and vector types as built-in
  7163. // types that can be used for arithmetic operations, conversions etc.
  7164. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7165. return InvalidKernelParam;
  7166. if (PT->isRecordType())
  7167. return RecordKernelParam;
  7168. // Look into an array argument to check if it has a forbidden type.
  7169. if (PT->isArrayType()) {
  7170. const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
  7171. // Call ourself to check an underlying type of an array. Since the
  7172. // getPointeeOrArrayElementType returns an innermost type which is not an
  7173. // array, this recursive call only happens once.
  7174. return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
  7175. }
  7176. return ValidKernelParam;
  7177. }
  7178. static void checkIsValidOpenCLKernelParameter(
  7179. Sema &S,
  7180. Declarator &D,
  7181. ParmVarDecl *Param,
  7182. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7183. QualType PT = Param->getType();
  7184. // Cache the valid types we encounter to avoid rechecking structs that are
  7185. // used again
  7186. if (ValidTypes.count(PT.getTypePtr()))
  7187. return;
  7188. switch (getOpenCLKernelParameterType(S, PT)) {
  7189. case PtrPtrKernelParam:
  7190. // OpenCL v1.2 s6.9.a:
  7191. // A kernel function argument cannot be declared as a
  7192. // pointer to a pointer type.
  7193. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7194. D.setInvalidType();
  7195. return;
  7196. case InvalidAddrSpacePtrKernelParam:
  7197. // OpenCL v1.0 s6.5:
  7198. // __kernel function arguments declared to be a pointer of a type can point
  7199. // to one of the following address spaces only : __global, __local or
  7200. // __constant.
  7201. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7202. D.setInvalidType();
  7203. return;
  7204. // OpenCL v1.2 s6.9.k:
  7205. // Arguments to kernel functions in a program cannot be declared with the
  7206. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7207. // uintptr_t or a struct and/or union that contain fields declared to be
  7208. // one of these built-in scalar types.
  7209. case InvalidKernelParam:
  7210. // OpenCL v1.2 s6.8 n:
  7211. // A kernel function argument cannot be declared
  7212. // of event_t type.
  7213. // Do not diagnose half type since it is diagnosed as invalid argument
  7214. // type for any function elsewhere.
  7215. if (!PT->isHalfType()) {
  7216. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7217. // Explain what typedefs are involved.
  7218. const TypedefType *Typedef = nullptr;
  7219. while ((Typedef = PT->getAs<TypedefType>())) {
  7220. SourceLocation Loc = Typedef->getDecl()->getLocation();
  7221. // SourceLocation may be invalid for a built-in type.
  7222. if (Loc.isValid())
  7223. S.Diag(Loc, diag::note_entity_declared_at) << PT;
  7224. PT = Typedef->desugar();
  7225. }
  7226. }
  7227. D.setInvalidType();
  7228. return;
  7229. case PtrKernelParam:
  7230. case ValidKernelParam:
  7231. ValidTypes.insert(PT.getTypePtr());
  7232. return;
  7233. case RecordKernelParam:
  7234. break;
  7235. }
  7236. // Track nested structs we will inspect
  7237. SmallVector<const Decl *, 4> VisitStack;
  7238. // Track where we are in the nested structs. Items will migrate from
  7239. // VisitStack to HistoryStack as we do the DFS for bad field.
  7240. SmallVector<const FieldDecl *, 4> HistoryStack;
  7241. HistoryStack.push_back(nullptr);
  7242. // At this point we already handled everything except of a RecordType or
  7243. // an ArrayType of a RecordType.
  7244. assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
  7245. const RecordType *RecTy =
  7246. PT->getPointeeOrArrayElementType()->getAs<RecordType>();
  7247. const RecordDecl *OrigRecDecl = RecTy->getDecl();
  7248. VisitStack.push_back(RecTy->getDecl());
  7249. assert(VisitStack.back() && "First decl null?");
  7250. do {
  7251. const Decl *Next = VisitStack.pop_back_val();
  7252. if (!Next) {
  7253. assert(!HistoryStack.empty());
  7254. // Found a marker, we have gone up a level
  7255. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7256. ValidTypes.insert(Hist->getType().getTypePtr());
  7257. continue;
  7258. }
  7259. // Adds everything except the original parameter declaration (which is not a
  7260. // field itself) to the history stack.
  7261. const RecordDecl *RD;
  7262. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7263. HistoryStack.push_back(Field);
  7264. QualType FieldTy = Field->getType();
  7265. // Other field types (known to be valid or invalid) are handled while we
  7266. // walk around RecordDecl::fields().
  7267. assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
  7268. "Unexpected type.");
  7269. const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
  7270. RD = FieldRecTy->castAs<RecordType>()->getDecl();
  7271. } else {
  7272. RD = cast<RecordDecl>(Next);
  7273. }
  7274. // Add a null marker so we know when we've gone back up a level
  7275. VisitStack.push_back(nullptr);
  7276. for (const auto *FD : RD->fields()) {
  7277. QualType QT = FD->getType();
  7278. if (ValidTypes.count(QT.getTypePtr()))
  7279. continue;
  7280. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7281. if (ParamType == ValidKernelParam)
  7282. continue;
  7283. if (ParamType == RecordKernelParam) {
  7284. VisitStack.push_back(FD);
  7285. continue;
  7286. }
  7287. // OpenCL v1.2 s6.9.p:
  7288. // Arguments to kernel functions that are declared to be a struct or union
  7289. // do not allow OpenCL objects to be passed as elements of the struct or
  7290. // union.
  7291. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7292. ParamType == InvalidAddrSpacePtrKernelParam) {
  7293. S.Diag(Param->getLocation(),
  7294. diag::err_record_with_pointers_kernel_param)
  7295. << PT->isUnionType()
  7296. << PT;
  7297. } else {
  7298. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7299. }
  7300. S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
  7301. << OrigRecDecl->getDeclName();
  7302. // We have an error, now let's go back up through history and show where
  7303. // the offending field came from
  7304. for (ArrayRef<const FieldDecl *>::const_iterator
  7305. I = HistoryStack.begin() + 1,
  7306. E = HistoryStack.end();
  7307. I != E; ++I) {
  7308. const FieldDecl *OuterField = *I;
  7309. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7310. << OuterField->getType();
  7311. }
  7312. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7313. << QT->isPointerType()
  7314. << QT;
  7315. D.setInvalidType();
  7316. return;
  7317. }
  7318. } while (!VisitStack.empty());
  7319. }
  7320. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7321. /// elaborated type specifier in the specified context, and lookup finds
  7322. /// nothing.
  7323. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7324. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7325. DC = DC->getParent();
  7326. return DC;
  7327. }
  7328. /// Find the Scope in which a tag is implicitly declared if we see an
  7329. /// elaborated type specifier in the specified context, and lookup finds
  7330. /// nothing.
  7331. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7332. while (S->isClassScope() ||
  7333. (LangOpts.CPlusPlus &&
  7334. S->isFunctionPrototypeScope()) ||
  7335. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7336. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7337. S = S->getParent();
  7338. return S;
  7339. }
  7340. NamedDecl*
  7341. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7342. TypeSourceInfo *TInfo, LookupResult &Previous,
  7343. MultiTemplateParamsArg TemplateParamLists,
  7344. bool &AddToScope) {
  7345. QualType R = TInfo->getType();
  7346. assert(R->isFunctionType());
  7347. // TODO: consider using NameInfo for diagnostic.
  7348. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7349. DeclarationName Name = NameInfo.getName();
  7350. StorageClass SC = getFunctionStorageClass(*this, D);
  7351. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7352. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7353. diag::err_invalid_thread)
  7354. << DeclSpec::getSpecifierName(TSCS);
  7355. if (D.isFirstDeclarationOfMember())
  7356. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7357. D.getIdentifierLoc());
  7358. bool isFriend = false;
  7359. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7360. bool isMemberSpecialization = false;
  7361. bool isFunctionTemplateSpecialization = false;
  7362. bool isDependentClassScopeExplicitSpecialization = false;
  7363. bool HasExplicitTemplateArgs = false;
  7364. TemplateArgumentListInfo TemplateArgs;
  7365. bool isVirtualOkay = false;
  7366. DeclContext *OriginalDC = DC;
  7367. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7368. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7369. isVirtualOkay);
  7370. if (!NewFD) return nullptr;
  7371. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7372. NewFD->setTopLevelDeclInObjCContainer();
  7373. // Set the lexical context. If this is a function-scope declaration, or has a
  7374. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7375. // context will be different from the semantic context.
  7376. NewFD->setLexicalDeclContext(CurContext);
  7377. if (IsLocalExternDecl)
  7378. NewFD->setLocalExternDecl();
  7379. if (getLangOpts().CPlusPlus) {
  7380. bool isInline = D.getDeclSpec().isInlineSpecified();
  7381. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7382. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7383. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7384. isFriend = D.getDeclSpec().isFriendSpecified();
  7385. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7386. // C++ [class.friend]p5
  7387. // A function can be defined in a friend declaration of a
  7388. // class . . . . Such a function is implicitly inline.
  7389. NewFD->setImplicitlyInline();
  7390. }
  7391. // If this is a method defined in an __interface, and is not a constructor
  7392. // or an overloaded operator, then set the pure flag (isVirtual will already
  7393. // return true).
  7394. if (const CXXRecordDecl *Parent =
  7395. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7396. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7397. NewFD->setPure(true);
  7398. // C++ [class.union]p2
  7399. // A union can have member functions, but not virtual functions.
  7400. if (isVirtual && Parent->isUnion())
  7401. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7402. }
  7403. SetNestedNameSpecifier(*this, NewFD, D);
  7404. isMemberSpecialization = false;
  7405. isFunctionTemplateSpecialization = false;
  7406. if (D.isInvalidType())
  7407. NewFD->setInvalidDecl();
  7408. // Match up the template parameter lists with the scope specifier, then
  7409. // determine whether we have a template or a template specialization.
  7410. bool Invalid = false;
  7411. if (TemplateParameterList *TemplateParams =
  7412. MatchTemplateParametersToScopeSpecifier(
  7413. D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
  7414. D.getCXXScopeSpec(),
  7415. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7416. ? D.getName().TemplateId
  7417. : nullptr,
  7418. TemplateParamLists, isFriend, isMemberSpecialization,
  7419. Invalid)) {
  7420. if (TemplateParams->size() > 0) {
  7421. // This is a function template
  7422. // Check that we can declare a template here.
  7423. if (CheckTemplateDeclScope(S, TemplateParams))
  7424. NewFD->setInvalidDecl();
  7425. // A destructor cannot be a template.
  7426. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7427. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7428. NewFD->setInvalidDecl();
  7429. }
  7430. // If we're adding a template to a dependent context, we may need to
  7431. // rebuilding some of the types used within the template parameter list,
  7432. // now that we know what the current instantiation is.
  7433. if (DC->isDependentContext()) {
  7434. ContextRAII SavedContext(*this, DC);
  7435. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7436. Invalid = true;
  7437. }
  7438. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7439. NewFD->getLocation(),
  7440. Name, TemplateParams,
  7441. NewFD);
  7442. FunctionTemplate->setLexicalDeclContext(CurContext);
  7443. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7444. // For source fidelity, store the other template param lists.
  7445. if (TemplateParamLists.size() > 1) {
  7446. NewFD->setTemplateParameterListsInfo(Context,
  7447. TemplateParamLists.drop_back(1));
  7448. }
  7449. } else {
  7450. // This is a function template specialization.
  7451. isFunctionTemplateSpecialization = true;
  7452. // For source fidelity, store all the template param lists.
  7453. if (TemplateParamLists.size() > 0)
  7454. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7455. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7456. if (isFriend) {
  7457. // We want to remove the "template<>", found here.
  7458. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7459. // If we remove the template<> and the name is not a
  7460. // template-id, we're actually silently creating a problem:
  7461. // the friend declaration will refer to an untemplated decl,
  7462. // and clearly the user wants a template specialization. So
  7463. // we need to insert '<>' after the name.
  7464. SourceLocation InsertLoc;
  7465. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7466. InsertLoc = D.getName().getSourceRange().getEnd();
  7467. InsertLoc = getLocForEndOfToken(InsertLoc);
  7468. }
  7469. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7470. << Name << RemoveRange
  7471. << FixItHint::CreateRemoval(RemoveRange)
  7472. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7473. }
  7474. }
  7475. } else {
  7476. // All template param lists were matched against the scope specifier:
  7477. // this is NOT (an explicit specialization of) a template.
  7478. if (TemplateParamLists.size() > 0)
  7479. // For source fidelity, store all the template param lists.
  7480. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7481. }
  7482. if (Invalid) {
  7483. NewFD->setInvalidDecl();
  7484. if (FunctionTemplate)
  7485. FunctionTemplate->setInvalidDecl();
  7486. }
  7487. // C++ [dcl.fct.spec]p5:
  7488. // The virtual specifier shall only be used in declarations of
  7489. // nonstatic class member functions that appear within a
  7490. // member-specification of a class declaration; see 10.3.
  7491. //
  7492. if (isVirtual && !NewFD->isInvalidDecl()) {
  7493. if (!isVirtualOkay) {
  7494. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7495. diag::err_virtual_non_function);
  7496. } else if (!CurContext->isRecord()) {
  7497. // 'virtual' was specified outside of the class.
  7498. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7499. diag::err_virtual_out_of_class)
  7500. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7501. } else if (NewFD->getDescribedFunctionTemplate()) {
  7502. // C++ [temp.mem]p3:
  7503. // A member function template shall not be virtual.
  7504. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7505. diag::err_virtual_member_function_template)
  7506. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7507. } else {
  7508. // Okay: Add virtual to the method.
  7509. NewFD->setVirtualAsWritten(true);
  7510. }
  7511. if (getLangOpts().CPlusPlus14 &&
  7512. NewFD->getReturnType()->isUndeducedType())
  7513. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7514. }
  7515. if (getLangOpts().CPlusPlus14 &&
  7516. (NewFD->isDependentContext() ||
  7517. (isFriend && CurContext->isDependentContext())) &&
  7518. NewFD->getReturnType()->isUndeducedType()) {
  7519. // If the function template is referenced directly (for instance, as a
  7520. // member of the current instantiation), pretend it has a dependent type.
  7521. // This is not really justified by the standard, but is the only sane
  7522. // thing to do.
  7523. // FIXME: For a friend function, we have not marked the function as being
  7524. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7525. const FunctionProtoType *FPT =
  7526. NewFD->getType()->castAs<FunctionProtoType>();
  7527. QualType Result =
  7528. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7529. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7530. FPT->getExtProtoInfo()));
  7531. }
  7532. // C++ [dcl.fct.spec]p3:
  7533. // The inline specifier shall not appear on a block scope function
  7534. // declaration.
  7535. if (isInline && !NewFD->isInvalidDecl()) {
  7536. if (CurContext->isFunctionOrMethod()) {
  7537. // 'inline' is not allowed on block scope function declaration.
  7538. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7539. diag::err_inline_declaration_block_scope) << Name
  7540. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7541. }
  7542. }
  7543. // C++ [dcl.fct.spec]p6:
  7544. // The explicit specifier shall be used only in the declaration of a
  7545. // constructor or conversion function within its class definition;
  7546. // see 12.3.1 and 12.3.2.
  7547. if (isExplicit && !NewFD->isInvalidDecl() &&
  7548. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7549. if (!CurContext->isRecord()) {
  7550. // 'explicit' was specified outside of the class.
  7551. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7552. diag::err_explicit_out_of_class)
  7553. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7554. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7555. !isa<CXXConversionDecl>(NewFD)) {
  7556. // 'explicit' was specified on a function that wasn't a constructor
  7557. // or conversion function.
  7558. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7559. diag::err_explicit_non_ctor_or_conv_function)
  7560. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7561. }
  7562. }
  7563. if (isConstexpr) {
  7564. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7565. // are implicitly inline.
  7566. NewFD->setImplicitlyInline();
  7567. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7568. // be either constructors or to return a literal type. Therefore,
  7569. // destructors cannot be declared constexpr.
  7570. if (isa<CXXDestructorDecl>(NewFD))
  7571. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7572. }
  7573. // If __module_private__ was specified, mark the function accordingly.
  7574. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7575. if (isFunctionTemplateSpecialization) {
  7576. SourceLocation ModulePrivateLoc
  7577. = D.getDeclSpec().getModulePrivateSpecLoc();
  7578. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7579. << 0
  7580. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7581. } else {
  7582. NewFD->setModulePrivate();
  7583. if (FunctionTemplate)
  7584. FunctionTemplate->setModulePrivate();
  7585. }
  7586. }
  7587. if (isFriend) {
  7588. if (FunctionTemplate) {
  7589. FunctionTemplate->setObjectOfFriendDecl();
  7590. FunctionTemplate->setAccess(AS_public);
  7591. }
  7592. NewFD->setObjectOfFriendDecl();
  7593. NewFD->setAccess(AS_public);
  7594. }
  7595. // If a function is defined as defaulted or deleted, mark it as such now.
  7596. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7597. // definition kind to FDK_Definition.
  7598. switch (D.getFunctionDefinitionKind()) {
  7599. case FDK_Declaration:
  7600. case FDK_Definition:
  7601. break;
  7602. case FDK_Defaulted:
  7603. NewFD->setDefaulted();
  7604. break;
  7605. case FDK_Deleted:
  7606. NewFD->setDeletedAsWritten();
  7607. break;
  7608. }
  7609. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7610. D.isFunctionDefinition()) {
  7611. // C++ [class.mfct]p2:
  7612. // A member function may be defined (8.4) in its class definition, in
  7613. // which case it is an inline member function (7.1.2)
  7614. NewFD->setImplicitlyInline();
  7615. }
  7616. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7617. !CurContext->isRecord()) {
  7618. // C++ [class.static]p1:
  7619. // A data or function member of a class may be declared static
  7620. // in a class definition, in which case it is a static member of
  7621. // the class.
  7622. // Complain about the 'static' specifier if it's on an out-of-line
  7623. // member function definition.
  7624. // MSVC permits the use of a 'static' storage specifier on an out-of-line
  7625. // member function template declaration, warn about this.
  7626. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7627. NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
  7628. ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
  7629. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7630. }
  7631. // C++11 [except.spec]p15:
  7632. // A deallocation function with no exception-specification is treated
  7633. // as if it were specified with noexcept(true).
  7634. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7635. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7636. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7637. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7638. NewFD->setType(Context.getFunctionType(
  7639. FPT->getReturnType(), FPT->getParamTypes(),
  7640. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7641. }
  7642. // Filter out previous declarations that don't match the scope.
  7643. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7644. D.getCXXScopeSpec().isNotEmpty() ||
  7645. isMemberSpecialization ||
  7646. isFunctionTemplateSpecialization);
  7647. // Handle GNU asm-label extension (encoded as an attribute).
  7648. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7649. // The parser guarantees this is a string.
  7650. StringLiteral *SE = cast<StringLiteral>(E);
  7651. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7652. SE->getString(), 0));
  7653. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7654. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7655. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7656. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7657. if (isDeclExternC(NewFD)) {
  7658. NewFD->addAttr(I->second);
  7659. ExtnameUndeclaredIdentifiers.erase(I);
  7660. } else
  7661. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7662. << /*Variable*/0 << NewFD;
  7663. }
  7664. }
  7665. // Copy the parameter declarations from the declarator D to the function
  7666. // declaration NewFD, if they are available. First scavenge them into Params.
  7667. SmallVector<ParmVarDecl*, 16> Params;
  7668. unsigned FTIIdx;
  7669. if (D.isFunctionDeclarator(FTIIdx)) {
  7670. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7671. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7672. // function that takes no arguments, not a function that takes a
  7673. // single void argument.
  7674. // We let through "const void" here because Sema::GetTypeForDeclarator
  7675. // already checks for that case.
  7676. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7677. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7678. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7679. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7680. Param->setDeclContext(NewFD);
  7681. Params.push_back(Param);
  7682. if (Param->isInvalidDecl())
  7683. NewFD->setInvalidDecl();
  7684. }
  7685. }
  7686. if (!getLangOpts().CPlusPlus) {
  7687. // In C, find all the tag declarations from the prototype and move them
  7688. // into the function DeclContext. Remove them from the surrounding tag
  7689. // injection context of the function, which is typically but not always
  7690. // the TU.
  7691. DeclContext *PrototypeTagContext =
  7692. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7693. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7694. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7695. // We don't want to reparent enumerators. Look at their parent enum
  7696. // instead.
  7697. if (!TD) {
  7698. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7699. TD = cast<EnumDecl>(ECD->getDeclContext());
  7700. }
  7701. if (!TD)
  7702. continue;
  7703. DeclContext *TagDC = TD->getLexicalDeclContext();
  7704. if (!TagDC->containsDecl(TD))
  7705. continue;
  7706. TagDC->removeDecl(TD);
  7707. TD->setDeclContext(NewFD);
  7708. NewFD->addDecl(TD);
  7709. // Preserve the lexical DeclContext if it is not the surrounding tag
  7710. // injection context of the FD. In this example, the semantic context of
  7711. // E will be f and the lexical context will be S, while both the
  7712. // semantic and lexical contexts of S will be f:
  7713. // void f(struct S { enum E { a } f; } s);
  7714. if (TagDC != PrototypeTagContext)
  7715. TD->setLexicalDeclContext(TagDC);
  7716. }
  7717. }
  7718. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7719. // When we're declaring a function with a typedef, typeof, etc as in the
  7720. // following example, we'll need to synthesize (unnamed)
  7721. // parameters for use in the declaration.
  7722. //
  7723. // @code
  7724. // typedef void fn(int);
  7725. // fn f;
  7726. // @endcode
  7727. // Synthesize a parameter for each argument type.
  7728. for (const auto &AI : FT->param_types()) {
  7729. ParmVarDecl *Param =
  7730. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7731. Param->setScopeInfo(0, Params.size());
  7732. Params.push_back(Param);
  7733. }
  7734. } else {
  7735. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7736. "Should not need args for typedef of non-prototype fn");
  7737. }
  7738. // Finally, we know we have the right number of parameters, install them.
  7739. NewFD->setParams(Params);
  7740. if (D.getDeclSpec().isNoreturnSpecified())
  7741. NewFD->addAttr(
  7742. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7743. Context, 0));
  7744. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7745. // because all functions have linkage.
  7746. if (!NewFD->isInvalidDecl() &&
  7747. NewFD->getReturnType()->isVariablyModifiedType()) {
  7748. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7749. NewFD->setInvalidDecl();
  7750. }
  7751. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7752. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7753. !NewFD->hasAttr<SectionAttr>()) {
  7754. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7755. PragmaClangTextSection.SectionName,
  7756. PragmaClangTextSection.PragmaLocation));
  7757. }
  7758. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7759. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7760. !NewFD->hasAttr<SectionAttr>()) {
  7761. NewFD->addAttr(
  7762. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7763. CodeSegStack.CurrentValue->getString(),
  7764. CodeSegStack.CurrentPragmaLocation));
  7765. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7766. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7767. ASTContext::PSF_Read,
  7768. NewFD))
  7769. NewFD->dropAttr<SectionAttr>();
  7770. }
  7771. // Apply an implicit CodeSegAttr from class declspec or
  7772. // apply an implicit SectionAttr from #pragma code_seg if active.
  7773. if (!NewFD->hasAttr<CodeSegAttr>()) {
  7774. if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
  7775. D.isFunctionDefinition())) {
  7776. NewFD->addAttr(SAttr);
  7777. }
  7778. }
  7779. // Handle attributes.
  7780. ProcessDeclAttributes(S, NewFD, D);
  7781. if (getLangOpts().OpenCL) {
  7782. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7783. // type declaration will generate a compilation error.
  7784. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7785. if (AddressSpace != LangAS::Default) {
  7786. Diag(NewFD->getLocation(),
  7787. diag::err_opencl_return_value_with_address_space);
  7788. NewFD->setInvalidDecl();
  7789. }
  7790. }
  7791. if (!getLangOpts().CPlusPlus) {
  7792. // Perform semantic checking on the function declaration.
  7793. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7794. CheckMain(NewFD, D.getDeclSpec());
  7795. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7796. CheckMSVCRTEntryPoint(NewFD);
  7797. if (!NewFD->isInvalidDecl())
  7798. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7799. isMemberSpecialization));
  7800. else if (!Previous.empty())
  7801. // Recover gracefully from an invalid redeclaration.
  7802. D.setRedeclaration(true);
  7803. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7804. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7805. "previous declaration set still overloaded");
  7806. // Diagnose no-prototype function declarations with calling conventions that
  7807. // don't support variadic calls. Only do this in C and do it after merging
  7808. // possibly prototyped redeclarations.
  7809. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7810. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7811. CallingConv CC = FT->getExtInfo().getCC();
  7812. if (!supportsVariadicCall(CC)) {
  7813. // Windows system headers sometimes accidentally use stdcall without
  7814. // (void) parameters, so we relax this to a warning.
  7815. int DiagID =
  7816. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7817. Diag(NewFD->getLocation(), DiagID)
  7818. << FunctionType::getNameForCallConv(CC);
  7819. }
  7820. }
  7821. } else {
  7822. // C++11 [replacement.functions]p3:
  7823. // The program's definitions shall not be specified as inline.
  7824. //
  7825. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7826. //
  7827. // Suppress the diagnostic if the function is __attribute__((used)), since
  7828. // that forces an external definition to be emitted.
  7829. if (D.getDeclSpec().isInlineSpecified() &&
  7830. NewFD->isReplaceableGlobalAllocationFunction() &&
  7831. !NewFD->hasAttr<UsedAttr>())
  7832. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7833. diag::ext_operator_new_delete_declared_inline)
  7834. << NewFD->getDeclName();
  7835. // If the declarator is a template-id, translate the parser's template
  7836. // argument list into our AST format.
  7837. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7838. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7839. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7840. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7841. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7842. TemplateId->NumArgs);
  7843. translateTemplateArguments(TemplateArgsPtr,
  7844. TemplateArgs);
  7845. HasExplicitTemplateArgs = true;
  7846. if (NewFD->isInvalidDecl()) {
  7847. HasExplicitTemplateArgs = false;
  7848. } else if (FunctionTemplate) {
  7849. // Function template with explicit template arguments.
  7850. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7851. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7852. HasExplicitTemplateArgs = false;
  7853. } else {
  7854. assert((isFunctionTemplateSpecialization ||
  7855. D.getDeclSpec().isFriendSpecified()) &&
  7856. "should have a 'template<>' for this decl");
  7857. // "friend void foo<>(int);" is an implicit specialization decl.
  7858. isFunctionTemplateSpecialization = true;
  7859. }
  7860. } else if (isFriend && isFunctionTemplateSpecialization) {
  7861. // This combination is only possible in a recovery case; the user
  7862. // wrote something like:
  7863. // template <> friend void foo(int);
  7864. // which we're recovering from as if the user had written:
  7865. // friend void foo<>(int);
  7866. // Go ahead and fake up a template id.
  7867. HasExplicitTemplateArgs = true;
  7868. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7869. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7870. }
  7871. // We do not add HD attributes to specializations here because
  7872. // they may have different constexpr-ness compared to their
  7873. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7874. // may end up with different effective targets. Instead, a
  7875. // specialization inherits its target attributes from its template
  7876. // in the CheckFunctionTemplateSpecialization() call below.
  7877. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7878. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7879. // If it's a friend (and only if it's a friend), it's possible
  7880. // that either the specialized function type or the specialized
  7881. // template is dependent, and therefore matching will fail. In
  7882. // this case, don't check the specialization yet.
  7883. bool InstantiationDependent = false;
  7884. if (isFunctionTemplateSpecialization && isFriend &&
  7885. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7886. TemplateSpecializationType::anyDependentTemplateArguments(
  7887. TemplateArgs,
  7888. InstantiationDependent))) {
  7889. assert(HasExplicitTemplateArgs &&
  7890. "friend function specialization without template args");
  7891. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7892. Previous))
  7893. NewFD->setInvalidDecl();
  7894. } else if (isFunctionTemplateSpecialization) {
  7895. if (CurContext->isDependentContext() && CurContext->isRecord()
  7896. && !isFriend) {
  7897. isDependentClassScopeExplicitSpecialization = true;
  7898. } else if (!NewFD->isInvalidDecl() &&
  7899. CheckFunctionTemplateSpecialization(
  7900. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7901. Previous))
  7902. NewFD->setInvalidDecl();
  7903. // C++ [dcl.stc]p1:
  7904. // A storage-class-specifier shall not be specified in an explicit
  7905. // specialization (14.7.3)
  7906. FunctionTemplateSpecializationInfo *Info =
  7907. NewFD->getTemplateSpecializationInfo();
  7908. if (Info && SC != SC_None) {
  7909. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7910. Diag(NewFD->getLocation(),
  7911. diag::err_explicit_specialization_inconsistent_storage_class)
  7912. << SC
  7913. << FixItHint::CreateRemoval(
  7914. D.getDeclSpec().getStorageClassSpecLoc());
  7915. else
  7916. Diag(NewFD->getLocation(),
  7917. diag::ext_explicit_specialization_storage_class)
  7918. << FixItHint::CreateRemoval(
  7919. D.getDeclSpec().getStorageClassSpecLoc());
  7920. }
  7921. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7922. if (CheckMemberSpecialization(NewFD, Previous))
  7923. NewFD->setInvalidDecl();
  7924. }
  7925. // Perform semantic checking on the function declaration.
  7926. if (!isDependentClassScopeExplicitSpecialization) {
  7927. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7928. CheckMain(NewFD, D.getDeclSpec());
  7929. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7930. CheckMSVCRTEntryPoint(NewFD);
  7931. if (!NewFD->isInvalidDecl())
  7932. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7933. isMemberSpecialization));
  7934. else if (!Previous.empty())
  7935. // Recover gracefully from an invalid redeclaration.
  7936. D.setRedeclaration(true);
  7937. }
  7938. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7939. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7940. "previous declaration set still overloaded");
  7941. NamedDecl *PrincipalDecl = (FunctionTemplate
  7942. ? cast<NamedDecl>(FunctionTemplate)
  7943. : NewFD);
  7944. if (isFriend && NewFD->getPreviousDecl()) {
  7945. AccessSpecifier Access = AS_public;
  7946. if (!NewFD->isInvalidDecl())
  7947. Access = NewFD->getPreviousDecl()->getAccess();
  7948. NewFD->setAccess(Access);
  7949. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7950. }
  7951. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7952. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7953. PrincipalDecl->setNonMemberOperator();
  7954. // If we have a function template, check the template parameter
  7955. // list. This will check and merge default template arguments.
  7956. if (FunctionTemplate) {
  7957. FunctionTemplateDecl *PrevTemplate =
  7958. FunctionTemplate->getPreviousDecl();
  7959. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7960. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7961. : nullptr,
  7962. D.getDeclSpec().isFriendSpecified()
  7963. ? (D.isFunctionDefinition()
  7964. ? TPC_FriendFunctionTemplateDefinition
  7965. : TPC_FriendFunctionTemplate)
  7966. : (D.getCXXScopeSpec().isSet() &&
  7967. DC && DC->isRecord() &&
  7968. DC->isDependentContext())
  7969. ? TPC_ClassTemplateMember
  7970. : TPC_FunctionTemplate);
  7971. }
  7972. if (NewFD->isInvalidDecl()) {
  7973. // Ignore all the rest of this.
  7974. } else if (!D.isRedeclaration()) {
  7975. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7976. AddToScope };
  7977. // Fake up an access specifier if it's supposed to be a class member.
  7978. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7979. NewFD->setAccess(AS_public);
  7980. // Qualified decls generally require a previous declaration.
  7981. if (D.getCXXScopeSpec().isSet()) {
  7982. // ...with the major exception of templated-scope or
  7983. // dependent-scope friend declarations.
  7984. // TODO: we currently also suppress this check in dependent
  7985. // contexts because (1) the parameter depth will be off when
  7986. // matching friend templates and (2) we might actually be
  7987. // selecting a friend based on a dependent factor. But there
  7988. // are situations where these conditions don't apply and we
  7989. // can actually do this check immediately.
  7990. //
  7991. // Unless the scope is dependent, it's always an error if qualified
  7992. // redeclaration lookup found nothing at all. Diagnose that now;
  7993. // nothing will diagnose that error later.
  7994. if (isFriend &&
  7995. (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7996. (!Previous.empty() && (TemplateParamLists.size() ||
  7997. CurContext->isDependentContext())))) {
  7998. // ignore these
  7999. } else {
  8000. // The user tried to provide an out-of-line definition for a
  8001. // function that is a member of a class or namespace, but there
  8002. // was no such member function declared (C++ [class.mfct]p2,
  8003. // C++ [namespace.memdef]p2). For example:
  8004. //
  8005. // class X {
  8006. // void f() const;
  8007. // };
  8008. //
  8009. // void X::f() { } // ill-formed
  8010. //
  8011. // Complain about this problem, and attempt to suggest close
  8012. // matches (e.g., those that differ only in cv-qualifiers and
  8013. // whether the parameter types are references).
  8014. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8015. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  8016. AddToScope = ExtraArgs.AddToScope;
  8017. return Result;
  8018. }
  8019. }
  8020. // Unqualified local friend declarations are required to resolve
  8021. // to something.
  8022. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  8023. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  8024. *this, Previous, NewFD, ExtraArgs, true, S)) {
  8025. AddToScope = ExtraArgs.AddToScope;
  8026. return Result;
  8027. }
  8028. }
  8029. } else if (!D.isFunctionDefinition() &&
  8030. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  8031. !isFriend && !isFunctionTemplateSpecialization &&
  8032. !isMemberSpecialization) {
  8033. // An out-of-line member function declaration must also be a
  8034. // definition (C++ [class.mfct]p2).
  8035. // Note that this is not the case for explicit specializations of
  8036. // function templates or member functions of class templates, per
  8037. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  8038. // extension for compatibility with old SWIG code which likes to
  8039. // generate them.
  8040. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  8041. << D.getCXXScopeSpec().getRange();
  8042. }
  8043. }
  8044. ProcessPragmaWeak(S, NewFD);
  8045. checkAttributesAfterMerging(*this, *NewFD);
  8046. AddKnownFunctionAttributes(NewFD);
  8047. if (NewFD->hasAttr<OverloadableAttr>() &&
  8048. !NewFD->getType()->getAs<FunctionProtoType>()) {
  8049. Diag(NewFD->getLocation(),
  8050. diag::err_attribute_overloadable_no_prototype)
  8051. << NewFD;
  8052. // Turn this into a variadic function with no parameters.
  8053. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  8054. FunctionProtoType::ExtProtoInfo EPI(
  8055. Context.getDefaultCallingConvention(true, false));
  8056. EPI.Variadic = true;
  8057. EPI.ExtInfo = FT->getExtInfo();
  8058. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  8059. NewFD->setType(R);
  8060. }
  8061. // If there's a #pragma GCC visibility in scope, and this isn't a class
  8062. // member, set the visibility of this function.
  8063. if (!DC->isRecord() && NewFD->isExternallyVisible())
  8064. AddPushedVisibilityAttribute(NewFD);
  8065. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  8066. // marking the function.
  8067. AddCFAuditedAttribute(NewFD);
  8068. // If this is a function definition, check if we have to apply optnone due to
  8069. // a pragma.
  8070. if(D.isFunctionDefinition())
  8071. AddRangeBasedOptnone(NewFD);
  8072. // If this is the first declaration of an extern C variable, update
  8073. // the map of such variables.
  8074. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8075. isIncompleteDeclExternC(*this, NewFD))
  8076. RegisterLocallyScopedExternCDecl(NewFD, S);
  8077. // Set this FunctionDecl's range up to the right paren.
  8078. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8079. if (D.isRedeclaration() && !Previous.empty()) {
  8080. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8081. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8082. isMemberSpecialization ||
  8083. isFunctionTemplateSpecialization,
  8084. D.isFunctionDefinition());
  8085. }
  8086. if (getLangOpts().CUDA) {
  8087. IdentifierInfo *II = NewFD->getIdentifier();
  8088. if (II && II->isStr(getCudaConfigureFuncName()) &&
  8089. !NewFD->isInvalidDecl() &&
  8090. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8091. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8092. Diag(NewFD->getLocation(), diag::err_config_scalar_return)
  8093. << getCudaConfigureFuncName();
  8094. Context.setcudaConfigureCallDecl(NewFD);
  8095. }
  8096. // Variadic functions, other than a *declaration* of printf, are not allowed
  8097. // in device-side CUDA code, unless someone passed
  8098. // -fcuda-allow-variadic-functions.
  8099. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8100. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8101. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8102. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8103. !D.isFunctionDefinition())) {
  8104. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8105. }
  8106. }
  8107. MarkUnusedFileScopedDecl(NewFD);
  8108. if (getLangOpts().CPlusPlus) {
  8109. if (FunctionTemplate) {
  8110. if (NewFD->isInvalidDecl())
  8111. FunctionTemplate->setInvalidDecl();
  8112. return FunctionTemplate;
  8113. }
  8114. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8115. CompleteMemberSpecialization(NewFD, Previous);
  8116. }
  8117. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  8118. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8119. if ((getLangOpts().OpenCLVersion >= 120)
  8120. && (SC == SC_Static)) {
  8121. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8122. D.setInvalidType();
  8123. }
  8124. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8125. if (!NewFD->getReturnType()->isVoidType()) {
  8126. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8127. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8128. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8129. : FixItHint());
  8130. D.setInvalidType();
  8131. }
  8132. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8133. for (auto Param : NewFD->parameters())
  8134. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8135. }
  8136. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8137. QualType PT = Param->getType();
  8138. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8139. // types.
  8140. if (getLangOpts().OpenCLVersion >= 200) {
  8141. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8142. QualType ElemTy = PipeTy->getElementType();
  8143. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8144. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8145. D.setInvalidType();
  8146. }
  8147. }
  8148. }
  8149. }
  8150. // Here we have an function template explicit specialization at class scope.
  8151. // The actual specialization will be postponed to template instatiation
  8152. // time via the ClassScopeFunctionSpecializationDecl node.
  8153. if (isDependentClassScopeExplicitSpecialization) {
  8154. ClassScopeFunctionSpecializationDecl *NewSpec =
  8155. ClassScopeFunctionSpecializationDecl::Create(
  8156. Context, CurContext, NewFD->getLocation(),
  8157. cast<CXXMethodDecl>(NewFD),
  8158. HasExplicitTemplateArgs, TemplateArgs);
  8159. CurContext->addDecl(NewSpec);
  8160. AddToScope = false;
  8161. }
  8162. // Diagnose availability attributes. Availability cannot be used on functions
  8163. // that are run during load/unload.
  8164. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8165. if (NewFD->hasAttr<ConstructorAttr>()) {
  8166. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8167. << 1;
  8168. NewFD->dropAttr<AvailabilityAttr>();
  8169. }
  8170. if (NewFD->hasAttr<DestructorAttr>()) {
  8171. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8172. << 2;
  8173. NewFD->dropAttr<AvailabilityAttr>();
  8174. }
  8175. }
  8176. return NewFD;
  8177. }
  8178. /// Return a CodeSegAttr from a containing class. The Microsoft docs say
  8179. /// when __declspec(code_seg) "is applied to a class, all member functions of
  8180. /// the class and nested classes -- this includes compiler-generated special
  8181. /// member functions -- are put in the specified segment."
  8182. /// The actual behavior is a little more complicated. The Microsoft compiler
  8183. /// won't check outer classes if there is an active value from #pragma code_seg.
  8184. /// The CodeSeg is always applied from the direct parent but only from outer
  8185. /// classes when the #pragma code_seg stack is empty. See:
  8186. /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
  8187. /// available since MS has removed the page.
  8188. static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
  8189. const auto *Method = dyn_cast<CXXMethodDecl>(FD);
  8190. if (!Method)
  8191. return nullptr;
  8192. const CXXRecordDecl *Parent = Method->getParent();
  8193. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8194. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8195. NewAttr->setImplicit(true);
  8196. return NewAttr;
  8197. }
  8198. // The Microsoft compiler won't check outer classes for the CodeSeg
  8199. // when the #pragma code_seg stack is active.
  8200. if (S.CodeSegStack.CurrentValue)
  8201. return nullptr;
  8202. while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
  8203. if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
  8204. Attr *NewAttr = SAttr->clone(S.getASTContext());
  8205. NewAttr->setImplicit(true);
  8206. return NewAttr;
  8207. }
  8208. }
  8209. return nullptr;
  8210. }
  8211. /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
  8212. /// containing class. Otherwise it will return implicit SectionAttr if the
  8213. /// function is a definition and there is an active value on CodeSegStack
  8214. /// (from the current #pragma code-seg value).
  8215. ///
  8216. /// \param FD Function being declared.
  8217. /// \param IsDefinition Whether it is a definition or just a declarartion.
  8218. /// \returns A CodeSegAttr or SectionAttr to apply to the function or
  8219. /// nullptr if no attribute should be added.
  8220. Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
  8221. bool IsDefinition) {
  8222. if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
  8223. return A;
  8224. if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
  8225. CodeSegStack.CurrentValue) {
  8226. return SectionAttr::CreateImplicit(getASTContext(),
  8227. SectionAttr::Declspec_allocate,
  8228. CodeSegStack.CurrentValue->getString(),
  8229. CodeSegStack.CurrentPragmaLocation);
  8230. }
  8231. return nullptr;
  8232. }
  8233. /// Determines if we can perform a correct type check for \p D as a
  8234. /// redeclaration of \p PrevDecl. If not, we can generally still perform a
  8235. /// best-effort check.
  8236. ///
  8237. /// \param NewD The new declaration.
  8238. /// \param OldD The old declaration.
  8239. /// \param NewT The portion of the type of the new declaration to check.
  8240. /// \param OldT The portion of the type of the old declaration to check.
  8241. bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
  8242. QualType NewT, QualType OldT) {
  8243. if (!NewD->getLexicalDeclContext()->isDependentContext())
  8244. return true;
  8245. // For dependently-typed local extern declarations and friends, we can't
  8246. // perform a correct type check in general until instantiation:
  8247. //
  8248. // int f();
  8249. // template<typename T> void g() { T f(); }
  8250. //
  8251. // (valid if g() is only instantiated with T = int).
  8252. if (NewT->isDependentType() &&
  8253. (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
  8254. return false;
  8255. // Similarly, if the previous declaration was a dependent local extern
  8256. // declaration, we don't really know its type yet.
  8257. if (OldT->isDependentType() && OldD->isLocalExternDecl())
  8258. return false;
  8259. return true;
  8260. }
  8261. /// Checks if the new declaration declared in dependent context must be
  8262. /// put in the same redeclaration chain as the specified declaration.
  8263. ///
  8264. /// \param D Declaration that is checked.
  8265. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8266. /// same declaration name.
  8267. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8268. /// belongs to.
  8269. ///
  8270. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8271. if (!D->getLexicalDeclContext()->isDependentContext())
  8272. return true;
  8273. // Don't chain dependent friend function definitions until instantiation, to
  8274. // permit cases like
  8275. //
  8276. // void func();
  8277. // template<typename T> class C1 { friend void func() {} };
  8278. // template<typename T> class C2 { friend void func() {} };
  8279. //
  8280. // ... which is valid if only one of C1 and C2 is ever instantiated.
  8281. //
  8282. // FIXME: This need only apply to function definitions. For now, we proxy
  8283. // this by checking for a file-scope function. We do not want this to apply
  8284. // to friend declarations nominating member functions, because that gets in
  8285. // the way of access checks.
  8286. if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
  8287. return false;
  8288. auto *VD = dyn_cast<ValueDecl>(D);
  8289. auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
  8290. return !VD || !PrevVD ||
  8291. canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
  8292. PrevVD->getType());
  8293. }
  8294. /// Check the target attribute of the function for MultiVersion
  8295. /// validity.
  8296. ///
  8297. /// Returns true if there was an error, false otherwise.
  8298. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8299. const auto *TA = FD->getAttr<TargetAttr>();
  8300. assert(TA && "MultiVersion Candidate requires a target attribute");
  8301. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8302. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8303. enum ErrType { Feature = 0, Architecture = 1 };
  8304. if (!ParseInfo.Architecture.empty() &&
  8305. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8306. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8307. << Architecture << ParseInfo.Architecture;
  8308. return true;
  8309. }
  8310. for (const auto &Feat : ParseInfo.Features) {
  8311. auto BareFeat = StringRef{Feat}.substr(1);
  8312. if (Feat[0] == '-') {
  8313. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8314. << Feature << ("no-" + BareFeat).str();
  8315. return true;
  8316. }
  8317. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8318. !TargetInfo.isValidFeatureName(BareFeat)) {
  8319. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8320. << Feature << BareFeat;
  8321. return true;
  8322. }
  8323. }
  8324. return false;
  8325. }
  8326. static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
  8327. MultiVersionKind MVType) {
  8328. for (const Attr *A : FD->attrs()) {
  8329. switch (A->getKind()) {
  8330. case attr::CPUDispatch:
  8331. case attr::CPUSpecific:
  8332. if (MVType != MultiVersionKind::CPUDispatch &&
  8333. MVType != MultiVersionKind::CPUSpecific)
  8334. return true;
  8335. break;
  8336. case attr::Target:
  8337. if (MVType != MultiVersionKind::Target)
  8338. return true;
  8339. break;
  8340. default:
  8341. return true;
  8342. }
  8343. }
  8344. return false;
  8345. }
  8346. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8347. const FunctionDecl *NewFD,
  8348. bool CausesMV,
  8349. MultiVersionKind MVType) {
  8350. enum DoesntSupport {
  8351. FuncTemplates = 0,
  8352. VirtFuncs = 1,
  8353. DeducedReturn = 2,
  8354. Constructors = 3,
  8355. Destructors = 4,
  8356. DeletedFuncs = 5,
  8357. DefaultedFuncs = 6,
  8358. ConstexprFuncs = 7,
  8359. };
  8360. enum Different {
  8361. CallingConv = 0,
  8362. ReturnType = 1,
  8363. ConstexprSpec = 2,
  8364. InlineSpec = 3,
  8365. StorageClass = 4,
  8366. Linkage = 5
  8367. };
  8368. bool IsCPUSpecificCPUDispatchMVType =
  8369. MVType == MultiVersionKind::CPUDispatch ||
  8370. MVType == MultiVersionKind::CPUSpecific;
  8371. if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
  8372. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8373. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8374. return true;
  8375. }
  8376. if (!NewFD->getType()->getAs<FunctionProtoType>())
  8377. return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8378. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8379. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8380. if (OldFD)
  8381. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8382. return true;
  8383. }
  8384. // For now, disallow all other attributes. These should be opt-in, but
  8385. // an analysis of all of them is a future FIXME.
  8386. if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
  8387. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8388. << IsCPUSpecificCPUDispatchMVType;
  8389. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8390. return true;
  8391. }
  8392. if (HasNonMultiVersionAttributes(NewFD, MVType))
  8393. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
  8394. << IsCPUSpecificCPUDispatchMVType;
  8395. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8396. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8397. << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
  8398. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8399. if (NewCXXFD->isVirtual())
  8400. return S.Diag(NewCXXFD->getLocation(),
  8401. diag::err_multiversion_doesnt_support)
  8402. << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
  8403. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8404. return S.Diag(NewCXXCtor->getLocation(),
  8405. diag::err_multiversion_doesnt_support)
  8406. << IsCPUSpecificCPUDispatchMVType << Constructors;
  8407. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8408. return S.Diag(NewCXXDtor->getLocation(),
  8409. diag::err_multiversion_doesnt_support)
  8410. << IsCPUSpecificCPUDispatchMVType << Destructors;
  8411. }
  8412. if (NewFD->isDeleted())
  8413. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8414. << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
  8415. if (NewFD->isDefaulted())
  8416. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8417. << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
  8418. if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
  8419. MVType == MultiVersionKind::CPUSpecific))
  8420. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8421. << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
  8422. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8423. const auto *NewType = cast<FunctionType>(NewQType);
  8424. QualType NewReturnType = NewType->getReturnType();
  8425. if (NewReturnType->isUndeducedType())
  8426. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8427. << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
  8428. // Only allow transition to MultiVersion if it hasn't been used.
  8429. if (OldFD && CausesMV && OldFD->isUsed(false))
  8430. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8431. // Ensure the return type is identical.
  8432. if (OldFD) {
  8433. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8434. const auto *OldType = cast<FunctionType>(OldQType);
  8435. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8436. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8437. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8438. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8439. << CallingConv;
  8440. QualType OldReturnType = OldType->getReturnType();
  8441. if (OldReturnType != NewReturnType)
  8442. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8443. << ReturnType;
  8444. if (OldFD->isConstexpr() != NewFD->isConstexpr())
  8445. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8446. << ConstexprSpec;
  8447. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8448. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8449. << InlineSpec;
  8450. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8451. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8452. << StorageClass;
  8453. if (OldFD->isExternC() != NewFD->isExternC())
  8454. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8455. << Linkage;
  8456. if (S.CheckEquivalentExceptionSpec(
  8457. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8458. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8459. return true;
  8460. }
  8461. return false;
  8462. }
  8463. /// Check the validity of a multiversion function declaration that is the
  8464. /// first of its kind. Also sets the multiversion'ness' of the function itself.
  8465. ///
  8466. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8467. ///
  8468. /// Returns true if there was an error, false otherwise.
  8469. static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
  8470. MultiVersionKind MVType,
  8471. const TargetAttr *TA,
  8472. const CPUDispatchAttr *CPUDisp,
  8473. const CPUSpecificAttr *CPUSpec) {
  8474. assert(MVType != MultiVersionKind::None &&
  8475. "Function lacks multiversion attribute");
  8476. // Target only causes MV if it is default, otherwise this is a normal
  8477. // function.
  8478. if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
  8479. return false;
  8480. if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
  8481. FD->setInvalidDecl();
  8482. return true;
  8483. }
  8484. if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
  8485. FD->setInvalidDecl();
  8486. return true;
  8487. }
  8488. FD->setIsMultiVersion();
  8489. return false;
  8490. }
  8491. static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
  8492. for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
  8493. if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
  8494. return true;
  8495. }
  8496. return false;
  8497. }
  8498. static bool CheckTargetCausesMultiVersioning(
  8499. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
  8500. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8501. LookupResult &Previous) {
  8502. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8503. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8504. // Sort order doesn't matter, it just needs to be consistent.
  8505. llvm::sort(NewParsed.Features);
  8506. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8507. // to change, this is a simple redeclaration.
  8508. if (!NewTA->isDefaultVersion() &&
  8509. (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
  8510. return false;
  8511. // Otherwise, this decl causes MultiVersioning.
  8512. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8513. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8514. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8515. NewFD->setInvalidDecl();
  8516. return true;
  8517. }
  8518. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
  8519. MultiVersionKind::Target)) {
  8520. NewFD->setInvalidDecl();
  8521. return true;
  8522. }
  8523. if (CheckMultiVersionValue(S, NewFD)) {
  8524. NewFD->setInvalidDecl();
  8525. return true;
  8526. }
  8527. // If this is 'default', permit the forward declaration.
  8528. if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
  8529. Redeclaration = true;
  8530. OldDecl = OldFD;
  8531. OldFD->setIsMultiVersion();
  8532. NewFD->setIsMultiVersion();
  8533. return false;
  8534. }
  8535. if (CheckMultiVersionValue(S, OldFD)) {
  8536. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8537. NewFD->setInvalidDecl();
  8538. return true;
  8539. }
  8540. TargetAttr::ParsedTargetAttr OldParsed =
  8541. OldTA->parse(std::less<std::string>());
  8542. if (OldParsed == NewParsed) {
  8543. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8544. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8545. NewFD->setInvalidDecl();
  8546. return true;
  8547. }
  8548. for (const auto *FD : OldFD->redecls()) {
  8549. const auto *CurTA = FD->getAttr<TargetAttr>();
  8550. // We allow forward declarations before ANY multiversioning attributes, but
  8551. // nothing after the fact.
  8552. if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
  8553. (!CurTA || CurTA->isInherited())) {
  8554. S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
  8555. << 0;
  8556. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8557. NewFD->setInvalidDecl();
  8558. return true;
  8559. }
  8560. }
  8561. OldFD->setIsMultiVersion();
  8562. NewFD->setIsMultiVersion();
  8563. Redeclaration = false;
  8564. MergeTypeWithPrevious = false;
  8565. OldDecl = nullptr;
  8566. Previous.clear();
  8567. return false;
  8568. }
  8569. /// Check the validity of a new function declaration being added to an existing
  8570. /// multiversioned declaration collection.
  8571. static bool CheckMultiVersionAdditionalDecl(
  8572. Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
  8573. MultiVersionKind NewMVType, const TargetAttr *NewTA,
  8574. const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
  8575. bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
  8576. LookupResult &Previous) {
  8577. MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
  8578. // Disallow mixing of multiversioning types.
  8579. if ((OldMVType == MultiVersionKind::Target &&
  8580. NewMVType != MultiVersionKind::Target) ||
  8581. (NewMVType == MultiVersionKind::Target &&
  8582. OldMVType != MultiVersionKind::Target)) {
  8583. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8584. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8585. NewFD->setInvalidDecl();
  8586. return true;
  8587. }
  8588. TargetAttr::ParsedTargetAttr NewParsed;
  8589. if (NewTA) {
  8590. NewParsed = NewTA->parse();
  8591. llvm::sort(NewParsed.Features);
  8592. }
  8593. bool UseMemberUsingDeclRules =
  8594. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8595. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8596. // previous member of the MultiVersion set.
  8597. for (NamedDecl *ND : Previous) {
  8598. FunctionDecl *CurFD = ND->getAsFunction();
  8599. if (!CurFD)
  8600. continue;
  8601. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8602. continue;
  8603. if (NewMVType == MultiVersionKind::Target) {
  8604. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8605. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8606. NewFD->setIsMultiVersion();
  8607. Redeclaration = true;
  8608. OldDecl = ND;
  8609. return false;
  8610. }
  8611. TargetAttr::ParsedTargetAttr CurParsed =
  8612. CurTA->parse(std::less<std::string>());
  8613. if (CurParsed == NewParsed) {
  8614. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8615. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8616. NewFD->setInvalidDecl();
  8617. return true;
  8618. }
  8619. } else {
  8620. const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
  8621. const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
  8622. // Handle CPUDispatch/CPUSpecific versions.
  8623. // Only 1 CPUDispatch function is allowed, this will make it go through
  8624. // the redeclaration errors.
  8625. if (NewMVType == MultiVersionKind::CPUDispatch &&
  8626. CurFD->hasAttr<CPUDispatchAttr>()) {
  8627. if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
  8628. std::equal(
  8629. CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
  8630. NewCPUDisp->cpus_begin(),
  8631. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8632. return Cur->getName() == New->getName();
  8633. })) {
  8634. NewFD->setIsMultiVersion();
  8635. Redeclaration = true;
  8636. OldDecl = ND;
  8637. return false;
  8638. }
  8639. // If the declarations don't match, this is an error condition.
  8640. S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
  8641. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8642. NewFD->setInvalidDecl();
  8643. return true;
  8644. }
  8645. if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
  8646. if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
  8647. std::equal(
  8648. CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
  8649. NewCPUSpec->cpus_begin(),
  8650. [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
  8651. return Cur->getName() == New->getName();
  8652. })) {
  8653. NewFD->setIsMultiVersion();
  8654. Redeclaration = true;
  8655. OldDecl = ND;
  8656. return false;
  8657. }
  8658. // Only 1 version of CPUSpecific is allowed for each CPU.
  8659. for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
  8660. for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
  8661. if (CurII == NewII) {
  8662. S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
  8663. << NewII;
  8664. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8665. NewFD->setInvalidDecl();
  8666. return true;
  8667. }
  8668. }
  8669. }
  8670. }
  8671. // If the two decls aren't the same MVType, there is no possible error
  8672. // condition.
  8673. }
  8674. }
  8675. // Else, this is simply a non-redecl case. Checking the 'value' is only
  8676. // necessary in the Target case, since The CPUSpecific/Dispatch cases are
  8677. // handled in the attribute adding step.
  8678. if (NewMVType == MultiVersionKind::Target &&
  8679. CheckMultiVersionValue(S, NewFD)) {
  8680. NewFD->setInvalidDecl();
  8681. return true;
  8682. }
  8683. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
  8684. !OldFD->isMultiVersion(), NewMVType)) {
  8685. NewFD->setInvalidDecl();
  8686. return true;
  8687. }
  8688. // Permit forward declarations in the case where these two are compatible.
  8689. if (!OldFD->isMultiVersion()) {
  8690. OldFD->setIsMultiVersion();
  8691. NewFD->setIsMultiVersion();
  8692. Redeclaration = true;
  8693. OldDecl = OldFD;
  8694. return false;
  8695. }
  8696. NewFD->setIsMultiVersion();
  8697. Redeclaration = false;
  8698. MergeTypeWithPrevious = false;
  8699. OldDecl = nullptr;
  8700. Previous.clear();
  8701. return false;
  8702. }
  8703. /// Check the validity of a mulitversion function declaration.
  8704. /// Also sets the multiversion'ness' of the function itself.
  8705. ///
  8706. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8707. ///
  8708. /// Returns true if there was an error, false otherwise.
  8709. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8710. bool &Redeclaration, NamedDecl *&OldDecl,
  8711. bool &MergeTypeWithPrevious,
  8712. LookupResult &Previous) {
  8713. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8714. const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
  8715. const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
  8716. // Mixing Multiversioning types is prohibited.
  8717. if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
  8718. (NewCPUDisp && NewCPUSpec)) {
  8719. S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
  8720. NewFD->setInvalidDecl();
  8721. return true;
  8722. }
  8723. MultiVersionKind MVType = NewFD->getMultiVersionKind();
  8724. // Main isn't allowed to become a multiversion function, however it IS
  8725. // permitted to have 'main' be marked with the 'target' optimization hint.
  8726. if (NewFD->isMain()) {
  8727. if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
  8728. MVType == MultiVersionKind::CPUDispatch ||
  8729. MVType == MultiVersionKind::CPUSpecific) {
  8730. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8731. NewFD->setInvalidDecl();
  8732. return true;
  8733. }
  8734. return false;
  8735. }
  8736. if (!OldDecl || !OldDecl->getAsFunction() ||
  8737. OldDecl->getDeclContext()->getRedeclContext() !=
  8738. NewFD->getDeclContext()->getRedeclContext()) {
  8739. // If there's no previous declaration, AND this isn't attempting to cause
  8740. // multiversioning, this isn't an error condition.
  8741. if (MVType == MultiVersionKind::None)
  8742. return false;
  8743. return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
  8744. NewCPUSpec);
  8745. }
  8746. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8747. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
  8748. return false;
  8749. if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
  8750. S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
  8751. << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
  8752. NewFD->setInvalidDecl();
  8753. return true;
  8754. }
  8755. // Handle the target potentially causes multiversioning case.
  8756. if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
  8757. return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
  8758. Redeclaration, OldDecl,
  8759. MergeTypeWithPrevious, Previous);
  8760. // At this point, we have a multiversion function decl (in OldFD) AND an
  8761. // appropriate attribute in the current function decl. Resolve that these are
  8762. // still compatible with previous declarations.
  8763. return CheckMultiVersionAdditionalDecl(
  8764. S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
  8765. OldDecl, MergeTypeWithPrevious, Previous);
  8766. }
  8767. /// Perform semantic checking of a new function declaration.
  8768. ///
  8769. /// Performs semantic analysis of the new function declaration
  8770. /// NewFD. This routine performs all semantic checking that does not
  8771. /// require the actual declarator involved in the declaration, and is
  8772. /// used both for the declaration of functions as they are parsed
  8773. /// (called via ActOnDeclarator) and for the declaration of functions
  8774. /// that have been instantiated via C++ template instantiation (called
  8775. /// via InstantiateDecl).
  8776. ///
  8777. /// \param IsMemberSpecialization whether this new function declaration is
  8778. /// a member specialization (that replaces any definition provided by the
  8779. /// previous declaration).
  8780. ///
  8781. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8782. ///
  8783. /// \returns true if the function declaration is a redeclaration.
  8784. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8785. LookupResult &Previous,
  8786. bool IsMemberSpecialization) {
  8787. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8788. "Variably modified return types are not handled here");
  8789. // Determine whether the type of this function should be merged with
  8790. // a previous visible declaration. This never happens for functions in C++,
  8791. // and always happens in C if the previous declaration was visible.
  8792. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8793. !Previous.isShadowed();
  8794. bool Redeclaration = false;
  8795. NamedDecl *OldDecl = nullptr;
  8796. bool MayNeedOverloadableChecks = false;
  8797. // Merge or overload the declaration with an existing declaration of
  8798. // the same name, if appropriate.
  8799. if (!Previous.empty()) {
  8800. // Determine whether NewFD is an overload of PrevDecl or
  8801. // a declaration that requires merging. If it's an overload,
  8802. // there's no more work to do here; we'll just add the new
  8803. // function to the scope.
  8804. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8805. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8806. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8807. Redeclaration = true;
  8808. OldDecl = Candidate;
  8809. }
  8810. } else {
  8811. MayNeedOverloadableChecks = true;
  8812. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8813. /*NewIsUsingDecl*/ false)) {
  8814. case Ovl_Match:
  8815. Redeclaration = true;
  8816. break;
  8817. case Ovl_NonFunction:
  8818. Redeclaration = true;
  8819. break;
  8820. case Ovl_Overload:
  8821. Redeclaration = false;
  8822. break;
  8823. }
  8824. }
  8825. }
  8826. // Check for a previous extern "C" declaration with this name.
  8827. if (!Redeclaration &&
  8828. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8829. if (!Previous.empty()) {
  8830. // This is an extern "C" declaration with the same name as a previous
  8831. // declaration, and thus redeclares that entity...
  8832. Redeclaration = true;
  8833. OldDecl = Previous.getFoundDecl();
  8834. MergeTypeWithPrevious = false;
  8835. // ... except in the presence of __attribute__((overloadable)).
  8836. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8837. NewFD->hasAttr<OverloadableAttr>()) {
  8838. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8839. MayNeedOverloadableChecks = true;
  8840. Redeclaration = false;
  8841. OldDecl = nullptr;
  8842. }
  8843. }
  8844. }
  8845. }
  8846. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8847. MergeTypeWithPrevious, Previous))
  8848. return Redeclaration;
  8849. // C++11 [dcl.constexpr]p8:
  8850. // A constexpr specifier for a non-static member function that is not
  8851. // a constructor declares that member function to be const.
  8852. //
  8853. // This needs to be delayed until we know whether this is an out-of-line
  8854. // definition of a static member function.
  8855. //
  8856. // This rule is not present in C++1y, so we produce a backwards
  8857. // compatibility warning whenever it happens in C++11.
  8858. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8859. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8860. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8861. !MD->getMethodQualifiers().hasConst()) {
  8862. CXXMethodDecl *OldMD = nullptr;
  8863. if (OldDecl)
  8864. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8865. if (!OldMD || !OldMD->isStatic()) {
  8866. const FunctionProtoType *FPT =
  8867. MD->getType()->castAs<FunctionProtoType>();
  8868. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8869. EPI.TypeQuals.addConst();
  8870. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8871. FPT->getParamTypes(), EPI));
  8872. // Warn that we did this, if we're not performing template instantiation.
  8873. // In that case, we'll have warned already when the template was defined.
  8874. if (!inTemplateInstantiation()) {
  8875. SourceLocation AddConstLoc;
  8876. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8877. .IgnoreParens().getAs<FunctionTypeLoc>())
  8878. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8879. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8880. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8881. }
  8882. }
  8883. }
  8884. if (Redeclaration) {
  8885. // NewFD and OldDecl represent declarations that need to be
  8886. // merged.
  8887. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8888. NewFD->setInvalidDecl();
  8889. return Redeclaration;
  8890. }
  8891. Previous.clear();
  8892. Previous.addDecl(OldDecl);
  8893. if (FunctionTemplateDecl *OldTemplateDecl =
  8894. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8895. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8896. FunctionTemplateDecl *NewTemplateDecl
  8897. = NewFD->getDescribedFunctionTemplate();
  8898. assert(NewTemplateDecl && "Template/non-template mismatch");
  8899. // The call to MergeFunctionDecl above may have created some state in
  8900. // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
  8901. // can add it as a redeclaration.
  8902. NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
  8903. NewFD->setPreviousDeclaration(OldFD);
  8904. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8905. if (NewFD->isCXXClassMember()) {
  8906. NewFD->setAccess(OldTemplateDecl->getAccess());
  8907. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8908. }
  8909. // If this is an explicit specialization of a member that is a function
  8910. // template, mark it as a member specialization.
  8911. if (IsMemberSpecialization &&
  8912. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8913. NewTemplateDecl->setMemberSpecialization();
  8914. assert(OldTemplateDecl->isMemberSpecialization());
  8915. // Explicit specializations of a member template do not inherit deleted
  8916. // status from the parent member template that they are specializing.
  8917. if (OldFD->isDeleted()) {
  8918. // FIXME: This assert will not hold in the presence of modules.
  8919. assert(OldFD->getCanonicalDecl() == OldFD);
  8920. // FIXME: We need an update record for this AST mutation.
  8921. OldFD->setDeletedAsWritten(false);
  8922. }
  8923. }
  8924. } else {
  8925. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8926. auto *OldFD = cast<FunctionDecl>(OldDecl);
  8927. // This needs to happen first so that 'inline' propagates.
  8928. NewFD->setPreviousDeclaration(OldFD);
  8929. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8930. if (NewFD->isCXXClassMember())
  8931. NewFD->setAccess(OldFD->getAccess());
  8932. }
  8933. }
  8934. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  8935. !NewFD->getAttr<OverloadableAttr>()) {
  8936. assert((Previous.empty() ||
  8937. llvm::any_of(Previous,
  8938. [](const NamedDecl *ND) {
  8939. return ND->hasAttr<OverloadableAttr>();
  8940. })) &&
  8941. "Non-redecls shouldn't happen without overloadable present");
  8942. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  8943. const auto *FD = dyn_cast<FunctionDecl>(ND);
  8944. return FD && !FD->hasAttr<OverloadableAttr>();
  8945. });
  8946. if (OtherUnmarkedIter != Previous.end()) {
  8947. Diag(NewFD->getLocation(),
  8948. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  8949. Diag((*OtherUnmarkedIter)->getLocation(),
  8950. diag::note_attribute_overloadable_prev_overload)
  8951. << false;
  8952. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  8953. }
  8954. }
  8955. // Semantic checking for this function declaration (in isolation).
  8956. if (getLangOpts().CPlusPlus) {
  8957. // C++-specific checks.
  8958. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8959. CheckConstructor(Constructor);
  8960. } else if (CXXDestructorDecl *Destructor =
  8961. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8962. CXXRecordDecl *Record = Destructor->getParent();
  8963. QualType ClassType = Context.getTypeDeclType(Record);
  8964. // FIXME: Shouldn't we be able to perform this check even when the class
  8965. // type is dependent? Both gcc and edg can handle that.
  8966. if (!ClassType->isDependentType()) {
  8967. DeclarationName Name
  8968. = Context.DeclarationNames.getCXXDestructorName(
  8969. Context.getCanonicalType(ClassType));
  8970. if (NewFD->getDeclName() != Name) {
  8971. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8972. NewFD->setInvalidDecl();
  8973. return Redeclaration;
  8974. }
  8975. }
  8976. } else if (CXXConversionDecl *Conversion
  8977. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8978. ActOnConversionDeclarator(Conversion);
  8979. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8980. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8981. CheckDeductionGuideTemplate(TD);
  8982. // A deduction guide is not on the list of entities that can be
  8983. // explicitly specialized.
  8984. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8985. Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
  8986. << /*explicit specialization*/ 1;
  8987. }
  8988. // Find any virtual functions that this function overrides.
  8989. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8990. if (!Method->isFunctionTemplateSpecialization() &&
  8991. !Method->getDescribedFunctionTemplate() &&
  8992. Method->isCanonicalDecl()) {
  8993. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8994. // If the function was marked as "static", we have a problem.
  8995. if (NewFD->getStorageClass() == SC_Static) {
  8996. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8997. }
  8998. }
  8999. }
  9000. if (Method->isStatic())
  9001. checkThisInStaticMemberFunctionType(Method);
  9002. }
  9003. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  9004. if (NewFD->isOverloadedOperator() &&
  9005. CheckOverloadedOperatorDeclaration(NewFD)) {
  9006. NewFD->setInvalidDecl();
  9007. return Redeclaration;
  9008. }
  9009. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  9010. if (NewFD->getLiteralIdentifier() &&
  9011. CheckLiteralOperatorDeclaration(NewFD)) {
  9012. NewFD->setInvalidDecl();
  9013. return Redeclaration;
  9014. }
  9015. // In C++, check default arguments now that we have merged decls. Unless
  9016. // the lexical context is the class, because in this case this is done
  9017. // during delayed parsing anyway.
  9018. if (!CurContext->isRecord())
  9019. CheckCXXDefaultArguments(NewFD);
  9020. // If this function declares a builtin function, check the type of this
  9021. // declaration against the expected type for the builtin.
  9022. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  9023. ASTContext::GetBuiltinTypeError Error;
  9024. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  9025. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  9026. // If the type of the builtin differs only in its exception
  9027. // specification, that's OK.
  9028. // FIXME: If the types do differ in this way, it would be better to
  9029. // retain the 'noexcept' form of the type.
  9030. if (!T.isNull() &&
  9031. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  9032. NewFD->getType()))
  9033. // The type of this function differs from the type of the builtin,
  9034. // so forget about the builtin entirely.
  9035. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  9036. }
  9037. // If this function is declared as being extern "C", then check to see if
  9038. // the function returns a UDT (class, struct, or union type) that is not C
  9039. // compatible, and if it does, warn the user.
  9040. // But, issue any diagnostic on the first declaration only.
  9041. if (Previous.empty() && NewFD->isExternC()) {
  9042. QualType R = NewFD->getReturnType();
  9043. if (R->isIncompleteType() && !R->isVoidType())
  9044. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  9045. << NewFD << R;
  9046. else if (!R.isPODType(Context) && !R->isVoidType() &&
  9047. !R->isObjCObjectPointerType())
  9048. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  9049. }
  9050. // C++1z [dcl.fct]p6:
  9051. // [...] whether the function has a non-throwing exception-specification
  9052. // [is] part of the function type
  9053. //
  9054. // This results in an ABI break between C++14 and C++17 for functions whose
  9055. // declared type includes an exception-specification in a parameter or
  9056. // return type. (Exception specifications on the function itself are OK in
  9057. // most cases, and exception specifications are not permitted in most other
  9058. // contexts where they could make it into a mangling.)
  9059. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  9060. auto HasNoexcept = [&](QualType T) -> bool {
  9061. // Strip off declarator chunks that could be between us and a function
  9062. // type. We don't need to look far, exception specifications are very
  9063. // restricted prior to C++17.
  9064. if (auto *RT = T->getAs<ReferenceType>())
  9065. T = RT->getPointeeType();
  9066. else if (T->isAnyPointerType())
  9067. T = T->getPointeeType();
  9068. else if (auto *MPT = T->getAs<MemberPointerType>())
  9069. T = MPT->getPointeeType();
  9070. if (auto *FPT = T->getAs<FunctionProtoType>())
  9071. if (FPT->isNothrow())
  9072. return true;
  9073. return false;
  9074. };
  9075. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  9076. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  9077. for (QualType T : FPT->param_types())
  9078. AnyNoexcept |= HasNoexcept(T);
  9079. if (AnyNoexcept)
  9080. Diag(NewFD->getLocation(),
  9081. diag::warn_cxx17_compat_exception_spec_in_signature)
  9082. << NewFD;
  9083. }
  9084. if (!Redeclaration && LangOpts.CUDA)
  9085. checkCUDATargetOverload(NewFD, Previous);
  9086. }
  9087. return Redeclaration;
  9088. }
  9089. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  9090. // C++11 [basic.start.main]p3:
  9091. // A program that [...] declares main to be inline, static or
  9092. // constexpr is ill-formed.
  9093. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  9094. // appear in a declaration of main.
  9095. // static main is not an error under C99, but we should warn about it.
  9096. // We accept _Noreturn main as an extension.
  9097. if (FD->getStorageClass() == SC_Static)
  9098. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  9099. ? diag::err_static_main : diag::warn_static_main)
  9100. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  9101. if (FD->isInlineSpecified())
  9102. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  9103. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  9104. if (DS.isNoreturnSpecified()) {
  9105. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  9106. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  9107. Diag(NoreturnLoc, diag::ext_noreturn_main);
  9108. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  9109. << FixItHint::CreateRemoval(NoreturnRange);
  9110. }
  9111. if (FD->isConstexpr()) {
  9112. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  9113. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  9114. FD->setConstexpr(false);
  9115. }
  9116. if (getLangOpts().OpenCL) {
  9117. Diag(FD->getLocation(), diag::err_opencl_no_main)
  9118. << FD->hasAttr<OpenCLKernelAttr>();
  9119. FD->setInvalidDecl();
  9120. return;
  9121. }
  9122. QualType T = FD->getType();
  9123. assert(T->isFunctionType() && "function decl is not of function type");
  9124. const FunctionType* FT = T->castAs<FunctionType>();
  9125. // Set default calling convention for main()
  9126. if (FT->getCallConv() != CC_C) {
  9127. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  9128. FD->setType(QualType(FT, 0));
  9129. T = Context.getCanonicalType(FD->getType());
  9130. }
  9131. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  9132. // In C with GNU extensions we allow main() to have non-integer return
  9133. // type, but we should warn about the extension, and we disable the
  9134. // implicit-return-zero rule.
  9135. // GCC in C mode accepts qualified 'int'.
  9136. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  9137. FD->setHasImplicitReturnZero(true);
  9138. else {
  9139. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  9140. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9141. if (RTRange.isValid())
  9142. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  9143. << FixItHint::CreateReplacement(RTRange, "int");
  9144. }
  9145. } else {
  9146. // In C and C++, main magically returns 0 if you fall off the end;
  9147. // set the flag which tells us that.
  9148. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  9149. // All the standards say that main() should return 'int'.
  9150. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  9151. FD->setHasImplicitReturnZero(true);
  9152. else {
  9153. // Otherwise, this is just a flat-out error.
  9154. SourceRange RTRange = FD->getReturnTypeSourceRange();
  9155. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  9156. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  9157. : FixItHint());
  9158. FD->setInvalidDecl(true);
  9159. }
  9160. }
  9161. // Treat protoless main() as nullary.
  9162. if (isa<FunctionNoProtoType>(FT)) return;
  9163. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  9164. unsigned nparams = FTP->getNumParams();
  9165. assert(FD->getNumParams() == nparams);
  9166. bool HasExtraParameters = (nparams > 3);
  9167. if (FTP->isVariadic()) {
  9168. Diag(FD->getLocation(), diag::ext_variadic_main);
  9169. // FIXME: if we had information about the location of the ellipsis, we
  9170. // could add a FixIt hint to remove it as a parameter.
  9171. }
  9172. // Darwin passes an undocumented fourth argument of type char**. If
  9173. // other platforms start sprouting these, the logic below will start
  9174. // getting shifty.
  9175. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  9176. HasExtraParameters = false;
  9177. if (HasExtraParameters) {
  9178. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  9179. FD->setInvalidDecl(true);
  9180. nparams = 3;
  9181. }
  9182. // FIXME: a lot of the following diagnostics would be improved
  9183. // if we had some location information about types.
  9184. QualType CharPP =
  9185. Context.getPointerType(Context.getPointerType(Context.CharTy));
  9186. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  9187. for (unsigned i = 0; i < nparams; ++i) {
  9188. QualType AT = FTP->getParamType(i);
  9189. bool mismatch = true;
  9190. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  9191. mismatch = false;
  9192. else if (Expected[i] == CharPP) {
  9193. // As an extension, the following forms are okay:
  9194. // char const **
  9195. // char const * const *
  9196. // char * const *
  9197. QualifierCollector qs;
  9198. const PointerType* PT;
  9199. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  9200. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  9201. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  9202. Context.CharTy)) {
  9203. qs.removeConst();
  9204. mismatch = !qs.empty();
  9205. }
  9206. }
  9207. if (mismatch) {
  9208. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  9209. // TODO: suggest replacing given type with expected type
  9210. FD->setInvalidDecl(true);
  9211. }
  9212. }
  9213. if (nparams == 1 && !FD->isInvalidDecl()) {
  9214. Diag(FD->getLocation(), diag::warn_main_one_arg);
  9215. }
  9216. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9217. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9218. FD->setInvalidDecl();
  9219. }
  9220. }
  9221. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  9222. QualType T = FD->getType();
  9223. assert(T->isFunctionType() && "function decl is not of function type");
  9224. const FunctionType *FT = T->castAs<FunctionType>();
  9225. // Set an implicit return of 'zero' if the function can return some integral,
  9226. // enumeration, pointer or nullptr type.
  9227. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  9228. FT->getReturnType()->isAnyPointerType() ||
  9229. FT->getReturnType()->isNullPtrType())
  9230. // DllMain is exempt because a return value of zero means it failed.
  9231. if (FD->getName() != "DllMain")
  9232. FD->setHasImplicitReturnZero(true);
  9233. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  9234. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  9235. FD->setInvalidDecl();
  9236. }
  9237. }
  9238. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  9239. // FIXME: Need strict checking. In C89, we need to check for
  9240. // any assignment, increment, decrement, function-calls, or
  9241. // commas outside of a sizeof. In C99, it's the same list,
  9242. // except that the aforementioned are allowed in unevaluated
  9243. // expressions. Everything else falls under the
  9244. // "may accept other forms of constant expressions" exception.
  9245. // (We never end up here for C++, so the constant expression
  9246. // rules there don't matter.)
  9247. const Expr *Culprit;
  9248. if (Init->isConstantInitializer(Context, false, &Culprit))
  9249. return false;
  9250. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  9251. << Culprit->getSourceRange();
  9252. return true;
  9253. }
  9254. namespace {
  9255. // Visits an initialization expression to see if OrigDecl is evaluated in
  9256. // its own initialization and throws a warning if it does.
  9257. class SelfReferenceChecker
  9258. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  9259. Sema &S;
  9260. Decl *OrigDecl;
  9261. bool isRecordType;
  9262. bool isPODType;
  9263. bool isReferenceType;
  9264. bool isInitList;
  9265. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  9266. public:
  9267. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  9268. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  9269. S(S), OrigDecl(OrigDecl) {
  9270. isPODType = false;
  9271. isRecordType = false;
  9272. isReferenceType = false;
  9273. isInitList = false;
  9274. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  9275. isPODType = VD->getType().isPODType(S.Context);
  9276. isRecordType = VD->getType()->isRecordType();
  9277. isReferenceType = VD->getType()->isReferenceType();
  9278. }
  9279. }
  9280. // For most expressions, just call the visitor. For initializer lists,
  9281. // track the index of the field being initialized since fields are
  9282. // initialized in order allowing use of previously initialized fields.
  9283. void CheckExpr(Expr *E) {
  9284. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  9285. if (!InitList) {
  9286. Visit(E);
  9287. return;
  9288. }
  9289. // Track and increment the index here.
  9290. isInitList = true;
  9291. InitFieldIndex.push_back(0);
  9292. for (auto Child : InitList->children()) {
  9293. CheckExpr(cast<Expr>(Child));
  9294. ++InitFieldIndex.back();
  9295. }
  9296. InitFieldIndex.pop_back();
  9297. }
  9298. // Returns true if MemberExpr is checked and no further checking is needed.
  9299. // Returns false if additional checking is required.
  9300. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  9301. llvm::SmallVector<FieldDecl*, 4> Fields;
  9302. Expr *Base = E;
  9303. bool ReferenceField = false;
  9304. // Get the field members used.
  9305. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9306. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  9307. if (!FD)
  9308. return false;
  9309. Fields.push_back(FD);
  9310. if (FD->getType()->isReferenceType())
  9311. ReferenceField = true;
  9312. Base = ME->getBase()->IgnoreParenImpCasts();
  9313. }
  9314. // Keep checking only if the base Decl is the same.
  9315. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  9316. if (!DRE || DRE->getDecl() != OrigDecl)
  9317. return false;
  9318. // A reference field can be bound to an unininitialized field.
  9319. if (CheckReference && !ReferenceField)
  9320. return true;
  9321. // Convert FieldDecls to their index number.
  9322. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  9323. for (const FieldDecl *I : llvm::reverse(Fields))
  9324. UsedFieldIndex.push_back(I->getFieldIndex());
  9325. // See if a warning is needed by checking the first difference in index
  9326. // numbers. If field being used has index less than the field being
  9327. // initialized, then the use is safe.
  9328. for (auto UsedIter = UsedFieldIndex.begin(),
  9329. UsedEnd = UsedFieldIndex.end(),
  9330. OrigIter = InitFieldIndex.begin(),
  9331. OrigEnd = InitFieldIndex.end();
  9332. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  9333. if (*UsedIter < *OrigIter)
  9334. return true;
  9335. if (*UsedIter > *OrigIter)
  9336. break;
  9337. }
  9338. // TODO: Add a different warning which will print the field names.
  9339. HandleDeclRefExpr(DRE);
  9340. return true;
  9341. }
  9342. // For most expressions, the cast is directly above the DeclRefExpr.
  9343. // For conditional operators, the cast can be outside the conditional
  9344. // operator if both expressions are DeclRefExpr's.
  9345. void HandleValue(Expr *E) {
  9346. E = E->IgnoreParens();
  9347. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  9348. HandleDeclRefExpr(DRE);
  9349. return;
  9350. }
  9351. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9352. Visit(CO->getCond());
  9353. HandleValue(CO->getTrueExpr());
  9354. HandleValue(CO->getFalseExpr());
  9355. return;
  9356. }
  9357. if (BinaryConditionalOperator *BCO =
  9358. dyn_cast<BinaryConditionalOperator>(E)) {
  9359. Visit(BCO->getCond());
  9360. HandleValue(BCO->getFalseExpr());
  9361. return;
  9362. }
  9363. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9364. HandleValue(OVE->getSourceExpr());
  9365. return;
  9366. }
  9367. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9368. if (BO->getOpcode() == BO_Comma) {
  9369. Visit(BO->getLHS());
  9370. HandleValue(BO->getRHS());
  9371. return;
  9372. }
  9373. }
  9374. if (isa<MemberExpr>(E)) {
  9375. if (isInitList) {
  9376. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9377. false /*CheckReference*/))
  9378. return;
  9379. }
  9380. Expr *Base = E->IgnoreParenImpCasts();
  9381. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9382. // Check for static member variables and don't warn on them.
  9383. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9384. return;
  9385. Base = ME->getBase()->IgnoreParenImpCasts();
  9386. }
  9387. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9388. HandleDeclRefExpr(DRE);
  9389. return;
  9390. }
  9391. Visit(E);
  9392. }
  9393. // Reference types not handled in HandleValue are handled here since all
  9394. // uses of references are bad, not just r-value uses.
  9395. void VisitDeclRefExpr(DeclRefExpr *E) {
  9396. if (isReferenceType)
  9397. HandleDeclRefExpr(E);
  9398. }
  9399. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9400. if (E->getCastKind() == CK_LValueToRValue) {
  9401. HandleValue(E->getSubExpr());
  9402. return;
  9403. }
  9404. Inherited::VisitImplicitCastExpr(E);
  9405. }
  9406. void VisitMemberExpr(MemberExpr *E) {
  9407. if (isInitList) {
  9408. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9409. return;
  9410. }
  9411. // Don't warn on arrays since they can be treated as pointers.
  9412. if (E->getType()->canDecayToPointerType()) return;
  9413. // Warn when a non-static method call is followed by non-static member
  9414. // field accesses, which is followed by a DeclRefExpr.
  9415. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9416. bool Warn = (MD && !MD->isStatic());
  9417. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9418. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9419. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9420. Warn = false;
  9421. Base = ME->getBase()->IgnoreParenImpCasts();
  9422. }
  9423. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9424. if (Warn)
  9425. HandleDeclRefExpr(DRE);
  9426. return;
  9427. }
  9428. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9429. // Visit that expression.
  9430. Visit(Base);
  9431. }
  9432. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9433. Expr *Callee = E->getCallee();
  9434. if (isa<UnresolvedLookupExpr>(Callee))
  9435. return Inherited::VisitCXXOperatorCallExpr(E);
  9436. Visit(Callee);
  9437. for (auto Arg: E->arguments())
  9438. HandleValue(Arg->IgnoreParenImpCasts());
  9439. }
  9440. void VisitUnaryOperator(UnaryOperator *E) {
  9441. // For POD record types, addresses of its own members are well-defined.
  9442. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9443. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9444. if (!isPODType)
  9445. HandleValue(E->getSubExpr());
  9446. return;
  9447. }
  9448. if (E->isIncrementDecrementOp()) {
  9449. HandleValue(E->getSubExpr());
  9450. return;
  9451. }
  9452. Inherited::VisitUnaryOperator(E);
  9453. }
  9454. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9455. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9456. if (E->getConstructor()->isCopyConstructor()) {
  9457. Expr *ArgExpr = E->getArg(0);
  9458. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9459. if (ILE->getNumInits() == 1)
  9460. ArgExpr = ILE->getInit(0);
  9461. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9462. if (ICE->getCastKind() == CK_NoOp)
  9463. ArgExpr = ICE->getSubExpr();
  9464. HandleValue(ArgExpr);
  9465. return;
  9466. }
  9467. Inherited::VisitCXXConstructExpr(E);
  9468. }
  9469. void VisitCallExpr(CallExpr *E) {
  9470. // Treat std::move as a use.
  9471. if (E->isCallToStdMove()) {
  9472. HandleValue(E->getArg(0));
  9473. return;
  9474. }
  9475. Inherited::VisitCallExpr(E);
  9476. }
  9477. void VisitBinaryOperator(BinaryOperator *E) {
  9478. if (E->isCompoundAssignmentOp()) {
  9479. HandleValue(E->getLHS());
  9480. Visit(E->getRHS());
  9481. return;
  9482. }
  9483. Inherited::VisitBinaryOperator(E);
  9484. }
  9485. // A custom visitor for BinaryConditionalOperator is needed because the
  9486. // regular visitor would check the condition and true expression separately
  9487. // but both point to the same place giving duplicate diagnostics.
  9488. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9489. Visit(E->getCond());
  9490. Visit(E->getFalseExpr());
  9491. }
  9492. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9493. Decl* ReferenceDecl = DRE->getDecl();
  9494. if (OrigDecl != ReferenceDecl) return;
  9495. unsigned diag;
  9496. if (isReferenceType) {
  9497. diag = diag::warn_uninit_self_reference_in_reference_init;
  9498. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9499. diag = diag::warn_static_self_reference_in_init;
  9500. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9501. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9502. DRE->getDecl()->getType()->isRecordType()) {
  9503. diag = diag::warn_uninit_self_reference_in_init;
  9504. } else {
  9505. // Local variables will be handled by the CFG analysis.
  9506. return;
  9507. }
  9508. S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
  9509. S.PDiag(diag)
  9510. << DRE->getDecl() << OrigDecl->getLocation()
  9511. << DRE->getSourceRange());
  9512. }
  9513. };
  9514. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9515. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9516. bool DirectInit) {
  9517. // Parameters arguments are occassionially constructed with itself,
  9518. // for instance, in recursive functions. Skip them.
  9519. if (isa<ParmVarDecl>(OrigDecl))
  9520. return;
  9521. E = E->IgnoreParens();
  9522. // Skip checking T a = a where T is not a record or reference type.
  9523. // Doing so is a way to silence uninitialized warnings.
  9524. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9525. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9526. if (ICE->getCastKind() == CK_LValueToRValue)
  9527. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9528. if (DRE->getDecl() == OrigDecl)
  9529. return;
  9530. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9531. }
  9532. } // end anonymous namespace
  9533. namespace {
  9534. // Simple wrapper to add the name of a variable or (if no variable is
  9535. // available) a DeclarationName into a diagnostic.
  9536. struct VarDeclOrName {
  9537. VarDecl *VDecl;
  9538. DeclarationName Name;
  9539. friend const Sema::SemaDiagnosticBuilder &
  9540. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9541. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9542. }
  9543. };
  9544. } // end anonymous namespace
  9545. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9546. DeclarationName Name, QualType Type,
  9547. TypeSourceInfo *TSI,
  9548. SourceRange Range, bool DirectInit,
  9549. Expr *&Init) {
  9550. bool IsInitCapture = !VDecl;
  9551. assert((!VDecl || !VDecl->isInitCapture()) &&
  9552. "init captures are expected to be deduced prior to initialization");
  9553. VarDeclOrName VN{VDecl, Name};
  9554. DeducedType *Deduced = Type->getContainedDeducedType();
  9555. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9556. // C++11 [dcl.spec.auto]p3
  9557. if (!Init) {
  9558. assert(VDecl && "no init for init capture deduction?");
  9559. // Except for class argument deduction, and then for an initializing
  9560. // declaration only, i.e. no static at class scope or extern.
  9561. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9562. VDecl->hasExternalStorage() ||
  9563. VDecl->isStaticDataMember()) {
  9564. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9565. << VDecl->getDeclName() << Type;
  9566. return QualType();
  9567. }
  9568. }
  9569. ArrayRef<Expr*> DeduceInits;
  9570. if (Init)
  9571. DeduceInits = Init;
  9572. if (DirectInit) {
  9573. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9574. DeduceInits = PL->exprs();
  9575. }
  9576. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9577. assert(VDecl && "non-auto type for init capture deduction?");
  9578. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9579. InitializationKind Kind = InitializationKind::CreateForInit(
  9580. VDecl->getLocation(), DirectInit, Init);
  9581. // FIXME: Initialization should not be taking a mutable list of inits.
  9582. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9583. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9584. InitsCopy);
  9585. }
  9586. if (DirectInit) {
  9587. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9588. DeduceInits = IL->inits();
  9589. }
  9590. // Deduction only works if we have exactly one source expression.
  9591. if (DeduceInits.empty()) {
  9592. // It isn't possible to write this directly, but it is possible to
  9593. // end up in this situation with "auto x(some_pack...);"
  9594. Diag(Init->getBeginLoc(), IsInitCapture
  9595. ? diag::err_init_capture_no_expression
  9596. : diag::err_auto_var_init_no_expression)
  9597. << VN << Type << Range;
  9598. return QualType();
  9599. }
  9600. if (DeduceInits.size() > 1) {
  9601. Diag(DeduceInits[1]->getBeginLoc(),
  9602. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9603. : diag::err_auto_var_init_multiple_expressions)
  9604. << VN << Type << Range;
  9605. return QualType();
  9606. }
  9607. Expr *DeduceInit = DeduceInits[0];
  9608. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9609. Diag(Init->getBeginLoc(), IsInitCapture
  9610. ? diag::err_init_capture_paren_braces
  9611. : diag::err_auto_var_init_paren_braces)
  9612. << isa<InitListExpr>(Init) << VN << Type << Range;
  9613. return QualType();
  9614. }
  9615. // Expressions default to 'id' when we're in a debugger.
  9616. bool DefaultedAnyToId = false;
  9617. if (getLangOpts().DebuggerCastResultToId &&
  9618. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9619. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9620. if (Result.isInvalid()) {
  9621. return QualType();
  9622. }
  9623. Init = Result.get();
  9624. DefaultedAnyToId = true;
  9625. }
  9626. // C++ [dcl.decomp]p1:
  9627. // If the assignment-expression [...] has array type A and no ref-qualifier
  9628. // is present, e has type cv A
  9629. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9630. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9631. DeduceInit->getType()->isConstantArrayType())
  9632. return Context.getQualifiedType(DeduceInit->getType(),
  9633. Type.getQualifiers());
  9634. QualType DeducedType;
  9635. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9636. if (!IsInitCapture)
  9637. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9638. else if (isa<InitListExpr>(Init))
  9639. Diag(Range.getBegin(),
  9640. diag::err_init_capture_deduction_failure_from_init_list)
  9641. << VN
  9642. << (DeduceInit->getType().isNull() ? TSI->getType()
  9643. : DeduceInit->getType())
  9644. << DeduceInit->getSourceRange();
  9645. else
  9646. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9647. << VN << TSI->getType()
  9648. << (DeduceInit->getType().isNull() ? TSI->getType()
  9649. : DeduceInit->getType())
  9650. << DeduceInit->getSourceRange();
  9651. } else
  9652. Init = DeduceInit;
  9653. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9654. // 'id' instead of a specific object type prevents most of our usual
  9655. // checks.
  9656. // We only want to warn outside of template instantiations, though:
  9657. // inside a template, the 'id' could have come from a parameter.
  9658. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9659. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9660. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9661. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9662. }
  9663. return DeducedType;
  9664. }
  9665. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9666. Expr *&Init) {
  9667. QualType DeducedType = deduceVarTypeFromInitializer(
  9668. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9669. VDecl->getSourceRange(), DirectInit, Init);
  9670. if (DeducedType.isNull()) {
  9671. VDecl->setInvalidDecl();
  9672. return true;
  9673. }
  9674. VDecl->setType(DeducedType);
  9675. assert(VDecl->isLinkageValid());
  9676. // In ARC, infer lifetime.
  9677. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9678. VDecl->setInvalidDecl();
  9679. // If this is a redeclaration, check that the type we just deduced matches
  9680. // the previously declared type.
  9681. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9682. // We never need to merge the type, because we cannot form an incomplete
  9683. // array of auto, nor deduce such a type.
  9684. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9685. }
  9686. // Check the deduced type is valid for a variable declaration.
  9687. CheckVariableDeclarationType(VDecl);
  9688. return VDecl->isInvalidDecl();
  9689. }
  9690. /// AddInitializerToDecl - Adds the initializer Init to the
  9691. /// declaration dcl. If DirectInit is true, this is C++ direct
  9692. /// initialization rather than copy initialization.
  9693. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9694. // If there is no declaration, there was an error parsing it. Just ignore
  9695. // the initializer.
  9696. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9697. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9698. return;
  9699. }
  9700. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9701. // Pure-specifiers are handled in ActOnPureSpecifier.
  9702. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9703. << Method->getDeclName() << Init->getSourceRange();
  9704. Method->setInvalidDecl();
  9705. return;
  9706. }
  9707. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9708. if (!VDecl) {
  9709. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9710. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9711. RealDecl->setInvalidDecl();
  9712. return;
  9713. }
  9714. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9715. if (VDecl->getType()->isUndeducedType()) {
  9716. // Attempt typo correction early so that the type of the init expression can
  9717. // be deduced based on the chosen correction if the original init contains a
  9718. // TypoExpr.
  9719. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9720. if (!Res.isUsable()) {
  9721. RealDecl->setInvalidDecl();
  9722. return;
  9723. }
  9724. Init = Res.get();
  9725. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9726. return;
  9727. }
  9728. // dllimport cannot be used on variable definitions.
  9729. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9730. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9731. VDecl->setInvalidDecl();
  9732. return;
  9733. }
  9734. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9735. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9736. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9737. VDecl->setInvalidDecl();
  9738. return;
  9739. }
  9740. if (!VDecl->getType()->isDependentType()) {
  9741. // A definition must end up with a complete type, which means it must be
  9742. // complete with the restriction that an array type might be completed by
  9743. // the initializer; note that later code assumes this restriction.
  9744. QualType BaseDeclType = VDecl->getType();
  9745. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9746. BaseDeclType = Array->getElementType();
  9747. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9748. diag::err_typecheck_decl_incomplete_type)) {
  9749. RealDecl->setInvalidDecl();
  9750. return;
  9751. }
  9752. // The variable can not have an abstract class type.
  9753. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9754. diag::err_abstract_type_in_decl,
  9755. AbstractVariableType))
  9756. VDecl->setInvalidDecl();
  9757. }
  9758. // If adding the initializer will turn this declaration into a definition,
  9759. // and we already have a definition for this variable, diagnose or otherwise
  9760. // handle the situation.
  9761. VarDecl *Def;
  9762. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9763. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9764. !VDecl->isThisDeclarationADemotedDefinition() &&
  9765. checkVarDeclRedefinition(Def, VDecl))
  9766. return;
  9767. if (getLangOpts().CPlusPlus) {
  9768. // C++ [class.static.data]p4
  9769. // If a static data member is of const integral or const
  9770. // enumeration type, its declaration in the class definition can
  9771. // specify a constant-initializer which shall be an integral
  9772. // constant expression (5.19). In that case, the member can appear
  9773. // in integral constant expressions. The member shall still be
  9774. // defined in a namespace scope if it is used in the program and the
  9775. // namespace scope definition shall not contain an initializer.
  9776. //
  9777. // We already performed a redefinition check above, but for static
  9778. // data members we also need to check whether there was an in-class
  9779. // declaration with an initializer.
  9780. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9781. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9782. << VDecl->getDeclName();
  9783. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9784. diag::note_previous_initializer)
  9785. << 0;
  9786. return;
  9787. }
  9788. if (VDecl->hasLocalStorage())
  9789. setFunctionHasBranchProtectedScope();
  9790. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9791. VDecl->setInvalidDecl();
  9792. return;
  9793. }
  9794. }
  9795. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9796. // a kernel function cannot be initialized."
  9797. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9798. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9799. VDecl->setInvalidDecl();
  9800. return;
  9801. }
  9802. // Get the decls type and save a reference for later, since
  9803. // CheckInitializerTypes may change it.
  9804. QualType DclT = VDecl->getType(), SavT = DclT;
  9805. // Expressions default to 'id' when we're in a debugger
  9806. // and we are assigning it to a variable of Objective-C pointer type.
  9807. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9808. Init->getType() == Context.UnknownAnyTy) {
  9809. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9810. if (Result.isInvalid()) {
  9811. VDecl->setInvalidDecl();
  9812. return;
  9813. }
  9814. Init = Result.get();
  9815. }
  9816. // Perform the initialization.
  9817. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9818. if (!VDecl->isInvalidDecl()) {
  9819. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9820. InitializationKind Kind = InitializationKind::CreateForInit(
  9821. VDecl->getLocation(), DirectInit, Init);
  9822. MultiExprArg Args = Init;
  9823. if (CXXDirectInit)
  9824. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9825. CXXDirectInit->getNumExprs());
  9826. // Try to correct any TypoExprs in the initialization arguments.
  9827. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9828. ExprResult Res = CorrectDelayedTyposInExpr(
  9829. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9830. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9831. return Init.Failed() ? ExprError() : E;
  9832. });
  9833. if (Res.isInvalid()) {
  9834. VDecl->setInvalidDecl();
  9835. } else if (Res.get() != Args[Idx]) {
  9836. Args[Idx] = Res.get();
  9837. }
  9838. }
  9839. if (VDecl->isInvalidDecl())
  9840. return;
  9841. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9842. /*TopLevelOfInitList=*/false,
  9843. /*TreatUnavailableAsInvalid=*/false);
  9844. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9845. if (Result.isInvalid()) {
  9846. VDecl->setInvalidDecl();
  9847. return;
  9848. }
  9849. Init = Result.getAs<Expr>();
  9850. }
  9851. // Check for self-references within variable initializers.
  9852. // Variables declared within a function/method body (except for references)
  9853. // are handled by a dataflow analysis.
  9854. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9855. VDecl->getType()->isReferenceType()) {
  9856. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9857. }
  9858. // If the type changed, it means we had an incomplete type that was
  9859. // completed by the initializer. For example:
  9860. // int ary[] = { 1, 3, 5 };
  9861. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9862. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9863. VDecl->setType(DclT);
  9864. if (!VDecl->isInvalidDecl()) {
  9865. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9866. if (VDecl->hasAttr<BlocksAttr>())
  9867. checkRetainCycles(VDecl, Init);
  9868. // It is safe to assign a weak reference into a strong variable.
  9869. // Although this code can still have problems:
  9870. // id x = self.weakProp;
  9871. // id y = self.weakProp;
  9872. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9873. // paths through the function. This should be revisited if
  9874. // -Wrepeated-use-of-weak is made flow-sensitive.
  9875. if (FunctionScopeInfo *FSI = getCurFunction())
  9876. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9877. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9878. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9879. Init->getBeginLoc()))
  9880. FSI->markSafeWeakUse(Init);
  9881. }
  9882. // The initialization is usually a full-expression.
  9883. //
  9884. // FIXME: If this is a braced initialization of an aggregate, it is not
  9885. // an expression, and each individual field initializer is a separate
  9886. // full-expression. For instance, in:
  9887. //
  9888. // struct Temp { ~Temp(); };
  9889. // struct S { S(Temp); };
  9890. // struct T { S a, b; } t = { Temp(), Temp() }
  9891. //
  9892. // we should destroy the first Temp before constructing the second.
  9893. ExprResult Result =
  9894. ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9895. /*DiscardedValue*/ false, VDecl->isConstexpr());
  9896. if (Result.isInvalid()) {
  9897. VDecl->setInvalidDecl();
  9898. return;
  9899. }
  9900. Init = Result.get();
  9901. // Attach the initializer to the decl.
  9902. VDecl->setInit(Init);
  9903. if (VDecl->isLocalVarDecl()) {
  9904. // Don't check the initializer if the declaration is malformed.
  9905. if (VDecl->isInvalidDecl()) {
  9906. // do nothing
  9907. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9908. // This is true even in OpenCL C++.
  9909. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9910. CheckForConstantInitializer(Init, DclT);
  9911. // Otherwise, C++ does not restrict the initializer.
  9912. } else if (getLangOpts().CPlusPlus) {
  9913. // do nothing
  9914. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9915. // static storage duration shall be constant expressions or string literals.
  9916. } else if (VDecl->getStorageClass() == SC_Static) {
  9917. CheckForConstantInitializer(Init, DclT);
  9918. // C89 is stricter than C99 for aggregate initializers.
  9919. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9920. // for an object that has aggregate or union type shall be
  9921. // constant expressions.
  9922. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9923. isa<InitListExpr>(Init)) {
  9924. const Expr *Culprit;
  9925. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9926. Diag(Culprit->getExprLoc(),
  9927. diag::ext_aggregate_init_not_constant)
  9928. << Culprit->getSourceRange();
  9929. }
  9930. }
  9931. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9932. VDecl->getLexicalDeclContext()->isRecord()) {
  9933. // This is an in-class initialization for a static data member, e.g.,
  9934. //
  9935. // struct S {
  9936. // static const int value = 17;
  9937. // };
  9938. // C++ [class.mem]p4:
  9939. // A member-declarator can contain a constant-initializer only
  9940. // if it declares a static member (9.4) of const integral or
  9941. // const enumeration type, see 9.4.2.
  9942. //
  9943. // C++11 [class.static.data]p3:
  9944. // If a non-volatile non-inline const static data member is of integral
  9945. // or enumeration type, its declaration in the class definition can
  9946. // specify a brace-or-equal-initializer in which every initializer-clause
  9947. // that is an assignment-expression is a constant expression. A static
  9948. // data member of literal type can be declared in the class definition
  9949. // with the constexpr specifier; if so, its declaration shall specify a
  9950. // brace-or-equal-initializer in which every initializer-clause that is
  9951. // an assignment-expression is a constant expression.
  9952. // Do nothing on dependent types.
  9953. if (DclT->isDependentType()) {
  9954. // Allow any 'static constexpr' members, whether or not they are of literal
  9955. // type. We separately check that every constexpr variable is of literal
  9956. // type.
  9957. } else if (VDecl->isConstexpr()) {
  9958. // Require constness.
  9959. } else if (!DclT.isConstQualified()) {
  9960. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9961. << Init->getSourceRange();
  9962. VDecl->setInvalidDecl();
  9963. // We allow integer constant expressions in all cases.
  9964. } else if (DclT->isIntegralOrEnumerationType()) {
  9965. // Check whether the expression is a constant expression.
  9966. SourceLocation Loc;
  9967. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9968. // In C++11, a non-constexpr const static data member with an
  9969. // in-class initializer cannot be volatile.
  9970. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9971. else if (Init->isValueDependent())
  9972. ; // Nothing to check.
  9973. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9974. ; // Ok, it's an ICE!
  9975. else if (Init->getType()->isScopedEnumeralType() &&
  9976. Init->isCXX11ConstantExpr(Context))
  9977. ; // Ok, it is a scoped-enum constant expression.
  9978. else if (Init->isEvaluatable(Context)) {
  9979. // If we can constant fold the initializer through heroics, accept it,
  9980. // but report this as a use of an extension for -pedantic.
  9981. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9982. << Init->getSourceRange();
  9983. } else {
  9984. // Otherwise, this is some crazy unknown case. Report the issue at the
  9985. // location provided by the isIntegerConstantExpr failed check.
  9986. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9987. << Init->getSourceRange();
  9988. VDecl->setInvalidDecl();
  9989. }
  9990. // We allow foldable floating-point constants as an extension.
  9991. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9992. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9993. // it anyway and provide a fixit to add the 'constexpr'.
  9994. if (getLangOpts().CPlusPlus11) {
  9995. Diag(VDecl->getLocation(),
  9996. diag::ext_in_class_initializer_float_type_cxx11)
  9997. << DclT << Init->getSourceRange();
  9998. Diag(VDecl->getBeginLoc(),
  9999. diag::note_in_class_initializer_float_type_cxx11)
  10000. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10001. } else {
  10002. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  10003. << DclT << Init->getSourceRange();
  10004. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  10005. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  10006. << Init->getSourceRange();
  10007. VDecl->setInvalidDecl();
  10008. }
  10009. }
  10010. // Suggest adding 'constexpr' in C++11 for literal types.
  10011. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  10012. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  10013. << DclT << Init->getSourceRange()
  10014. << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
  10015. VDecl->setConstexpr(true);
  10016. } else {
  10017. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  10018. << DclT << Init->getSourceRange();
  10019. VDecl->setInvalidDecl();
  10020. }
  10021. } else if (VDecl->isFileVarDecl()) {
  10022. // In C, extern is typically used to avoid tentative definitions when
  10023. // declaring variables in headers, but adding an intializer makes it a
  10024. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  10025. // In C++, extern is often used to give implictly static const variables
  10026. // external linkage, so don't warn in that case. If selectany is present,
  10027. // this might be header code intended for C and C++ inclusion, so apply the
  10028. // C++ rules.
  10029. if (VDecl->getStorageClass() == SC_Extern &&
  10030. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  10031. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  10032. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  10033. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  10034. Diag(VDecl->getLocation(), diag::warn_extern_init);
  10035. // C99 6.7.8p4. All file scoped initializers need to be constant.
  10036. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  10037. CheckForConstantInitializer(Init, DclT);
  10038. }
  10039. // We will represent direct-initialization similarly to copy-initialization:
  10040. // int x(1); -as-> int x = 1;
  10041. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  10042. //
  10043. // Clients that want to distinguish between the two forms, can check for
  10044. // direct initializer using VarDecl::getInitStyle().
  10045. // A major benefit is that clients that don't particularly care about which
  10046. // exactly form was it (like the CodeGen) can handle both cases without
  10047. // special case code.
  10048. // C++ 8.5p11:
  10049. // The form of initialization (using parentheses or '=') is generally
  10050. // insignificant, but does matter when the entity being initialized has a
  10051. // class type.
  10052. if (CXXDirectInit) {
  10053. assert(DirectInit && "Call-style initializer must be direct init.");
  10054. VDecl->setInitStyle(VarDecl::CallInit);
  10055. } else if (DirectInit) {
  10056. // This must be list-initialization. No other way is direct-initialization.
  10057. VDecl->setInitStyle(VarDecl::ListInit);
  10058. }
  10059. CheckCompleteVariableDeclaration(VDecl);
  10060. }
  10061. /// ActOnInitializerError - Given that there was an error parsing an
  10062. /// initializer for the given declaration, try to return to some form
  10063. /// of sanity.
  10064. void Sema::ActOnInitializerError(Decl *D) {
  10065. // Our main concern here is re-establishing invariants like "a
  10066. // variable's type is either dependent or complete".
  10067. if (!D || D->isInvalidDecl()) return;
  10068. VarDecl *VD = dyn_cast<VarDecl>(D);
  10069. if (!VD) return;
  10070. // Bindings are not usable if we can't make sense of the initializer.
  10071. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  10072. for (auto *BD : DD->bindings())
  10073. BD->setInvalidDecl();
  10074. // Auto types are meaningless if we can't make sense of the initializer.
  10075. if (ParsingInitForAutoVars.count(D)) {
  10076. D->setInvalidDecl();
  10077. return;
  10078. }
  10079. QualType Ty = VD->getType();
  10080. if (Ty->isDependentType()) return;
  10081. // Require a complete type.
  10082. if (RequireCompleteType(VD->getLocation(),
  10083. Context.getBaseElementType(Ty),
  10084. diag::err_typecheck_decl_incomplete_type)) {
  10085. VD->setInvalidDecl();
  10086. return;
  10087. }
  10088. // Require a non-abstract type.
  10089. if (RequireNonAbstractType(VD->getLocation(), Ty,
  10090. diag::err_abstract_type_in_decl,
  10091. AbstractVariableType)) {
  10092. VD->setInvalidDecl();
  10093. return;
  10094. }
  10095. // Don't bother complaining about constructors or destructors,
  10096. // though.
  10097. }
  10098. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  10099. // If there is no declaration, there was an error parsing it. Just ignore it.
  10100. if (!RealDecl)
  10101. return;
  10102. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  10103. QualType Type = Var->getType();
  10104. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  10105. if (isa<DecompositionDecl>(RealDecl)) {
  10106. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  10107. Var->setInvalidDecl();
  10108. return;
  10109. }
  10110. Expr *TmpInit = nullptr;
  10111. if (Type->isUndeducedType() &&
  10112. DeduceVariableDeclarationType(Var, false, TmpInit))
  10113. return;
  10114. // C++11 [class.static.data]p3: A static data member can be declared with
  10115. // the constexpr specifier; if so, its declaration shall specify
  10116. // a brace-or-equal-initializer.
  10117. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  10118. // the definition of a variable [...] or the declaration of a static data
  10119. // member.
  10120. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  10121. !Var->isThisDeclarationADemotedDefinition()) {
  10122. if (Var->isStaticDataMember()) {
  10123. // C++1z removes the relevant rule; the in-class declaration is always
  10124. // a definition there.
  10125. if (!getLangOpts().CPlusPlus17) {
  10126. Diag(Var->getLocation(),
  10127. diag::err_constexpr_static_mem_var_requires_init)
  10128. << Var->getDeclName();
  10129. Var->setInvalidDecl();
  10130. return;
  10131. }
  10132. } else {
  10133. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  10134. Var->setInvalidDecl();
  10135. return;
  10136. }
  10137. }
  10138. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  10139. // be initialized.
  10140. if (!Var->isInvalidDecl() &&
  10141. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  10142. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  10143. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  10144. Var->setInvalidDecl();
  10145. return;
  10146. }
  10147. switch (Var->isThisDeclarationADefinition()) {
  10148. case VarDecl::Definition:
  10149. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  10150. break;
  10151. // We have an out-of-line definition of a static data member
  10152. // that has an in-class initializer, so we type-check this like
  10153. // a declaration.
  10154. //
  10155. LLVM_FALLTHROUGH;
  10156. case VarDecl::DeclarationOnly:
  10157. // It's only a declaration.
  10158. // Block scope. C99 6.7p7: If an identifier for an object is
  10159. // declared with no linkage (C99 6.2.2p6), the type for the
  10160. // object shall be complete.
  10161. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  10162. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  10163. RequireCompleteType(Var->getLocation(), Type,
  10164. diag::err_typecheck_decl_incomplete_type))
  10165. Var->setInvalidDecl();
  10166. // Make sure that the type is not abstract.
  10167. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10168. RequireNonAbstractType(Var->getLocation(), Type,
  10169. diag::err_abstract_type_in_decl,
  10170. AbstractVariableType))
  10171. Var->setInvalidDecl();
  10172. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  10173. Var->getStorageClass() == SC_PrivateExtern) {
  10174. Diag(Var->getLocation(), diag::warn_private_extern);
  10175. Diag(Var->getLocation(), diag::note_private_extern);
  10176. }
  10177. return;
  10178. case VarDecl::TentativeDefinition:
  10179. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  10180. // object that has file scope without an initializer, and without a
  10181. // storage-class specifier or with the storage-class specifier "static",
  10182. // constitutes a tentative definition. Note: A tentative definition with
  10183. // external linkage is valid (C99 6.2.2p5).
  10184. if (!Var->isInvalidDecl()) {
  10185. if (const IncompleteArrayType *ArrayT
  10186. = Context.getAsIncompleteArrayType(Type)) {
  10187. if (RequireCompleteType(Var->getLocation(),
  10188. ArrayT->getElementType(),
  10189. diag::err_illegal_decl_array_incomplete_type))
  10190. Var->setInvalidDecl();
  10191. } else if (Var->getStorageClass() == SC_Static) {
  10192. // C99 6.9.2p3: If the declaration of an identifier for an object is
  10193. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  10194. // declared type shall not be an incomplete type.
  10195. // NOTE: code such as the following
  10196. // static struct s;
  10197. // struct s { int a; };
  10198. // is accepted by gcc. Hence here we issue a warning instead of
  10199. // an error and we do not invalidate the static declaration.
  10200. // NOTE: to avoid multiple warnings, only check the first declaration.
  10201. if (Var->isFirstDecl())
  10202. RequireCompleteType(Var->getLocation(), Type,
  10203. diag::ext_typecheck_decl_incomplete_type);
  10204. }
  10205. }
  10206. // Record the tentative definition; we're done.
  10207. if (!Var->isInvalidDecl())
  10208. TentativeDefinitions.push_back(Var);
  10209. return;
  10210. }
  10211. // Provide a specific diagnostic for uninitialized variable
  10212. // definitions with incomplete array type.
  10213. if (Type->isIncompleteArrayType()) {
  10214. Diag(Var->getLocation(),
  10215. diag::err_typecheck_incomplete_array_needs_initializer);
  10216. Var->setInvalidDecl();
  10217. return;
  10218. }
  10219. // Provide a specific diagnostic for uninitialized variable
  10220. // definitions with reference type.
  10221. if (Type->isReferenceType()) {
  10222. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  10223. << Var->getDeclName()
  10224. << SourceRange(Var->getLocation(), Var->getLocation());
  10225. Var->setInvalidDecl();
  10226. return;
  10227. }
  10228. // Do not attempt to type-check the default initializer for a
  10229. // variable with dependent type.
  10230. if (Type->isDependentType())
  10231. return;
  10232. if (Var->isInvalidDecl())
  10233. return;
  10234. if (!Var->hasAttr<AliasAttr>()) {
  10235. if (RequireCompleteType(Var->getLocation(),
  10236. Context.getBaseElementType(Type),
  10237. diag::err_typecheck_decl_incomplete_type)) {
  10238. Var->setInvalidDecl();
  10239. return;
  10240. }
  10241. } else {
  10242. return;
  10243. }
  10244. // The variable can not have an abstract class type.
  10245. if (RequireNonAbstractType(Var->getLocation(), Type,
  10246. diag::err_abstract_type_in_decl,
  10247. AbstractVariableType)) {
  10248. Var->setInvalidDecl();
  10249. return;
  10250. }
  10251. // Check for jumps past the implicit initializer. C++0x
  10252. // clarifies that this applies to a "variable with automatic
  10253. // storage duration", not a "local variable".
  10254. // C++11 [stmt.dcl]p3
  10255. // A program that jumps from a point where a variable with automatic
  10256. // storage duration is not in scope to a point where it is in scope is
  10257. // ill-formed unless the variable has scalar type, class type with a
  10258. // trivial default constructor and a trivial destructor, a cv-qualified
  10259. // version of one of these types, or an array of one of the preceding
  10260. // types and is declared without an initializer.
  10261. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  10262. if (const RecordType *Record
  10263. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  10264. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  10265. // Mark the function (if we're in one) for further checking even if the
  10266. // looser rules of C++11 do not require such checks, so that we can
  10267. // diagnose incompatibilities with C++98.
  10268. if (!CXXRecord->isPOD())
  10269. setFunctionHasBranchProtectedScope();
  10270. }
  10271. }
  10272. // C++03 [dcl.init]p9:
  10273. // If no initializer is specified for an object, and the
  10274. // object is of (possibly cv-qualified) non-POD class type (or
  10275. // array thereof), the object shall be default-initialized; if
  10276. // the object is of const-qualified type, the underlying class
  10277. // type shall have a user-declared default
  10278. // constructor. Otherwise, if no initializer is specified for
  10279. // a non- static object, the object and its subobjects, if
  10280. // any, have an indeterminate initial value); if the object
  10281. // or any of its subobjects are of const-qualified type, the
  10282. // program is ill-formed.
  10283. // C++0x [dcl.init]p11:
  10284. // If no initializer is specified for an object, the object is
  10285. // default-initialized; [...].
  10286. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  10287. InitializationKind Kind
  10288. = InitializationKind::CreateDefault(Var->getLocation());
  10289. InitializationSequence InitSeq(*this, Entity, Kind, None);
  10290. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  10291. if (Init.isInvalid())
  10292. Var->setInvalidDecl();
  10293. else if (Init.get()) {
  10294. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  10295. // This is important for template substitution.
  10296. Var->setInitStyle(VarDecl::CallInit);
  10297. }
  10298. CheckCompleteVariableDeclaration(Var);
  10299. }
  10300. }
  10301. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  10302. // If there is no declaration, there was an error parsing it. Ignore it.
  10303. if (!D)
  10304. return;
  10305. VarDecl *VD = dyn_cast<VarDecl>(D);
  10306. if (!VD) {
  10307. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  10308. D->setInvalidDecl();
  10309. return;
  10310. }
  10311. VD->setCXXForRangeDecl(true);
  10312. // for-range-declaration cannot be given a storage class specifier.
  10313. int Error = -1;
  10314. switch (VD->getStorageClass()) {
  10315. case SC_None:
  10316. break;
  10317. case SC_Extern:
  10318. Error = 0;
  10319. break;
  10320. case SC_Static:
  10321. Error = 1;
  10322. break;
  10323. case SC_PrivateExtern:
  10324. Error = 2;
  10325. break;
  10326. case SC_Auto:
  10327. Error = 3;
  10328. break;
  10329. case SC_Register:
  10330. Error = 4;
  10331. break;
  10332. }
  10333. if (Error != -1) {
  10334. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  10335. << VD->getDeclName() << Error;
  10336. D->setInvalidDecl();
  10337. }
  10338. }
  10339. StmtResult
  10340. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  10341. IdentifierInfo *Ident,
  10342. ParsedAttributes &Attrs,
  10343. SourceLocation AttrEnd) {
  10344. // C++1y [stmt.iter]p1:
  10345. // A range-based for statement of the form
  10346. // for ( for-range-identifier : for-range-initializer ) statement
  10347. // is equivalent to
  10348. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  10349. DeclSpec DS(Attrs.getPool().getFactory());
  10350. const char *PrevSpec;
  10351. unsigned DiagID;
  10352. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  10353. getPrintingPolicy());
  10354. Declarator D(DS, DeclaratorContext::ForContext);
  10355. D.SetIdentifier(Ident, IdentLoc);
  10356. D.takeAttributes(Attrs, AttrEnd);
  10357. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  10358. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
  10359. IdentLoc);
  10360. Decl *Var = ActOnDeclarator(S, D);
  10361. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10362. FinalizeDeclaration(Var);
  10363. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10364. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10365. }
  10366. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10367. if (var->isInvalidDecl()) return;
  10368. if (getLangOpts().OpenCL) {
  10369. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10370. // initialiser
  10371. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10372. !var->hasInit()) {
  10373. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10374. << 1 /*Init*/;
  10375. var->setInvalidDecl();
  10376. return;
  10377. }
  10378. }
  10379. // In Objective-C, don't allow jumps past the implicit initialization of a
  10380. // local retaining variable.
  10381. if (getLangOpts().ObjC &&
  10382. var->hasLocalStorage()) {
  10383. switch (var->getType().getObjCLifetime()) {
  10384. case Qualifiers::OCL_None:
  10385. case Qualifiers::OCL_ExplicitNone:
  10386. case Qualifiers::OCL_Autoreleasing:
  10387. break;
  10388. case Qualifiers::OCL_Weak:
  10389. case Qualifiers::OCL_Strong:
  10390. setFunctionHasBranchProtectedScope();
  10391. break;
  10392. }
  10393. }
  10394. if (var->hasLocalStorage() &&
  10395. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10396. setFunctionHasBranchProtectedScope();
  10397. // Warn about externally-visible variables being defined without a
  10398. // prior declaration. We only want to do this for global
  10399. // declarations, but we also specifically need to avoid doing it for
  10400. // class members because the linkage of an anonymous class can
  10401. // change if it's later given a typedef name.
  10402. if (var->isThisDeclarationADefinition() &&
  10403. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10404. var->isExternallyVisible() && var->hasLinkage() &&
  10405. !var->isInline() && !var->getDescribedVarTemplate() &&
  10406. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10407. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10408. var->getLocation())) {
  10409. // Find a previous declaration that's not a definition.
  10410. VarDecl *prev = var->getPreviousDecl();
  10411. while (prev && prev->isThisDeclarationADefinition())
  10412. prev = prev->getPreviousDecl();
  10413. if (!prev)
  10414. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10415. }
  10416. // Cache the result of checking for constant initialization.
  10417. Optional<bool> CacheHasConstInit;
  10418. const Expr *CacheCulprit;
  10419. auto checkConstInit = [&]() mutable {
  10420. if (!CacheHasConstInit)
  10421. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10422. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10423. return *CacheHasConstInit;
  10424. };
  10425. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10426. if (var->getType().isDestructedType()) {
  10427. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10428. // The type of an object with thread storage duration shall not
  10429. // have a non-trivial destructor.
  10430. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10431. if (getLangOpts().CPlusPlus11)
  10432. Diag(var->getLocation(), diag::note_use_thread_local);
  10433. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10434. if (!checkConstInit()) {
  10435. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10436. // An object of thread storage duration shall not require dynamic
  10437. // initialization.
  10438. // FIXME: Need strict checking here.
  10439. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10440. << CacheCulprit->getSourceRange();
  10441. if (getLangOpts().CPlusPlus11)
  10442. Diag(var->getLocation(), diag::note_use_thread_local);
  10443. }
  10444. }
  10445. }
  10446. // Apply section attributes and pragmas to global variables.
  10447. bool GlobalStorage = var->hasGlobalStorage();
  10448. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10449. !inTemplateInstantiation()) {
  10450. PragmaStack<StringLiteral *> *Stack = nullptr;
  10451. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10452. if (var->getType().isConstQualified())
  10453. Stack = &ConstSegStack;
  10454. else if (!var->getInit()) {
  10455. Stack = &BSSSegStack;
  10456. SectionFlags |= ASTContext::PSF_Write;
  10457. } else {
  10458. Stack = &DataSegStack;
  10459. SectionFlags |= ASTContext::PSF_Write;
  10460. }
  10461. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10462. var->addAttr(SectionAttr::CreateImplicit(
  10463. Context, SectionAttr::Declspec_allocate,
  10464. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10465. }
  10466. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10467. if (UnifySection(SA->getName(), SectionFlags, var))
  10468. var->dropAttr<SectionAttr>();
  10469. // Apply the init_seg attribute if this has an initializer. If the
  10470. // initializer turns out to not be dynamic, we'll end up ignoring this
  10471. // attribute.
  10472. if (CurInitSeg && var->getInit())
  10473. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10474. CurInitSegLoc));
  10475. }
  10476. // All the following checks are C++ only.
  10477. if (!getLangOpts().CPlusPlus) {
  10478. // If this variable must be emitted, add it as an initializer for the
  10479. // current module.
  10480. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10481. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10482. return;
  10483. }
  10484. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10485. CheckCompleteDecompositionDeclaration(DD);
  10486. QualType type = var->getType();
  10487. if (type->isDependentType()) return;
  10488. if (var->hasAttr<BlocksAttr>())
  10489. getCurFunction()->addByrefBlockVar(var);
  10490. Expr *Init = var->getInit();
  10491. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10492. QualType baseType = Context.getBaseElementType(type);
  10493. if (Init && !Init->isValueDependent()) {
  10494. if (var->isConstexpr()) {
  10495. SmallVector<PartialDiagnosticAt, 8> Notes;
  10496. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10497. SourceLocation DiagLoc = var->getLocation();
  10498. // If the note doesn't add any useful information other than a source
  10499. // location, fold it into the primary diagnostic.
  10500. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10501. diag::note_invalid_subexpr_in_const_expr) {
  10502. DiagLoc = Notes[0].first;
  10503. Notes.clear();
  10504. }
  10505. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10506. << var << Init->getSourceRange();
  10507. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10508. Diag(Notes[I].first, Notes[I].second);
  10509. }
  10510. } else if (var->isUsableInConstantExpressions(Context)) {
  10511. // Check whether the initializer of a const variable of integral or
  10512. // enumeration type is an ICE now, since we can't tell whether it was
  10513. // initialized by a constant expression if we check later.
  10514. var->checkInitIsICE();
  10515. }
  10516. // Don't emit further diagnostics about constexpr globals since they
  10517. // were just diagnosed.
  10518. if (!var->isConstexpr() && GlobalStorage &&
  10519. var->hasAttr<RequireConstantInitAttr>()) {
  10520. // FIXME: Need strict checking in C++03 here.
  10521. bool DiagErr = getLangOpts().CPlusPlus11
  10522. ? !var->checkInitIsICE() : !checkConstInit();
  10523. if (DiagErr) {
  10524. auto attr = var->getAttr<RequireConstantInitAttr>();
  10525. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10526. << Init->getSourceRange();
  10527. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10528. << attr->getRange();
  10529. if (getLangOpts().CPlusPlus11) {
  10530. APValue Value;
  10531. SmallVector<PartialDiagnosticAt, 8> Notes;
  10532. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10533. for (auto &it : Notes)
  10534. Diag(it.first, it.second);
  10535. } else {
  10536. Diag(CacheCulprit->getExprLoc(),
  10537. diag::note_invalid_subexpr_in_const_expr)
  10538. << CacheCulprit->getSourceRange();
  10539. }
  10540. }
  10541. }
  10542. else if (!var->isConstexpr() && IsGlobal &&
  10543. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10544. var->getLocation())) {
  10545. // Warn about globals which don't have a constant initializer. Don't
  10546. // warn about globals with a non-trivial destructor because we already
  10547. // warned about them.
  10548. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10549. if (!(RD && !RD->hasTrivialDestructor())) {
  10550. if (!checkConstInit())
  10551. Diag(var->getLocation(), diag::warn_global_constructor)
  10552. << Init->getSourceRange();
  10553. }
  10554. }
  10555. }
  10556. // Require the destructor.
  10557. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10558. FinalizeVarWithDestructor(var, recordType);
  10559. // If this variable must be emitted, add it as an initializer for the current
  10560. // module.
  10561. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10562. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10563. }
  10564. /// Determines if a variable's alignment is dependent.
  10565. static bool hasDependentAlignment(VarDecl *VD) {
  10566. if (VD->getType()->isDependentType())
  10567. return true;
  10568. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10569. if (I->isAlignmentDependent())
  10570. return true;
  10571. return false;
  10572. }
  10573. /// Check if VD needs to be dllexport/dllimport due to being in a
  10574. /// dllexport/import function.
  10575. void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
  10576. assert(VD->isStaticLocal());
  10577. auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10578. // Find outermost function when VD is in lambda function.
  10579. while (FD && !getDLLAttr(FD) &&
  10580. !FD->hasAttr<DLLExportStaticLocalAttr>() &&
  10581. !FD->hasAttr<DLLImportStaticLocalAttr>()) {
  10582. FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
  10583. }
  10584. if (!FD)
  10585. return;
  10586. // Static locals inherit dll attributes from their function.
  10587. if (Attr *A = getDLLAttr(FD)) {
  10588. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10589. NewAttr->setInherited(true);
  10590. VD->addAttr(NewAttr);
  10591. } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
  10592. auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
  10593. getASTContext(),
  10594. A->getSpellingListIndex());
  10595. NewAttr->setInherited(true);
  10596. VD->addAttr(NewAttr);
  10597. // Export this function to enforce exporting this static variable even
  10598. // if it is not used in this compilation unit.
  10599. if (!FD->hasAttr<DLLExportAttr>())
  10600. FD->addAttr(NewAttr);
  10601. } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
  10602. auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
  10603. getASTContext(),
  10604. A->getSpellingListIndex());
  10605. NewAttr->setInherited(true);
  10606. VD->addAttr(NewAttr);
  10607. }
  10608. }
  10609. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10610. /// any semantic actions necessary after any initializer has been attached.
  10611. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10612. // Note that we are no longer parsing the initializer for this declaration.
  10613. ParsingInitForAutoVars.erase(ThisDecl);
  10614. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10615. if (!VD)
  10616. return;
  10617. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10618. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10619. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10620. if (PragmaClangBSSSection.Valid)
  10621. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10622. PragmaClangBSSSection.SectionName,
  10623. PragmaClangBSSSection.PragmaLocation));
  10624. if (PragmaClangDataSection.Valid)
  10625. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10626. PragmaClangDataSection.SectionName,
  10627. PragmaClangDataSection.PragmaLocation));
  10628. if (PragmaClangRodataSection.Valid)
  10629. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10630. PragmaClangRodataSection.SectionName,
  10631. PragmaClangRodataSection.PragmaLocation));
  10632. }
  10633. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10634. for (auto *BD : DD->bindings()) {
  10635. FinalizeDeclaration(BD);
  10636. }
  10637. }
  10638. checkAttributesAfterMerging(*this, *VD);
  10639. // Perform TLS alignment check here after attributes attached to the variable
  10640. // which may affect the alignment have been processed. Only perform the check
  10641. // if the target has a maximum TLS alignment (zero means no constraints).
  10642. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10643. // Protect the check so that it's not performed on dependent types and
  10644. // dependent alignments (we can't determine the alignment in that case).
  10645. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10646. !VD->isInvalidDecl()) {
  10647. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10648. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10649. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10650. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10651. << (unsigned)MaxAlignChars.getQuantity();
  10652. }
  10653. }
  10654. }
  10655. if (VD->isStaticLocal()) {
  10656. CheckStaticLocalForDllExport(VD);
  10657. if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10658. // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
  10659. // function, only __shared__ variables or variables without any device
  10660. // memory qualifiers may be declared with static storage class.
  10661. // Note: It is unclear how a function-scope non-const static variable
  10662. // without device memory qualifier is implemented, therefore only static
  10663. // const variable without device memory qualifier is allowed.
  10664. [&]() {
  10665. if (!getLangOpts().CUDA)
  10666. return;
  10667. if (VD->hasAttr<CUDASharedAttr>())
  10668. return;
  10669. if (VD->getType().isConstQualified() &&
  10670. !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10671. return;
  10672. if (CUDADiagIfDeviceCode(VD->getLocation(),
  10673. diag::err_device_static_local_var)
  10674. << CurrentCUDATarget())
  10675. VD->setInvalidDecl();
  10676. }();
  10677. }
  10678. }
  10679. // Perform check for initializers of device-side global variables.
  10680. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10681. // 7.5). We must also apply the same checks to all __shared__
  10682. // variables whether they are local or not. CUDA also allows
  10683. // constant initializers for __constant__ and __device__ variables.
  10684. if (getLangOpts().CUDA)
  10685. checkAllowedCUDAInitializer(VD);
  10686. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10687. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10688. // Imported static data members cannot be defined out-of-line.
  10689. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10690. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10691. VD->isThisDeclarationADefinition()) {
  10692. // We allow definitions of dllimport class template static data members
  10693. // with a warning.
  10694. CXXRecordDecl *Context =
  10695. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10696. bool IsClassTemplateMember =
  10697. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10698. Context->getDescribedClassTemplate();
  10699. Diag(VD->getLocation(),
  10700. IsClassTemplateMember
  10701. ? diag::warn_attribute_dllimport_static_field_definition
  10702. : diag::err_attribute_dllimport_static_field_definition);
  10703. Diag(IA->getLocation(), diag::note_attribute);
  10704. if (!IsClassTemplateMember)
  10705. VD->setInvalidDecl();
  10706. }
  10707. }
  10708. // dllimport/dllexport variables cannot be thread local, their TLS index
  10709. // isn't exported with the variable.
  10710. if (DLLAttr && VD->getTLSKind()) {
  10711. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10712. if (F && getDLLAttr(F)) {
  10713. assert(VD->isStaticLocal());
  10714. // But if this is a static local in a dlimport/dllexport function, the
  10715. // function will never be inlined, which means the var would never be
  10716. // imported, so having it marked import/export is safe.
  10717. } else {
  10718. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10719. << DLLAttr;
  10720. VD->setInvalidDecl();
  10721. }
  10722. }
  10723. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10724. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10725. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10726. VD->dropAttr<UsedAttr>();
  10727. }
  10728. }
  10729. const DeclContext *DC = VD->getDeclContext();
  10730. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10731. // member, set the visibility of this variable.
  10732. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10733. AddPushedVisibilityAttribute(VD);
  10734. // FIXME: Warn on unused var template partial specializations.
  10735. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10736. MarkUnusedFileScopedDecl(VD);
  10737. // Now we have parsed the initializer and can update the table of magic
  10738. // tag values.
  10739. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10740. !VD->getType()->isIntegralOrEnumerationType())
  10741. return;
  10742. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10743. const Expr *MagicValueExpr = VD->getInit();
  10744. if (!MagicValueExpr) {
  10745. continue;
  10746. }
  10747. llvm::APSInt MagicValueInt;
  10748. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10749. Diag(I->getRange().getBegin(),
  10750. diag::err_type_tag_for_datatype_not_ice)
  10751. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10752. continue;
  10753. }
  10754. if (MagicValueInt.getActiveBits() > 64) {
  10755. Diag(I->getRange().getBegin(),
  10756. diag::err_type_tag_for_datatype_too_large)
  10757. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10758. continue;
  10759. }
  10760. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10761. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10762. MagicValue,
  10763. I->getMatchingCType(),
  10764. I->getLayoutCompatible(),
  10765. I->getMustBeNull());
  10766. }
  10767. }
  10768. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10769. auto *VD = dyn_cast<VarDecl>(DD);
  10770. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10771. }
  10772. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10773. ArrayRef<Decl *> Group) {
  10774. SmallVector<Decl*, 8> Decls;
  10775. if (DS.isTypeSpecOwned())
  10776. Decls.push_back(DS.getRepAsDecl());
  10777. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10778. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10779. bool DiagnosedMultipleDecomps = false;
  10780. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10781. bool DiagnosedNonDeducedAuto = false;
  10782. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10783. if (Decl *D = Group[i]) {
  10784. // For declarators, there are some additional syntactic-ish checks we need
  10785. // to perform.
  10786. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10787. if (!FirstDeclaratorInGroup)
  10788. FirstDeclaratorInGroup = DD;
  10789. if (!FirstDecompDeclaratorInGroup)
  10790. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10791. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10792. !hasDeducedAuto(DD))
  10793. FirstNonDeducedAutoInGroup = DD;
  10794. if (FirstDeclaratorInGroup != DD) {
  10795. // A decomposition declaration cannot be combined with any other
  10796. // declaration in the same group.
  10797. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10798. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10799. diag::err_decomp_decl_not_alone)
  10800. << FirstDeclaratorInGroup->getSourceRange()
  10801. << DD->getSourceRange();
  10802. DiagnosedMultipleDecomps = true;
  10803. }
  10804. // A declarator that uses 'auto' in any way other than to declare a
  10805. // variable with a deduced type cannot be combined with any other
  10806. // declarator in the same group.
  10807. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10808. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10809. diag::err_auto_non_deduced_not_alone)
  10810. << FirstNonDeducedAutoInGroup->getType()
  10811. ->hasAutoForTrailingReturnType()
  10812. << FirstDeclaratorInGroup->getSourceRange()
  10813. << DD->getSourceRange();
  10814. DiagnosedNonDeducedAuto = true;
  10815. }
  10816. }
  10817. }
  10818. Decls.push_back(D);
  10819. }
  10820. }
  10821. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10822. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10823. handleTagNumbering(Tag, S);
  10824. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10825. getLangOpts().CPlusPlus)
  10826. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10827. }
  10828. }
  10829. return BuildDeclaratorGroup(Decls);
  10830. }
  10831. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10832. /// group, performing any necessary semantic checking.
  10833. Sema::DeclGroupPtrTy
  10834. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10835. // C++14 [dcl.spec.auto]p7: (DR1347)
  10836. // If the type that replaces the placeholder type is not the same in each
  10837. // deduction, the program is ill-formed.
  10838. if (Group.size() > 1) {
  10839. QualType Deduced;
  10840. VarDecl *DeducedDecl = nullptr;
  10841. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10842. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10843. if (!D || D->isInvalidDecl())
  10844. break;
  10845. DeducedType *DT = D->getType()->getContainedDeducedType();
  10846. if (!DT || DT->getDeducedType().isNull())
  10847. continue;
  10848. if (Deduced.isNull()) {
  10849. Deduced = DT->getDeducedType();
  10850. DeducedDecl = D;
  10851. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10852. auto *AT = dyn_cast<AutoType>(DT);
  10853. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10854. diag::err_auto_different_deductions)
  10855. << (AT ? (unsigned)AT->getKeyword() : 3)
  10856. << Deduced << DeducedDecl->getDeclName()
  10857. << DT->getDeducedType() << D->getDeclName()
  10858. << DeducedDecl->getInit()->getSourceRange()
  10859. << D->getInit()->getSourceRange();
  10860. D->setInvalidDecl();
  10861. break;
  10862. }
  10863. }
  10864. }
  10865. ActOnDocumentableDecls(Group);
  10866. return DeclGroupPtrTy::make(
  10867. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10868. }
  10869. void Sema::ActOnDocumentableDecl(Decl *D) {
  10870. ActOnDocumentableDecls(D);
  10871. }
  10872. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10873. // Don't parse the comment if Doxygen diagnostics are ignored.
  10874. if (Group.empty() || !Group[0])
  10875. return;
  10876. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10877. Group[0]->getLocation()) &&
  10878. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10879. Group[0]->getLocation()))
  10880. return;
  10881. if (Group.size() >= 2) {
  10882. // This is a decl group. Normally it will contain only declarations
  10883. // produced from declarator list. But in case we have any definitions or
  10884. // additional declaration references:
  10885. // 'typedef struct S {} S;'
  10886. // 'typedef struct S *S;'
  10887. // 'struct S *pS;'
  10888. // FinalizeDeclaratorGroup adds these as separate declarations.
  10889. Decl *MaybeTagDecl = Group[0];
  10890. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10891. Group = Group.slice(1);
  10892. }
  10893. }
  10894. // See if there are any new comments that are not attached to a decl.
  10895. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10896. if (!Comments.empty() &&
  10897. !Comments.back()->isAttached()) {
  10898. // There is at least one comment that not attached to a decl.
  10899. // Maybe it should be attached to one of these decls?
  10900. //
  10901. // Note that this way we pick up not only comments that precede the
  10902. // declaration, but also comments that *follow* the declaration -- thanks to
  10903. // the lookahead in the lexer: we've consumed the semicolon and looked
  10904. // ahead through comments.
  10905. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10906. Context.getCommentForDecl(Group[i], &PP);
  10907. }
  10908. }
  10909. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10910. /// to introduce parameters into function prototype scope.
  10911. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10912. const DeclSpec &DS = D.getDeclSpec();
  10913. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10914. // C++03 [dcl.stc]p2 also permits 'auto'.
  10915. StorageClass SC = SC_None;
  10916. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10917. SC = SC_Register;
  10918. // In C++11, the 'register' storage class specifier is deprecated.
  10919. // In C++17, it is not allowed, but we tolerate it as an extension.
  10920. if (getLangOpts().CPlusPlus11) {
  10921. Diag(DS.getStorageClassSpecLoc(),
  10922. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  10923. : diag::warn_deprecated_register)
  10924. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10925. }
  10926. } else if (getLangOpts().CPlusPlus &&
  10927. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10928. SC = SC_Auto;
  10929. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10930. Diag(DS.getStorageClassSpecLoc(),
  10931. diag::err_invalid_storage_class_in_func_decl);
  10932. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10933. }
  10934. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10935. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10936. << DeclSpec::getSpecifierName(TSCS);
  10937. if (DS.isInlineSpecified())
  10938. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10939. << getLangOpts().CPlusPlus17;
  10940. if (DS.isConstexprSpecified())
  10941. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10942. << 0;
  10943. DiagnoseFunctionSpecifiers(DS);
  10944. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10945. QualType parmDeclType = TInfo->getType();
  10946. if (getLangOpts().CPlusPlus) {
  10947. // Check that there are no default arguments inside the type of this
  10948. // parameter.
  10949. CheckExtraCXXDefaultArguments(D);
  10950. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10951. if (D.getCXXScopeSpec().isSet()) {
  10952. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10953. << D.getCXXScopeSpec().getRange();
  10954. D.getCXXScopeSpec().clear();
  10955. }
  10956. }
  10957. // Ensure we have a valid name
  10958. IdentifierInfo *II = nullptr;
  10959. if (D.hasName()) {
  10960. II = D.getIdentifier();
  10961. if (!II) {
  10962. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10963. << GetNameForDeclarator(D).getName();
  10964. D.setInvalidType(true);
  10965. }
  10966. }
  10967. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10968. if (II) {
  10969. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10970. ForVisibleRedeclaration);
  10971. LookupName(R, S);
  10972. if (R.isSingleResult()) {
  10973. NamedDecl *PrevDecl = R.getFoundDecl();
  10974. if (PrevDecl->isTemplateParameter()) {
  10975. // Maybe we will complain about the shadowed template parameter.
  10976. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10977. // Just pretend that we didn't see the previous declaration.
  10978. PrevDecl = nullptr;
  10979. } else if (S->isDeclScope(PrevDecl)) {
  10980. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10981. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10982. // Recover by removing the name
  10983. II = nullptr;
  10984. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10985. D.setInvalidType(true);
  10986. }
  10987. }
  10988. }
  10989. // Temporarily put parameter variables in the translation unit, not
  10990. // the enclosing context. This prevents them from accidentally
  10991. // looking like class members in C++.
  10992. ParmVarDecl *New =
  10993. CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
  10994. D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
  10995. if (D.isInvalidType())
  10996. New->setInvalidDecl();
  10997. assert(S->isFunctionPrototypeScope());
  10998. assert(S->getFunctionPrototypeDepth() >= 1);
  10999. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  11000. S->getNextFunctionPrototypeIndex());
  11001. // Add the parameter declaration into this scope.
  11002. S->AddDecl(New);
  11003. if (II)
  11004. IdResolver.AddDecl(New);
  11005. ProcessDeclAttributes(S, New, D);
  11006. if (D.getDeclSpec().isModulePrivateSpecified())
  11007. Diag(New->getLocation(), diag::err_module_private_local)
  11008. << 1 << New->getDeclName()
  11009. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11010. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11011. if (New->hasAttr<BlocksAttr>()) {
  11012. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  11013. }
  11014. return New;
  11015. }
  11016. /// Synthesizes a variable for a parameter arising from a
  11017. /// typedef.
  11018. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  11019. SourceLocation Loc,
  11020. QualType T) {
  11021. /* FIXME: setting StartLoc == Loc.
  11022. Would it be worth to modify callers so as to provide proper source
  11023. location for the unnamed parameters, embedding the parameter's type? */
  11024. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  11025. T, Context.getTrivialTypeSourceInfo(T, Loc),
  11026. SC_None, nullptr);
  11027. Param->setImplicit();
  11028. return Param;
  11029. }
  11030. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  11031. // Don't diagnose unused-parameter errors in template instantiations; we
  11032. // will already have done so in the template itself.
  11033. if (inTemplateInstantiation())
  11034. return;
  11035. for (const ParmVarDecl *Parameter : Parameters) {
  11036. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  11037. !Parameter->hasAttr<UnusedAttr>()) {
  11038. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  11039. << Parameter->getDeclName();
  11040. }
  11041. }
  11042. }
  11043. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  11044. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  11045. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  11046. return;
  11047. // Warn if the return value is pass-by-value and larger than the specified
  11048. // threshold.
  11049. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  11050. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  11051. if (Size > LangOpts.NumLargeByValueCopy)
  11052. Diag(D->getLocation(), diag::warn_return_value_size)
  11053. << D->getDeclName() << Size;
  11054. }
  11055. // Warn if any parameter is pass-by-value and larger than the specified
  11056. // threshold.
  11057. for (const ParmVarDecl *Parameter : Parameters) {
  11058. QualType T = Parameter->getType();
  11059. if (T->isDependentType() || !T.isPODType(Context))
  11060. continue;
  11061. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  11062. if (Size > LangOpts.NumLargeByValueCopy)
  11063. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  11064. << Parameter->getDeclName() << Size;
  11065. }
  11066. }
  11067. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  11068. SourceLocation NameLoc, IdentifierInfo *Name,
  11069. QualType T, TypeSourceInfo *TSInfo,
  11070. StorageClass SC) {
  11071. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  11072. if (getLangOpts().ObjCAutoRefCount &&
  11073. T.getObjCLifetime() == Qualifiers::OCL_None &&
  11074. T->isObjCLifetimeType()) {
  11075. Qualifiers::ObjCLifetime lifetime;
  11076. // Special cases for arrays:
  11077. // - if it's const, use __unsafe_unretained
  11078. // - otherwise, it's an error
  11079. if (T->isArrayType()) {
  11080. if (!T.isConstQualified()) {
  11081. if (DelayedDiagnostics.shouldDelayDiagnostics())
  11082. DelayedDiagnostics.add(
  11083. sema::DelayedDiagnostic::makeForbiddenType(
  11084. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  11085. else
  11086. Diag(NameLoc, diag::err_arc_array_param_no_ownership)
  11087. << TSInfo->getTypeLoc().getSourceRange();
  11088. }
  11089. lifetime = Qualifiers::OCL_ExplicitNone;
  11090. } else {
  11091. lifetime = T->getObjCARCImplicitLifetime();
  11092. }
  11093. T = Context.getLifetimeQualifiedType(T, lifetime);
  11094. }
  11095. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  11096. Context.getAdjustedParameterType(T),
  11097. TSInfo, SC, nullptr);
  11098. // Parameters can not be abstract class types.
  11099. // For record types, this is done by the AbstractClassUsageDiagnoser once
  11100. // the class has been completely parsed.
  11101. if (!CurContext->isRecord() &&
  11102. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  11103. AbstractParamType))
  11104. New->setInvalidDecl();
  11105. // Parameter declarators cannot be interface types. All ObjC objects are
  11106. // passed by reference.
  11107. if (T->isObjCObjectType()) {
  11108. SourceLocation TypeEndLoc =
  11109. getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
  11110. Diag(NameLoc,
  11111. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  11112. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  11113. T = Context.getObjCObjectPointerType(T);
  11114. New->setType(T);
  11115. }
  11116. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  11117. // duration shall not be qualified by an address-space qualifier."
  11118. // Since all parameters have automatic store duration, they can not have
  11119. // an address space.
  11120. if (T.getAddressSpace() != LangAS::Default &&
  11121. // OpenCL allows function arguments declared to be an array of a type
  11122. // to be qualified with an address space.
  11123. !(getLangOpts().OpenCL &&
  11124. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  11125. Diag(NameLoc, diag::err_arg_with_address_space);
  11126. New->setInvalidDecl();
  11127. }
  11128. return New;
  11129. }
  11130. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  11131. SourceLocation LocAfterDecls) {
  11132. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  11133. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  11134. // for a K&R function.
  11135. if (!FTI.hasPrototype) {
  11136. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  11137. --i;
  11138. if (FTI.Params[i].Param == nullptr) {
  11139. SmallString<256> Code;
  11140. llvm::raw_svector_ostream(Code)
  11141. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  11142. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  11143. << FTI.Params[i].Ident
  11144. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  11145. // Implicitly declare the argument as type 'int' for lack of a better
  11146. // type.
  11147. AttributeFactory attrs;
  11148. DeclSpec DS(attrs);
  11149. const char* PrevSpec; // unused
  11150. unsigned DiagID; // unused
  11151. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  11152. DiagID, Context.getPrintingPolicy());
  11153. // Use the identifier location for the type source range.
  11154. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  11155. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  11156. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  11157. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  11158. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  11159. }
  11160. }
  11161. }
  11162. }
  11163. Decl *
  11164. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  11165. MultiTemplateParamsArg TemplateParameterLists,
  11166. SkipBodyInfo *SkipBody) {
  11167. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  11168. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  11169. Scope *ParentScope = FnBodyScope->getParent();
  11170. D.setFunctionDefinitionKind(FDK_Definition);
  11171. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  11172. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  11173. }
  11174. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  11175. Consumer.HandleInlineFunctionDefinition(D);
  11176. }
  11177. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  11178. const FunctionDecl*& PossibleZeroParamPrototype) {
  11179. // Don't warn about invalid declarations.
  11180. if (FD->isInvalidDecl())
  11181. return false;
  11182. // Or declarations that aren't global.
  11183. if (!FD->isGlobal())
  11184. return false;
  11185. // Don't warn about C++ member functions.
  11186. if (isa<CXXMethodDecl>(FD))
  11187. return false;
  11188. // Don't warn about 'main'.
  11189. if (FD->isMain())
  11190. return false;
  11191. // Don't warn about inline functions.
  11192. if (FD->isInlined())
  11193. return false;
  11194. // Don't warn about function templates.
  11195. if (FD->getDescribedFunctionTemplate())
  11196. return false;
  11197. // Don't warn about function template specializations.
  11198. if (FD->isFunctionTemplateSpecialization())
  11199. return false;
  11200. // Don't warn for OpenCL kernels.
  11201. if (FD->hasAttr<OpenCLKernelAttr>())
  11202. return false;
  11203. // Don't warn on explicitly deleted functions.
  11204. if (FD->isDeleted())
  11205. return false;
  11206. bool MissingPrototype = true;
  11207. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  11208. Prev; Prev = Prev->getPreviousDecl()) {
  11209. // Ignore any declarations that occur in function or method
  11210. // scope, because they aren't visible from the header.
  11211. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  11212. continue;
  11213. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  11214. if (FD->getNumParams() == 0)
  11215. PossibleZeroParamPrototype = Prev;
  11216. break;
  11217. }
  11218. return MissingPrototype;
  11219. }
  11220. void
  11221. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  11222. const FunctionDecl *EffectiveDefinition,
  11223. SkipBodyInfo *SkipBody) {
  11224. const FunctionDecl *Definition = EffectiveDefinition;
  11225. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  11226. // If this is a friend function defined in a class template, it does not
  11227. // have a body until it is used, nevertheless it is a definition, see
  11228. // [temp.inst]p2:
  11229. //
  11230. // ... for the purpose of determining whether an instantiated redeclaration
  11231. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  11232. // corresponds to a definition in the template is considered to be a
  11233. // definition.
  11234. //
  11235. // The following code must produce redefinition error:
  11236. //
  11237. // template<typename T> struct C20 { friend void func_20() {} };
  11238. // C20<int> c20i;
  11239. // void func_20() {}
  11240. //
  11241. for (auto I : FD->redecls()) {
  11242. if (I != FD && !I->isInvalidDecl() &&
  11243. I->getFriendObjectKind() != Decl::FOK_None) {
  11244. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  11245. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  11246. // A merged copy of the same function, instantiated as a member of
  11247. // the same class, is OK.
  11248. if (declaresSameEntity(OrigFD, Original) &&
  11249. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  11250. cast<Decl>(FD->getLexicalDeclContext())))
  11251. continue;
  11252. }
  11253. if (Original->isThisDeclarationADefinition()) {
  11254. Definition = I;
  11255. break;
  11256. }
  11257. }
  11258. }
  11259. }
  11260. }
  11261. if (!Definition)
  11262. // Similar to friend functions a friend function template may be a
  11263. // definition and do not have a body if it is instantiated in a class
  11264. // template.
  11265. if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
  11266. for (auto I : FTD->redecls()) {
  11267. auto D = cast<FunctionTemplateDecl>(I);
  11268. if (D != FTD) {
  11269. assert(!D->isThisDeclarationADefinition() &&
  11270. "More than one definition in redeclaration chain");
  11271. if (D->getFriendObjectKind() != Decl::FOK_None)
  11272. if (FunctionTemplateDecl *FT =
  11273. D->getInstantiatedFromMemberTemplate()) {
  11274. if (FT->isThisDeclarationADefinition()) {
  11275. Definition = D->getTemplatedDecl();
  11276. break;
  11277. }
  11278. }
  11279. }
  11280. }
  11281. }
  11282. if (!Definition)
  11283. return;
  11284. if (canRedefineFunction(Definition, getLangOpts()))
  11285. return;
  11286. // Don't emit an error when this is redefinition of a typo-corrected
  11287. // definition.
  11288. if (TypoCorrectedFunctionDefinitions.count(Definition))
  11289. return;
  11290. // If we don't have a visible definition of the function, and it's inline or
  11291. // a template, skip the new definition.
  11292. if (SkipBody && !hasVisibleDefinition(Definition) &&
  11293. (Definition->getFormalLinkage() == InternalLinkage ||
  11294. Definition->isInlined() ||
  11295. Definition->getDescribedFunctionTemplate() ||
  11296. Definition->getNumTemplateParameterLists())) {
  11297. SkipBody->ShouldSkip = true;
  11298. SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
  11299. if (auto *TD = Definition->getDescribedFunctionTemplate())
  11300. makeMergedDefinitionVisible(TD);
  11301. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  11302. return;
  11303. }
  11304. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  11305. Definition->getStorageClass() == SC_Extern)
  11306. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  11307. << FD->getDeclName() << getLangOpts().CPlusPlus;
  11308. else
  11309. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  11310. Diag(Definition->getLocation(), diag::note_previous_definition);
  11311. FD->setInvalidDecl();
  11312. }
  11313. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  11314. Sema &S) {
  11315. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  11316. LambdaScopeInfo *LSI = S.PushLambdaScope();
  11317. LSI->CallOperator = CallOperator;
  11318. LSI->Lambda = LambdaClass;
  11319. LSI->ReturnType = CallOperator->getReturnType();
  11320. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  11321. if (LCD == LCD_None)
  11322. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  11323. else if (LCD == LCD_ByCopy)
  11324. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  11325. else if (LCD == LCD_ByRef)
  11326. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  11327. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  11328. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  11329. LSI->Mutable = !CallOperator->isConst();
  11330. // Add the captures to the LSI so they can be noted as already
  11331. // captured within tryCaptureVar.
  11332. auto I = LambdaClass->field_begin();
  11333. for (const auto &C : LambdaClass->captures()) {
  11334. if (C.capturesVariable()) {
  11335. VarDecl *VD = C.getCapturedVar();
  11336. if (VD->isInitCapture())
  11337. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  11338. QualType CaptureType = VD->getType();
  11339. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  11340. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  11341. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  11342. /*EllipsisLoc*/C.isPackExpansion()
  11343. ? C.getEllipsisLoc() : SourceLocation(),
  11344. CaptureType, /*Expr*/ nullptr);
  11345. } else if (C.capturesThis()) {
  11346. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  11347. /*Expr*/ nullptr,
  11348. C.getCaptureKind() == LCK_StarThis);
  11349. } else {
  11350. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  11351. }
  11352. ++I;
  11353. }
  11354. }
  11355. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11356. SkipBodyInfo *SkipBody) {
  11357. if (!D) {
  11358. // Parsing the function declaration failed in some way. Push on a fake scope
  11359. // anyway so we can try to parse the function body.
  11360. PushFunctionScope();
  11361. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11362. return D;
  11363. }
  11364. FunctionDecl *FD = nullptr;
  11365. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11366. FD = FunTmpl->getTemplatedDecl();
  11367. else
  11368. FD = cast<FunctionDecl>(D);
  11369. // Do not push if it is a lambda because one is already pushed when building
  11370. // the lambda in ActOnStartOfLambdaDefinition().
  11371. if (!isLambdaCallOperator(FD))
  11372. PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
  11373. // Check for defining attributes before the check for redefinition.
  11374. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11375. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11376. FD->dropAttr<AliasAttr>();
  11377. FD->setInvalidDecl();
  11378. }
  11379. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11380. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11381. FD->dropAttr<IFuncAttr>();
  11382. FD->setInvalidDecl();
  11383. }
  11384. // See if this is a redefinition. If 'will have body' is already set, then
  11385. // these checks were already performed when it was set.
  11386. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11387. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11388. // If we're skipping the body, we're done. Don't enter the scope.
  11389. if (SkipBody && SkipBody->ShouldSkip)
  11390. return D;
  11391. }
  11392. // Mark this function as "will have a body eventually". This lets users to
  11393. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11394. // this function.
  11395. FD->setWillHaveBody();
  11396. // If we are instantiating a generic lambda call operator, push
  11397. // a LambdaScopeInfo onto the function stack. But use the information
  11398. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11399. // LambdaScopeInfo.
  11400. // When the template operator is being specialized, the LambdaScopeInfo,
  11401. // has to be properly restored so that tryCaptureVariable doesn't try
  11402. // and capture any new variables. In addition when calculating potential
  11403. // captures during transformation of nested lambdas, it is necessary to
  11404. // have the LSI properly restored.
  11405. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11406. assert(inTemplateInstantiation() &&
  11407. "There should be an active template instantiation on the stack "
  11408. "when instantiating a generic lambda!");
  11409. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11410. } else {
  11411. // Enter a new function scope
  11412. PushFunctionScope();
  11413. }
  11414. // Builtin functions cannot be defined.
  11415. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11416. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11417. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11418. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11419. FD->setInvalidDecl();
  11420. }
  11421. }
  11422. // The return type of a function definition must be complete
  11423. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11424. QualType ResultType = FD->getReturnType();
  11425. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11426. !FD->isInvalidDecl() &&
  11427. RequireCompleteType(FD->getLocation(), ResultType,
  11428. diag::err_func_def_incomplete_result))
  11429. FD->setInvalidDecl();
  11430. if (FnBodyScope)
  11431. PushDeclContext(FnBodyScope, FD);
  11432. // Check the validity of our function parameters
  11433. CheckParmsForFunctionDef(FD->parameters(),
  11434. /*CheckParameterNames=*/true);
  11435. // Add non-parameter declarations already in the function to the current
  11436. // scope.
  11437. if (FnBodyScope) {
  11438. for (Decl *NPD : FD->decls()) {
  11439. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11440. if (!NonParmDecl)
  11441. continue;
  11442. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11443. "parameters should not be in newly created FD yet");
  11444. // If the decl has a name, make it accessible in the current scope.
  11445. if (NonParmDecl->getDeclName())
  11446. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11447. // Similarly, dive into enums and fish their constants out, making them
  11448. // accessible in this scope.
  11449. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11450. for (auto *EI : ED->enumerators())
  11451. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11452. }
  11453. }
  11454. }
  11455. // Introduce our parameters into the function scope
  11456. for (auto Param : FD->parameters()) {
  11457. Param->setOwningFunction(FD);
  11458. // If this has an identifier, add it to the scope stack.
  11459. if (Param->getIdentifier() && FnBodyScope) {
  11460. CheckShadow(FnBodyScope, Param);
  11461. PushOnScopeChains(Param, FnBodyScope);
  11462. }
  11463. }
  11464. // Ensure that the function's exception specification is instantiated.
  11465. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11466. ResolveExceptionSpec(D->getLocation(), FPT);
  11467. // dllimport cannot be applied to non-inline function definitions.
  11468. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11469. !FD->isTemplateInstantiation()) {
  11470. assert(!FD->hasAttr<DLLExportAttr>());
  11471. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11472. FD->setInvalidDecl();
  11473. return D;
  11474. }
  11475. // We want to attach documentation to original Decl (which might be
  11476. // a function template).
  11477. ActOnDocumentableDecl(D);
  11478. if (getCurLexicalContext()->isObjCContainer() &&
  11479. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11480. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11481. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11482. return D;
  11483. }
  11484. /// Given the set of return statements within a function body,
  11485. /// compute the variables that are subject to the named return value
  11486. /// optimization.
  11487. ///
  11488. /// Each of the variables that is subject to the named return value
  11489. /// optimization will be marked as NRVO variables in the AST, and any
  11490. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11491. /// use the named return value optimization.
  11492. ///
  11493. /// This function applies a very simplistic algorithm for NRVO: if every return
  11494. /// statement in the scope of a variable has the same NRVO candidate, that
  11495. /// candidate is an NRVO variable.
  11496. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11497. ReturnStmt **Returns = Scope->Returns.data();
  11498. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11499. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11500. if (!NRVOCandidate->isNRVOVariable())
  11501. Returns[I]->setNRVOCandidate(nullptr);
  11502. }
  11503. }
  11504. }
  11505. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11506. // We can't delay parsing the body of a constexpr function template (yet).
  11507. if (D.getDeclSpec().isConstexprSpecified())
  11508. return false;
  11509. // We can't delay parsing the body of a function template with a deduced
  11510. // return type (yet).
  11511. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11512. // If the placeholder introduces a non-deduced trailing return type,
  11513. // we can still delay parsing it.
  11514. if (D.getNumTypeObjects()) {
  11515. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11516. if (Outer.Kind == DeclaratorChunk::Function &&
  11517. Outer.Fun.hasTrailingReturnType()) {
  11518. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11519. return Ty.isNull() || !Ty->isUndeducedType();
  11520. }
  11521. }
  11522. return false;
  11523. }
  11524. return true;
  11525. }
  11526. bool Sema::canSkipFunctionBody(Decl *D) {
  11527. // We cannot skip the body of a function (or function template) which is
  11528. // constexpr, since we may need to evaluate its body in order to parse the
  11529. // rest of the file.
  11530. // We cannot skip the body of a function with an undeduced return type,
  11531. // because any callers of that function need to know the type.
  11532. if (const FunctionDecl *FD = D->getAsFunction()) {
  11533. if (FD->isConstexpr())
  11534. return false;
  11535. // We can't simply call Type::isUndeducedType here, because inside template
  11536. // auto can be deduced to a dependent type, which is not considered
  11537. // "undeduced".
  11538. if (FD->getReturnType()->getContainedDeducedType())
  11539. return false;
  11540. }
  11541. return Consumer.shouldSkipFunctionBody(D);
  11542. }
  11543. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11544. if (!Decl)
  11545. return nullptr;
  11546. if (FunctionDecl *FD = Decl->getAsFunction())
  11547. FD->setHasSkippedBody();
  11548. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11549. MD->setHasSkippedBody();
  11550. return Decl;
  11551. }
  11552. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11553. return ActOnFinishFunctionBody(D, BodyArg, false);
  11554. }
  11555. /// RAII object that pops an ExpressionEvaluationContext when exiting a function
  11556. /// body.
  11557. class ExitFunctionBodyRAII {
  11558. public:
  11559. ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
  11560. ~ExitFunctionBodyRAII() {
  11561. if (!IsLambda)
  11562. S.PopExpressionEvaluationContext();
  11563. }
  11564. private:
  11565. Sema &S;
  11566. bool IsLambda = false;
  11567. };
  11568. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11569. bool IsInstantiation) {
  11570. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11571. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11572. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11573. if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
  11574. CheckCompletedCoroutineBody(FD, Body);
  11575. // Do not call PopExpressionEvaluationContext() if it is a lambda because one
  11576. // is already popped when finishing the lambda in BuildLambdaExpr(). This is
  11577. // meant to pop the context added in ActOnStartOfFunctionDef().
  11578. ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
  11579. if (FD) {
  11580. FD->setBody(Body);
  11581. FD->setWillHaveBody(false);
  11582. if (getLangOpts().CPlusPlus14) {
  11583. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11584. FD->getReturnType()->isUndeducedType()) {
  11585. // If the function has a deduced result type but contains no 'return'
  11586. // statements, the result type as written must be exactly 'auto', and
  11587. // the deduced result type is 'void'.
  11588. if (!FD->getReturnType()->getAs<AutoType>()) {
  11589. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11590. << FD->getReturnType();
  11591. FD->setInvalidDecl();
  11592. } else {
  11593. // Substitute 'void' for the 'auto' in the type.
  11594. TypeLoc ResultType = getReturnTypeLoc(FD);
  11595. Context.adjustDeducedFunctionResultType(
  11596. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11597. }
  11598. }
  11599. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11600. // In C++11, we don't use 'auto' deduction rules for lambda call
  11601. // operators because we don't support return type deduction.
  11602. auto *LSI = getCurLambda();
  11603. if (LSI->HasImplicitReturnType) {
  11604. deduceClosureReturnType(*LSI);
  11605. // C++11 [expr.prim.lambda]p4:
  11606. // [...] if there are no return statements in the compound-statement
  11607. // [the deduced type is] the type void
  11608. QualType RetType =
  11609. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11610. // Update the return type to the deduced type.
  11611. const FunctionProtoType *Proto =
  11612. FD->getType()->getAs<FunctionProtoType>();
  11613. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11614. Proto->getExtProtoInfo()));
  11615. }
  11616. }
  11617. // If the function implicitly returns zero (like 'main') or is naked,
  11618. // don't complain about missing return statements.
  11619. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  11620. WP.disableCheckFallThrough();
  11621. // MSVC permits the use of pure specifier (=0) on function definition,
  11622. // defined at class scope, warn about this non-standard construct.
  11623. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  11624. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  11625. if (!FD->isInvalidDecl()) {
  11626. // Don't diagnose unused parameters of defaulted or deleted functions.
  11627. if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
  11628. DiagnoseUnusedParameters(FD->parameters());
  11629. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11630. FD->getReturnType(), FD);
  11631. // If this is a structor, we need a vtable.
  11632. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11633. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11634. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11635. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11636. // Try to apply the named return value optimization. We have to check
  11637. // if we can do this here because lambdas keep return statements around
  11638. // to deduce an implicit return type.
  11639. if (FD->getReturnType()->isRecordType() &&
  11640. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  11641. computeNRVO(Body, getCurFunction());
  11642. }
  11643. // GNU warning -Wmissing-prototypes:
  11644. // Warn if a global function is defined without a previous
  11645. // prototype declaration. This warning is issued even if the
  11646. // definition itself provides a prototype. The aim is to detect
  11647. // global functions that fail to be declared in header files.
  11648. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  11649. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  11650. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11651. if (PossibleZeroParamPrototype) {
  11652. // We found a declaration that is not a prototype,
  11653. // but that could be a zero-parameter prototype
  11654. if (TypeSourceInfo *TI =
  11655. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  11656. TypeLoc TL = TI->getTypeLoc();
  11657. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11658. Diag(PossibleZeroParamPrototype->getLocation(),
  11659. diag::note_declaration_not_a_prototype)
  11660. << PossibleZeroParamPrototype
  11661. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  11662. }
  11663. }
  11664. // GNU warning -Wstrict-prototypes
  11665. // Warn if K&R function is defined without a previous declaration.
  11666. // This warning is issued only if the definition itself does not provide
  11667. // a prototype. Only K&R definitions do not provide a prototype.
  11668. // An empty list in a function declarator that is part of a definition
  11669. // of that function specifies that the function has no parameters
  11670. // (C99 6.7.5.3p14)
  11671. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11672. !LangOpts.CPlusPlus) {
  11673. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11674. TypeLoc TL = TI->getTypeLoc();
  11675. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11676. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11677. }
  11678. }
  11679. // Warn on CPUDispatch with an actual body.
  11680. if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
  11681. if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
  11682. if (!CmpndBody->body_empty())
  11683. Diag(CmpndBody->body_front()->getBeginLoc(),
  11684. diag::warn_dispatch_body_ignored);
  11685. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11686. const CXXMethodDecl *KeyFunction;
  11687. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11688. MD->isVirtual() &&
  11689. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11690. MD == KeyFunction->getCanonicalDecl()) {
  11691. // Update the key-function state if necessary for this ABI.
  11692. if (FD->isInlined() &&
  11693. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11694. Context.setNonKeyFunction(MD);
  11695. // If the newly-chosen key function is already defined, then we
  11696. // need to mark the vtable as used retroactively.
  11697. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11698. const FunctionDecl *Definition;
  11699. if (KeyFunction && KeyFunction->isDefined(Definition))
  11700. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11701. } else {
  11702. // We just defined they key function; mark the vtable as used.
  11703. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11704. }
  11705. }
  11706. }
  11707. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11708. "Function parsing confused");
  11709. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11710. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11711. MD->setBody(Body);
  11712. if (!MD->isInvalidDecl()) {
  11713. if (!MD->hasSkippedBody())
  11714. DiagnoseUnusedParameters(MD->parameters());
  11715. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11716. MD->getReturnType(), MD);
  11717. if (Body)
  11718. computeNRVO(Body, getCurFunction());
  11719. }
  11720. if (getCurFunction()->ObjCShouldCallSuper) {
  11721. Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
  11722. << MD->getSelector().getAsString();
  11723. getCurFunction()->ObjCShouldCallSuper = false;
  11724. }
  11725. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11726. const ObjCMethodDecl *InitMethod = nullptr;
  11727. bool isDesignated =
  11728. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11729. assert(isDesignated && InitMethod);
  11730. (void)isDesignated;
  11731. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11732. auto IFace = MD->getClassInterface();
  11733. if (!IFace)
  11734. return false;
  11735. auto SuperD = IFace->getSuperClass();
  11736. if (!SuperD)
  11737. return false;
  11738. return SuperD->getIdentifier() ==
  11739. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11740. };
  11741. // Don't issue this warning for unavailable inits or direct subclasses
  11742. // of NSObject.
  11743. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11744. Diag(MD->getLocation(),
  11745. diag::warn_objc_designated_init_missing_super_call);
  11746. Diag(InitMethod->getLocation(),
  11747. diag::note_objc_designated_init_marked_here);
  11748. }
  11749. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11750. }
  11751. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11752. // Don't issue this warning for unavaialable inits.
  11753. if (!MD->isUnavailable())
  11754. Diag(MD->getLocation(),
  11755. diag::warn_objc_secondary_init_missing_init_call);
  11756. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11757. }
  11758. } else {
  11759. // Parsing the function declaration failed in some way. Pop the fake scope
  11760. // we pushed on.
  11761. PopFunctionScopeInfo(ActivePolicy, dcl);
  11762. return nullptr;
  11763. }
  11764. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11765. DiagnoseUnguardedAvailabilityViolations(dcl);
  11766. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11767. "This should only be set for ObjC methods, which should have been "
  11768. "handled in the block above.");
  11769. // Verify and clean out per-function state.
  11770. if (Body && (!FD || !FD->isDefaulted())) {
  11771. // C++ constructors that have function-try-blocks can't have return
  11772. // statements in the handlers of that block. (C++ [except.handle]p14)
  11773. // Verify this.
  11774. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11775. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11776. // Verify that gotos and switch cases don't jump into scopes illegally.
  11777. if (getCurFunction()->NeedsScopeChecking() &&
  11778. !PP.isCodeCompletionEnabled())
  11779. DiagnoseInvalidJumps(Body);
  11780. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11781. if (!Destructor->getParent()->isDependentType())
  11782. CheckDestructor(Destructor);
  11783. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11784. Destructor->getParent());
  11785. }
  11786. // If any errors have occurred, clear out any temporaries that may have
  11787. // been leftover. This ensures that these temporaries won't be picked up for
  11788. // deletion in some later function.
  11789. if (getDiagnostics().hasErrorOccurred() ||
  11790. getDiagnostics().getSuppressAllDiagnostics()) {
  11791. DiscardCleanupsInEvaluationContext();
  11792. }
  11793. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11794. !isa<FunctionTemplateDecl>(dcl)) {
  11795. // Since the body is valid, issue any analysis-based warnings that are
  11796. // enabled.
  11797. ActivePolicy = &WP;
  11798. }
  11799. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11800. (!CheckConstexprFunctionDecl(FD) ||
  11801. !CheckConstexprFunctionBody(FD, Body)))
  11802. FD->setInvalidDecl();
  11803. if (FD && FD->hasAttr<NakedAttr>()) {
  11804. for (const Stmt *S : Body->children()) {
  11805. // Allow local register variables without initializer as they don't
  11806. // require prologue.
  11807. bool RegisterVariables = false;
  11808. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11809. for (const auto *Decl : DS->decls()) {
  11810. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11811. RegisterVariables =
  11812. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11813. if (!RegisterVariables)
  11814. break;
  11815. }
  11816. }
  11817. }
  11818. if (RegisterVariables)
  11819. continue;
  11820. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11821. Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
  11822. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11823. FD->setInvalidDecl();
  11824. break;
  11825. }
  11826. }
  11827. }
  11828. assert(ExprCleanupObjects.size() ==
  11829. ExprEvalContexts.back().NumCleanupObjects &&
  11830. "Leftover temporaries in function");
  11831. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11832. assert(MaybeODRUseExprs.empty() &&
  11833. "Leftover expressions for odr-use checking");
  11834. }
  11835. if (!IsInstantiation)
  11836. PopDeclContext();
  11837. PopFunctionScopeInfo(ActivePolicy, dcl);
  11838. // If any errors have occurred, clear out any temporaries that may have
  11839. // been leftover. This ensures that these temporaries won't be picked up for
  11840. // deletion in some later function.
  11841. if (getDiagnostics().hasErrorOccurred()) {
  11842. DiscardCleanupsInEvaluationContext();
  11843. }
  11844. return dcl;
  11845. }
  11846. /// When we finish delayed parsing of an attribute, we must attach it to the
  11847. /// relevant Decl.
  11848. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11849. ParsedAttributes &Attrs) {
  11850. // Always attach attributes to the underlying decl.
  11851. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11852. D = TD->getTemplatedDecl();
  11853. ProcessDeclAttributeList(S, D, Attrs);
  11854. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11855. if (Method->isStatic())
  11856. checkThisInStaticMemberFunctionAttributes(Method);
  11857. }
  11858. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11859. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11860. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11861. IdentifierInfo &II, Scope *S) {
  11862. // Find the scope in which the identifier is injected and the corresponding
  11863. // DeclContext.
  11864. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  11865. // In that case, we inject the declaration into the translation unit scope
  11866. // instead.
  11867. Scope *BlockScope = S;
  11868. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  11869. BlockScope = BlockScope->getParent();
  11870. Scope *ContextScope = BlockScope;
  11871. while (!ContextScope->getEntity())
  11872. ContextScope = ContextScope->getParent();
  11873. ContextRAII SavedContext(*this, ContextScope->getEntity());
  11874. // Before we produce a declaration for an implicitly defined
  11875. // function, see whether there was a locally-scoped declaration of
  11876. // this name as a function or variable. If so, use that
  11877. // (non-visible) declaration, and complain about it.
  11878. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  11879. if (ExternCPrev) {
  11880. // We still need to inject the function into the enclosing block scope so
  11881. // that later (non-call) uses can see it.
  11882. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  11883. // C89 footnote 38:
  11884. // If in fact it is not defined as having type "function returning int",
  11885. // the behavior is undefined.
  11886. if (!isa<FunctionDecl>(ExternCPrev) ||
  11887. !Context.typesAreCompatible(
  11888. cast<FunctionDecl>(ExternCPrev)->getType(),
  11889. Context.getFunctionNoProtoType(Context.IntTy))) {
  11890. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  11891. << ExternCPrev << !getLangOpts().C99;
  11892. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11893. return ExternCPrev;
  11894. }
  11895. }
  11896. // Extension in C99. Legal in C90, but warn about it.
  11897. unsigned diag_id;
  11898. if (II.getName().startswith("__builtin_"))
  11899. diag_id = diag::warn_builtin_unknown;
  11900. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  11901. else if (getLangOpts().OpenCL)
  11902. diag_id = diag::err_opencl_implicit_function_decl;
  11903. else if (getLangOpts().C99)
  11904. diag_id = diag::ext_implicit_function_decl;
  11905. else
  11906. diag_id = diag::warn_implicit_function_decl;
  11907. Diag(Loc, diag_id) << &II;
  11908. // If we found a prior declaration of this function, don't bother building
  11909. // another one. We've already pushed that one into scope, so there's nothing
  11910. // more to do.
  11911. if (ExternCPrev)
  11912. return ExternCPrev;
  11913. // Because typo correction is expensive, only do it if the implicit
  11914. // function declaration is going to be treated as an error.
  11915. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  11916. TypoCorrection Corrected;
  11917. if (S &&
  11918. (Corrected = CorrectTypo(
  11919. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  11920. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  11921. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  11922. /*ErrorRecovery*/false);
  11923. }
  11924. // Set a Declarator for the implicit definition: int foo();
  11925. const char *Dummy;
  11926. AttributeFactory attrFactory;
  11927. DeclSpec DS(attrFactory);
  11928. unsigned DiagID;
  11929. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  11930. Context.getPrintingPolicy());
  11931. (void)Error; // Silence warning.
  11932. assert(!Error && "Error setting up implicit decl!");
  11933. SourceLocation NoLoc;
  11934. Declarator D(DS, DeclaratorContext::BlockContext);
  11935. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  11936. /*IsAmbiguous=*/false,
  11937. /*LParenLoc=*/NoLoc,
  11938. /*Params=*/nullptr,
  11939. /*NumParams=*/0,
  11940. /*EllipsisLoc=*/NoLoc,
  11941. /*RParenLoc=*/NoLoc,
  11942. /*RefQualifierIsLvalueRef=*/true,
  11943. /*RefQualifierLoc=*/NoLoc,
  11944. /*MutableLoc=*/NoLoc, EST_None,
  11945. /*ESpecRange=*/SourceRange(),
  11946. /*Exceptions=*/nullptr,
  11947. /*ExceptionRanges=*/nullptr,
  11948. /*NumExceptions=*/0,
  11949. /*NoexceptExpr=*/nullptr,
  11950. /*ExceptionSpecTokens=*/nullptr,
  11951. /*DeclsInPrototype=*/None, Loc,
  11952. Loc, D),
  11953. std::move(DS.getAttributes()), SourceLocation());
  11954. D.SetIdentifier(&II, Loc);
  11955. // Insert this function into the enclosing block scope.
  11956. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  11957. FD->setImplicit();
  11958. AddKnownFunctionAttributes(FD);
  11959. return FD;
  11960. }
  11961. /// Adds any function attributes that we know a priori based on
  11962. /// the declaration of this function.
  11963. ///
  11964. /// These attributes can apply both to implicitly-declared builtins
  11965. /// (like __builtin___printf_chk) or to library-declared functions
  11966. /// like NSLog or printf.
  11967. ///
  11968. /// We need to check for duplicate attributes both here and where user-written
  11969. /// attributes are applied to declarations.
  11970. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  11971. if (FD->isInvalidDecl())
  11972. return;
  11973. // If this is a built-in function, map its builtin attributes to
  11974. // actual attributes.
  11975. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11976. // Handle printf-formatting attributes.
  11977. unsigned FormatIdx;
  11978. bool HasVAListArg;
  11979. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  11980. if (!FD->hasAttr<FormatAttr>()) {
  11981. const char *fmt = "printf";
  11982. unsigned int NumParams = FD->getNumParams();
  11983. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  11984. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  11985. fmt = "NSString";
  11986. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11987. &Context.Idents.get(fmt),
  11988. FormatIdx+1,
  11989. HasVAListArg ? 0 : FormatIdx+2,
  11990. FD->getLocation()));
  11991. }
  11992. }
  11993. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  11994. HasVAListArg)) {
  11995. if (!FD->hasAttr<FormatAttr>())
  11996. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11997. &Context.Idents.get("scanf"),
  11998. FormatIdx+1,
  11999. HasVAListArg ? 0 : FormatIdx+2,
  12000. FD->getLocation()));
  12001. }
  12002. // Handle automatically recognized callbacks.
  12003. SmallVector<int, 4> Encoding;
  12004. if (!FD->hasAttr<CallbackAttr>() &&
  12005. Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
  12006. FD->addAttr(CallbackAttr::CreateImplicit(
  12007. Context, Encoding.data(), Encoding.size(), FD->getLocation()));
  12008. // Mark const if we don't care about errno and that is the only thing
  12009. // preventing the function from being const. This allows IRgen to use LLVM
  12010. // intrinsics for such functions.
  12011. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  12012. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  12013. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12014. // We make "fma" on some platforms const because we know it does not set
  12015. // errno in those environments even though it could set errno based on the
  12016. // C standard.
  12017. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  12018. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  12019. !FD->hasAttr<ConstAttr>()) {
  12020. switch (BuiltinID) {
  12021. case Builtin::BI__builtin_fma:
  12022. case Builtin::BI__builtin_fmaf:
  12023. case Builtin::BI__builtin_fmal:
  12024. case Builtin::BIfma:
  12025. case Builtin::BIfmaf:
  12026. case Builtin::BIfmal:
  12027. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12028. break;
  12029. default:
  12030. break;
  12031. }
  12032. }
  12033. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  12034. !FD->hasAttr<ReturnsTwiceAttr>())
  12035. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  12036. FD->getLocation()));
  12037. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  12038. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12039. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  12040. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  12041. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  12042. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  12043. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  12044. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  12045. // Add the appropriate attribute, depending on the CUDA compilation mode
  12046. // and which target the builtin belongs to. For example, during host
  12047. // compilation, aux builtins are __device__, while the rest are __host__.
  12048. if (getLangOpts().CUDAIsDevice !=
  12049. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  12050. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  12051. else
  12052. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  12053. }
  12054. }
  12055. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  12056. // throw, add an implicit nothrow attribute to any extern "C" function we come
  12057. // across.
  12058. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  12059. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  12060. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  12061. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  12062. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  12063. }
  12064. IdentifierInfo *Name = FD->getIdentifier();
  12065. if (!Name)
  12066. return;
  12067. if ((!getLangOpts().CPlusPlus &&
  12068. FD->getDeclContext()->isTranslationUnit()) ||
  12069. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  12070. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  12071. LinkageSpecDecl::lang_c)) {
  12072. // Okay: this could be a libc/libm/Objective-C function we know
  12073. // about.
  12074. } else
  12075. return;
  12076. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  12077. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  12078. // target-specific builtins, perhaps?
  12079. if (!FD->hasAttr<FormatAttr>())
  12080. FD->addAttr(FormatAttr::CreateImplicit(Context,
  12081. &Context.Idents.get("printf"), 2,
  12082. Name->isStr("vasprintf") ? 0 : 3,
  12083. FD->getLocation()));
  12084. }
  12085. if (Name->isStr("__CFStringMakeConstantString")) {
  12086. // We already have a __builtin___CFStringMakeConstantString,
  12087. // but builds that use -fno-constant-cfstrings don't go through that.
  12088. if (!FD->hasAttr<FormatArgAttr>())
  12089. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  12090. FD->getLocation()));
  12091. }
  12092. }
  12093. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  12094. TypeSourceInfo *TInfo) {
  12095. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  12096. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  12097. if (!TInfo) {
  12098. assert(D.isInvalidType() && "no declarator info for valid type");
  12099. TInfo = Context.getTrivialTypeSourceInfo(T);
  12100. }
  12101. // Scope manipulation handled by caller.
  12102. TypedefDecl *NewTD =
  12103. TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
  12104. D.getIdentifierLoc(), D.getIdentifier(), TInfo);
  12105. // Bail out immediately if we have an invalid declaration.
  12106. if (D.isInvalidType()) {
  12107. NewTD->setInvalidDecl();
  12108. return NewTD;
  12109. }
  12110. if (D.getDeclSpec().isModulePrivateSpecified()) {
  12111. if (CurContext->isFunctionOrMethod())
  12112. Diag(NewTD->getLocation(), diag::err_module_private_local)
  12113. << 2 << NewTD->getDeclName()
  12114. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  12115. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  12116. else
  12117. NewTD->setModulePrivate();
  12118. }
  12119. // C++ [dcl.typedef]p8:
  12120. // If the typedef declaration defines an unnamed class (or
  12121. // enum), the first typedef-name declared by the declaration
  12122. // to be that class type (or enum type) is used to denote the
  12123. // class type (or enum type) for linkage purposes only.
  12124. // We need to check whether the type was declared in the declaration.
  12125. switch (D.getDeclSpec().getTypeSpecType()) {
  12126. case TST_enum:
  12127. case TST_struct:
  12128. case TST_interface:
  12129. case TST_union:
  12130. case TST_class: {
  12131. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  12132. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  12133. break;
  12134. }
  12135. default:
  12136. break;
  12137. }
  12138. return NewTD;
  12139. }
  12140. /// Check that this is a valid underlying type for an enum declaration.
  12141. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  12142. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  12143. QualType T = TI->getType();
  12144. if (T->isDependentType())
  12145. return false;
  12146. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  12147. if (BT->isInteger())
  12148. return false;
  12149. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  12150. return true;
  12151. }
  12152. /// Check whether this is a valid redeclaration of a previous enumeration.
  12153. /// \return true if the redeclaration was invalid.
  12154. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  12155. QualType EnumUnderlyingTy, bool IsFixed,
  12156. const EnumDecl *Prev) {
  12157. if (IsScoped != Prev->isScoped()) {
  12158. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  12159. << Prev->isScoped();
  12160. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12161. return true;
  12162. }
  12163. if (IsFixed && Prev->isFixed()) {
  12164. if (!EnumUnderlyingTy->isDependentType() &&
  12165. !Prev->getIntegerType()->isDependentType() &&
  12166. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  12167. Prev->getIntegerType())) {
  12168. // TODO: Highlight the underlying type of the redeclaration.
  12169. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  12170. << EnumUnderlyingTy << Prev->getIntegerType();
  12171. Diag(Prev->getLocation(), diag::note_previous_declaration)
  12172. << Prev->getIntegerTypeRange();
  12173. return true;
  12174. }
  12175. } else if (IsFixed != Prev->isFixed()) {
  12176. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  12177. << Prev->isFixed();
  12178. Diag(Prev->getLocation(), diag::note_previous_declaration);
  12179. return true;
  12180. }
  12181. return false;
  12182. }
  12183. /// Get diagnostic %select index for tag kind for
  12184. /// redeclaration diagnostic message.
  12185. /// WARNING: Indexes apply to particular diagnostics only!
  12186. ///
  12187. /// \returns diagnostic %select index.
  12188. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  12189. switch (Tag) {
  12190. case TTK_Struct: return 0;
  12191. case TTK_Interface: return 1;
  12192. case TTK_Class: return 2;
  12193. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  12194. }
  12195. }
  12196. /// Determine if tag kind is a class-key compatible with
  12197. /// class for redeclaration (class, struct, or __interface).
  12198. ///
  12199. /// \returns true iff the tag kind is compatible.
  12200. static bool isClassCompatTagKind(TagTypeKind Tag)
  12201. {
  12202. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  12203. }
  12204. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  12205. TagTypeKind TTK) {
  12206. if (isa<TypedefDecl>(PrevDecl))
  12207. return NTK_Typedef;
  12208. else if (isa<TypeAliasDecl>(PrevDecl))
  12209. return NTK_TypeAlias;
  12210. else if (isa<ClassTemplateDecl>(PrevDecl))
  12211. return NTK_Template;
  12212. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  12213. return NTK_TypeAliasTemplate;
  12214. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  12215. return NTK_TemplateTemplateArgument;
  12216. switch (TTK) {
  12217. case TTK_Struct:
  12218. case TTK_Interface:
  12219. case TTK_Class:
  12220. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  12221. case TTK_Union:
  12222. return NTK_NonUnion;
  12223. case TTK_Enum:
  12224. return NTK_NonEnum;
  12225. }
  12226. llvm_unreachable("invalid TTK");
  12227. }
  12228. /// Determine whether a tag with a given kind is acceptable
  12229. /// as a redeclaration of the given tag declaration.
  12230. ///
  12231. /// \returns true if the new tag kind is acceptable, false otherwise.
  12232. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  12233. TagTypeKind NewTag, bool isDefinition,
  12234. SourceLocation NewTagLoc,
  12235. const IdentifierInfo *Name) {
  12236. // C++ [dcl.type.elab]p3:
  12237. // The class-key or enum keyword present in the
  12238. // elaborated-type-specifier shall agree in kind with the
  12239. // declaration to which the name in the elaborated-type-specifier
  12240. // refers. This rule also applies to the form of
  12241. // elaborated-type-specifier that declares a class-name or
  12242. // friend class since it can be construed as referring to the
  12243. // definition of the class. Thus, in any
  12244. // elaborated-type-specifier, the enum keyword shall be used to
  12245. // refer to an enumeration (7.2), the union class-key shall be
  12246. // used to refer to a union (clause 9), and either the class or
  12247. // struct class-key shall be used to refer to a class (clause 9)
  12248. // declared using the class or struct class-key.
  12249. TagTypeKind OldTag = Previous->getTagKind();
  12250. if (OldTag != NewTag &&
  12251. !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
  12252. return false;
  12253. // Tags are compatible, but we might still want to warn on mismatched tags.
  12254. // Non-class tags can't be mismatched at this point.
  12255. if (!isClassCompatTagKind(NewTag))
  12256. return true;
  12257. // Declarations for which -Wmismatched-tags is disabled are entirely ignored
  12258. // by our warning analysis. We don't want to warn about mismatches with (eg)
  12259. // declarations in system headers that are designed to be specialized, but if
  12260. // a user asks us to warn, we should warn if their code contains mismatched
  12261. // declarations.
  12262. auto IsIgnoredLoc = [&](SourceLocation Loc) {
  12263. return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
  12264. Loc);
  12265. };
  12266. if (IsIgnoredLoc(NewTagLoc))
  12267. return true;
  12268. auto IsIgnored = [&](const TagDecl *Tag) {
  12269. return IsIgnoredLoc(Tag->getLocation());
  12270. };
  12271. while (IsIgnored(Previous)) {
  12272. Previous = Previous->getPreviousDecl();
  12273. if (!Previous)
  12274. return true;
  12275. OldTag = Previous->getTagKind();
  12276. }
  12277. bool isTemplate = false;
  12278. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  12279. isTemplate = Record->getDescribedClassTemplate();
  12280. if (inTemplateInstantiation()) {
  12281. if (OldTag != NewTag) {
  12282. // In a template instantiation, do not offer fix-its for tag mismatches
  12283. // since they usually mess up the template instead of fixing the problem.
  12284. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12285. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12286. << getRedeclDiagFromTagKind(OldTag);
  12287. // FIXME: Note previous location?
  12288. }
  12289. return true;
  12290. }
  12291. if (isDefinition) {
  12292. // On definitions, check all previous tags and issue a fix-it for each
  12293. // one that doesn't match the current tag.
  12294. if (Previous->getDefinition()) {
  12295. // Don't suggest fix-its for redefinitions.
  12296. return true;
  12297. }
  12298. bool previousMismatch = false;
  12299. for (const TagDecl *I : Previous->redecls()) {
  12300. if (I->getTagKind() != NewTag) {
  12301. // Ignore previous declarations for which the warning was disabled.
  12302. if (IsIgnored(I))
  12303. continue;
  12304. if (!previousMismatch) {
  12305. previousMismatch = true;
  12306. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  12307. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12308. << getRedeclDiagFromTagKind(I->getTagKind());
  12309. }
  12310. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  12311. << getRedeclDiagFromTagKind(NewTag)
  12312. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  12313. TypeWithKeyword::getTagTypeKindName(NewTag));
  12314. }
  12315. }
  12316. return true;
  12317. }
  12318. // Identify the prevailing tag kind: this is the kind of the definition (if
  12319. // there is a non-ignored definition), or otherwise the kind of the prior
  12320. // (non-ignored) declaration.
  12321. const TagDecl *PrevDef = Previous->getDefinition();
  12322. if (PrevDef && IsIgnored(PrevDef))
  12323. PrevDef = nullptr;
  12324. const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
  12325. if (Redecl->getTagKind() != NewTag) {
  12326. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  12327. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  12328. << getRedeclDiagFromTagKind(OldTag);
  12329. Diag(Redecl->getLocation(), diag::note_previous_use);
  12330. // If there is a previous definition, suggest a fix-it.
  12331. if (PrevDef) {
  12332. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  12333. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  12334. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  12335. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  12336. }
  12337. }
  12338. return true;
  12339. }
  12340. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  12341. /// from an outer enclosing namespace or file scope inside a friend declaration.
  12342. /// This should provide the commented out code in the following snippet:
  12343. /// namespace N {
  12344. /// struct X;
  12345. /// namespace M {
  12346. /// struct Y { friend struct /*N::*/ X; };
  12347. /// }
  12348. /// }
  12349. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  12350. SourceLocation NameLoc) {
  12351. // While the decl is in a namespace, do repeated lookup of that name and see
  12352. // if we get the same namespace back. If we do not, continue until
  12353. // translation unit scope, at which point we have a fully qualified NNS.
  12354. SmallVector<IdentifierInfo *, 4> Namespaces;
  12355. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12356. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  12357. // This tag should be declared in a namespace, which can only be enclosed by
  12358. // other namespaces. Bail if there's an anonymous namespace in the chain.
  12359. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  12360. if (!Namespace || Namespace->isAnonymousNamespace())
  12361. return FixItHint();
  12362. IdentifierInfo *II = Namespace->getIdentifier();
  12363. Namespaces.push_back(II);
  12364. NamedDecl *Lookup = SemaRef.LookupSingleName(
  12365. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  12366. if (Lookup == Namespace)
  12367. break;
  12368. }
  12369. // Once we have all the namespaces, reverse them to go outermost first, and
  12370. // build an NNS.
  12371. SmallString<64> Insertion;
  12372. llvm::raw_svector_ostream OS(Insertion);
  12373. if (DC->isTranslationUnit())
  12374. OS << "::";
  12375. std::reverse(Namespaces.begin(), Namespaces.end());
  12376. for (auto *II : Namespaces)
  12377. OS << II->getName() << "::";
  12378. return FixItHint::CreateInsertion(NameLoc, Insertion);
  12379. }
  12380. /// Determine whether a tag originally declared in context \p OldDC can
  12381. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  12382. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  12383. /// using-declaration).
  12384. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  12385. DeclContext *NewDC) {
  12386. OldDC = OldDC->getRedeclContext();
  12387. NewDC = NewDC->getRedeclContext();
  12388. if (OldDC->Equals(NewDC))
  12389. return true;
  12390. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  12391. // encloses the other).
  12392. if (S.getLangOpts().MSVCCompat &&
  12393. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  12394. return true;
  12395. return false;
  12396. }
  12397. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  12398. /// former case, Name will be non-null. In the later case, Name will be null.
  12399. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  12400. /// reference/declaration/definition of a tag.
  12401. ///
  12402. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  12403. /// trailing-type-specifier) other than one in an alias-declaration.
  12404. ///
  12405. /// \param SkipBody If non-null, will be set to indicate if the caller should
  12406. /// skip the definition of this tag and treat it as if it were a declaration.
  12407. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  12408. SourceLocation KWLoc, CXXScopeSpec &SS,
  12409. IdentifierInfo *Name, SourceLocation NameLoc,
  12410. const ParsedAttributesView &Attrs, AccessSpecifier AS,
  12411. SourceLocation ModulePrivateLoc,
  12412. MultiTemplateParamsArg TemplateParameterLists,
  12413. bool &OwnedDecl, bool &IsDependent,
  12414. SourceLocation ScopedEnumKWLoc,
  12415. bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
  12416. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12417. SkipBodyInfo *SkipBody) {
  12418. // If this is not a definition, it must have a name.
  12419. IdentifierInfo *OrigName = Name;
  12420. assert((Name != nullptr || TUK == TUK_Definition) &&
  12421. "Nameless record must be a definition!");
  12422. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12423. OwnedDecl = false;
  12424. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12425. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12426. // FIXME: Check member specializations more carefully.
  12427. bool isMemberSpecialization = false;
  12428. bool Invalid = false;
  12429. // We only need to do this matching if we have template parameters
  12430. // or a scope specifier, which also conveniently avoids this work
  12431. // for non-C++ cases.
  12432. if (TemplateParameterLists.size() > 0 ||
  12433. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12434. if (TemplateParameterList *TemplateParams =
  12435. MatchTemplateParametersToScopeSpecifier(
  12436. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12437. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12438. if (Kind == TTK_Enum) {
  12439. Diag(KWLoc, diag::err_enum_template);
  12440. return nullptr;
  12441. }
  12442. if (TemplateParams->size() > 0) {
  12443. // This is a declaration or definition of a class template (which may
  12444. // be a member of another template).
  12445. if (Invalid)
  12446. return nullptr;
  12447. OwnedDecl = false;
  12448. DeclResult Result = CheckClassTemplate(
  12449. S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
  12450. AS, ModulePrivateLoc,
  12451. /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
  12452. TemplateParameterLists.data(), SkipBody);
  12453. return Result.get();
  12454. } else {
  12455. // The "template<>" header is extraneous.
  12456. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12457. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12458. isMemberSpecialization = true;
  12459. }
  12460. }
  12461. }
  12462. // Figure out the underlying type if this a enum declaration. We need to do
  12463. // this early, because it's needed to detect if this is an incompatible
  12464. // redeclaration.
  12465. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12466. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12467. if (Kind == TTK_Enum) {
  12468. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12469. // No underlying type explicitly specified, or we failed to parse the
  12470. // type, default to int.
  12471. EnumUnderlying = Context.IntTy.getTypePtr();
  12472. } else if (UnderlyingType.get()) {
  12473. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12474. // integral type; any cv-qualification is ignored.
  12475. TypeSourceInfo *TI = nullptr;
  12476. GetTypeFromParser(UnderlyingType.get(), &TI);
  12477. EnumUnderlying = TI;
  12478. if (CheckEnumUnderlyingType(TI))
  12479. // Recover by falling back to int.
  12480. EnumUnderlying = Context.IntTy.getTypePtr();
  12481. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12482. UPPC_FixedUnderlyingType))
  12483. EnumUnderlying = Context.IntTy.getTypePtr();
  12484. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12485. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12486. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12487. // the underlying type unless the user enables -fms-compatibility. This
  12488. // makes unfixed forward declared enums incomplete and is more conforming.
  12489. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12490. EnumUnderlying = Context.IntTy.getTypePtr();
  12491. }
  12492. }
  12493. DeclContext *SearchDC = CurContext;
  12494. DeclContext *DC = CurContext;
  12495. bool isStdBadAlloc = false;
  12496. bool isStdAlignValT = false;
  12497. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12498. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12499. Redecl = NotForRedeclaration;
  12500. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12501. /// implemented asks for structural equivalence checking, the returned decl
  12502. /// here is passed back to the parser, allowing the tag body to be parsed.
  12503. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12504. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12505. // If there is an identifier, use the location of the identifier as the
  12506. // location of the decl, otherwise use the location of the struct/union
  12507. // keyword.
  12508. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12509. TagDecl *New = nullptr;
  12510. if (Kind == TTK_Enum) {
  12511. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12512. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12513. // If this is an undefined enum, bail.
  12514. if (TUK != TUK_Definition && !Invalid)
  12515. return nullptr;
  12516. if (EnumUnderlying) {
  12517. EnumDecl *ED = cast<EnumDecl>(New);
  12518. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12519. ED->setIntegerTypeSourceInfo(TI);
  12520. else
  12521. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12522. ED->setPromotionType(ED->getIntegerType());
  12523. }
  12524. } else { // struct/union
  12525. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12526. nullptr);
  12527. }
  12528. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12529. // Add alignment attributes if necessary; these attributes are checked
  12530. // when the ASTContext lays out the structure.
  12531. //
  12532. // It is important for implementing the correct semantics that this
  12533. // happen here (in ActOnTag). The #pragma pack stack is
  12534. // maintained as a result of parser callbacks which can occur at
  12535. // many points during the parsing of a struct declaration (because
  12536. // the #pragma tokens are effectively skipped over during the
  12537. // parsing of the struct).
  12538. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  12539. AddAlignmentAttributesForRecord(RD);
  12540. AddMsStructLayoutForRecord(RD);
  12541. }
  12542. }
  12543. New->setLexicalDeclContext(CurContext);
  12544. return New;
  12545. };
  12546. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12547. if (Name && SS.isNotEmpty()) {
  12548. // We have a nested-name tag ('struct foo::bar').
  12549. // Check for invalid 'foo::'.
  12550. if (SS.isInvalid()) {
  12551. Name = nullptr;
  12552. goto CreateNewDecl;
  12553. }
  12554. // If this is a friend or a reference to a class in a dependent
  12555. // context, don't try to make a decl for it.
  12556. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12557. DC = computeDeclContext(SS, false);
  12558. if (!DC) {
  12559. IsDependent = true;
  12560. return nullptr;
  12561. }
  12562. } else {
  12563. DC = computeDeclContext(SS, true);
  12564. if (!DC) {
  12565. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12566. << SS.getRange();
  12567. return nullptr;
  12568. }
  12569. }
  12570. if (RequireCompleteDeclContext(SS, DC))
  12571. return nullptr;
  12572. SearchDC = DC;
  12573. // Look-up name inside 'foo::'.
  12574. LookupQualifiedName(Previous, DC);
  12575. if (Previous.isAmbiguous())
  12576. return nullptr;
  12577. if (Previous.empty()) {
  12578. // Name lookup did not find anything. However, if the
  12579. // nested-name-specifier refers to the current instantiation,
  12580. // and that current instantiation has any dependent base
  12581. // classes, we might find something at instantiation time: treat
  12582. // this as a dependent elaborated-type-specifier.
  12583. // But this only makes any sense for reference-like lookups.
  12584. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12585. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12586. IsDependent = true;
  12587. return nullptr;
  12588. }
  12589. // A tag 'foo::bar' must already exist.
  12590. Diag(NameLoc, diag::err_not_tag_in_scope)
  12591. << Kind << Name << DC << SS.getRange();
  12592. Name = nullptr;
  12593. Invalid = true;
  12594. goto CreateNewDecl;
  12595. }
  12596. } else if (Name) {
  12597. // C++14 [class.mem]p14:
  12598. // If T is the name of a class, then each of the following shall have a
  12599. // name different from T:
  12600. // -- every member of class T that is itself a type
  12601. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12602. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12603. return nullptr;
  12604. // If this is a named struct, check to see if there was a previous forward
  12605. // declaration or definition.
  12606. // FIXME: We're looking into outer scopes here, even when we
  12607. // shouldn't be. Doing so can result in ambiguities that we
  12608. // shouldn't be diagnosing.
  12609. LookupName(Previous, S);
  12610. // When declaring or defining a tag, ignore ambiguities introduced
  12611. // by types using'ed into this scope.
  12612. if (Previous.isAmbiguous() &&
  12613. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  12614. LookupResult::Filter F = Previous.makeFilter();
  12615. while (F.hasNext()) {
  12616. NamedDecl *ND = F.next();
  12617. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  12618. SearchDC->getRedeclContext()))
  12619. F.erase();
  12620. }
  12621. F.done();
  12622. }
  12623. // C++11 [namespace.memdef]p3:
  12624. // If the name in a friend declaration is neither qualified nor
  12625. // a template-id and the declaration is a function or an
  12626. // elaborated-type-specifier, the lookup to determine whether
  12627. // the entity has been previously declared shall not consider
  12628. // any scopes outside the innermost enclosing namespace.
  12629. //
  12630. // MSVC doesn't implement the above rule for types, so a friend tag
  12631. // declaration may be a redeclaration of a type declared in an enclosing
  12632. // scope. They do implement this rule for friend functions.
  12633. //
  12634. // Does it matter that this should be by scope instead of by
  12635. // semantic context?
  12636. if (!Previous.empty() && TUK == TUK_Friend) {
  12637. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  12638. LookupResult::Filter F = Previous.makeFilter();
  12639. bool FriendSawTagOutsideEnclosingNamespace = false;
  12640. while (F.hasNext()) {
  12641. NamedDecl *ND = F.next();
  12642. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12643. if (DC->isFileContext() &&
  12644. !EnclosingNS->Encloses(ND->getDeclContext())) {
  12645. if (getLangOpts().MSVCCompat)
  12646. FriendSawTagOutsideEnclosingNamespace = true;
  12647. else
  12648. F.erase();
  12649. }
  12650. }
  12651. F.done();
  12652. // Diagnose this MSVC extension in the easy case where lookup would have
  12653. // unambiguously found something outside the enclosing namespace.
  12654. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  12655. NamedDecl *ND = Previous.getFoundDecl();
  12656. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  12657. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  12658. }
  12659. }
  12660. // Note: there used to be some attempt at recovery here.
  12661. if (Previous.isAmbiguous())
  12662. return nullptr;
  12663. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  12664. // FIXME: This makes sure that we ignore the contexts associated
  12665. // with C structs, unions, and enums when looking for a matching
  12666. // tag declaration or definition. See the similar lookup tweak
  12667. // in Sema::LookupName; is there a better way to deal with this?
  12668. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  12669. SearchDC = SearchDC->getParent();
  12670. }
  12671. }
  12672. if (Previous.isSingleResult() &&
  12673. Previous.getFoundDecl()->isTemplateParameter()) {
  12674. // Maybe we will complain about the shadowed template parameter.
  12675. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  12676. // Just pretend that we didn't see the previous declaration.
  12677. Previous.clear();
  12678. }
  12679. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  12680. DC->Equals(getStdNamespace())) {
  12681. if (Name->isStr("bad_alloc")) {
  12682. // This is a declaration of or a reference to "std::bad_alloc".
  12683. isStdBadAlloc = true;
  12684. // If std::bad_alloc has been implicitly declared (but made invisible to
  12685. // name lookup), fill in this implicit declaration as the previous
  12686. // declaration, so that the declarations get chained appropriately.
  12687. if (Previous.empty() && StdBadAlloc)
  12688. Previous.addDecl(getStdBadAlloc());
  12689. } else if (Name->isStr("align_val_t")) {
  12690. isStdAlignValT = true;
  12691. if (Previous.empty() && StdAlignValT)
  12692. Previous.addDecl(getStdAlignValT());
  12693. }
  12694. }
  12695. // If we didn't find a previous declaration, and this is a reference
  12696. // (or friend reference), move to the correct scope. In C++, we
  12697. // also need to do a redeclaration lookup there, just in case
  12698. // there's a shadow friend decl.
  12699. if (Name && Previous.empty() &&
  12700. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12701. if (Invalid) goto CreateNewDecl;
  12702. assert(SS.isEmpty());
  12703. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12704. // C++ [basic.scope.pdecl]p5:
  12705. // -- for an elaborated-type-specifier of the form
  12706. //
  12707. // class-key identifier
  12708. //
  12709. // if the elaborated-type-specifier is used in the
  12710. // decl-specifier-seq or parameter-declaration-clause of a
  12711. // function defined in namespace scope, the identifier is
  12712. // declared as a class-name in the namespace that contains
  12713. // the declaration; otherwise, except as a friend
  12714. // declaration, the identifier is declared in the smallest
  12715. // non-class, non-function-prototype scope that contains the
  12716. // declaration.
  12717. //
  12718. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12719. // C structs and unions.
  12720. //
  12721. // It is an error in C++ to declare (rather than define) an enum
  12722. // type, including via an elaborated type specifier. We'll
  12723. // diagnose that later; for now, declare the enum in the same
  12724. // scope as we would have picked for any other tag type.
  12725. //
  12726. // GNU C also supports this behavior as part of its incomplete
  12727. // enum types extension, while GNU C++ does not.
  12728. //
  12729. // Find the context where we'll be declaring the tag.
  12730. // FIXME: We would like to maintain the current DeclContext as the
  12731. // lexical context,
  12732. SearchDC = getTagInjectionContext(SearchDC);
  12733. // Find the scope where we'll be declaring the tag.
  12734. S = getTagInjectionScope(S, getLangOpts());
  12735. } else {
  12736. assert(TUK == TUK_Friend);
  12737. // C++ [namespace.memdef]p3:
  12738. // If a friend declaration in a non-local class first declares a
  12739. // class or function, the friend class or function is a member of
  12740. // the innermost enclosing namespace.
  12741. SearchDC = SearchDC->getEnclosingNamespaceContext();
  12742. }
  12743. // In C++, we need to do a redeclaration lookup to properly
  12744. // diagnose some problems.
  12745. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  12746. // hidden declaration so that we don't get ambiguity errors when using a
  12747. // type declared by an elaborated-type-specifier. In C that is not correct
  12748. // and we should instead merge compatible types found by lookup.
  12749. if (getLangOpts().CPlusPlus) {
  12750. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12751. LookupQualifiedName(Previous, SearchDC);
  12752. } else {
  12753. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12754. LookupName(Previous, S);
  12755. }
  12756. }
  12757. // If we have a known previous declaration to use, then use it.
  12758. if (Previous.empty() && SkipBody && SkipBody->Previous)
  12759. Previous.addDecl(SkipBody->Previous);
  12760. if (!Previous.empty()) {
  12761. NamedDecl *PrevDecl = Previous.getFoundDecl();
  12762. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  12763. // It's okay to have a tag decl in the same scope as a typedef
  12764. // which hides a tag decl in the same scope. Finding this
  12765. // insanity with a redeclaration lookup can only actually happen
  12766. // in C++.
  12767. //
  12768. // This is also okay for elaborated-type-specifiers, which is
  12769. // technically forbidden by the current standard but which is
  12770. // okay according to the likely resolution of an open issue;
  12771. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  12772. if (getLangOpts().CPlusPlus) {
  12773. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12774. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12775. TagDecl *Tag = TT->getDecl();
  12776. if (Tag->getDeclName() == Name &&
  12777. Tag->getDeclContext()->getRedeclContext()
  12778. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12779. PrevDecl = Tag;
  12780. Previous.clear();
  12781. Previous.addDecl(Tag);
  12782. Previous.resolveKind();
  12783. }
  12784. }
  12785. }
  12786. }
  12787. // If this is a redeclaration of a using shadow declaration, it must
  12788. // declare a tag in the same context. In MSVC mode, we allow a
  12789. // redefinition if either context is within the other.
  12790. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12791. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12792. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12793. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12794. !(OldTag && isAcceptableTagRedeclContext(
  12795. *this, OldTag->getDeclContext(), SearchDC))) {
  12796. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12797. Diag(Shadow->getTargetDecl()->getLocation(),
  12798. diag::note_using_decl_target);
  12799. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12800. << 0;
  12801. // Recover by ignoring the old declaration.
  12802. Previous.clear();
  12803. goto CreateNewDecl;
  12804. }
  12805. }
  12806. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12807. // If this is a use of a previous tag, or if the tag is already declared
  12808. // in the same scope (so that the definition/declaration completes or
  12809. // rementions the tag), reuse the decl.
  12810. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12811. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12812. SS.isNotEmpty() || isMemberSpecialization)) {
  12813. // Make sure that this wasn't declared as an enum and now used as a
  12814. // struct or something similar.
  12815. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12816. TUK == TUK_Definition, KWLoc,
  12817. Name)) {
  12818. bool SafeToContinue
  12819. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12820. Kind != TTK_Enum);
  12821. if (SafeToContinue)
  12822. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12823. << Name
  12824. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12825. PrevTagDecl->getKindName());
  12826. else
  12827. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12828. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12829. if (SafeToContinue)
  12830. Kind = PrevTagDecl->getTagKind();
  12831. else {
  12832. // Recover by making this an anonymous redefinition.
  12833. Name = nullptr;
  12834. Previous.clear();
  12835. Invalid = true;
  12836. }
  12837. }
  12838. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12839. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12840. // If this is an elaborated-type-specifier for a scoped enumeration,
  12841. // the 'class' keyword is not necessary and not permitted.
  12842. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12843. if (ScopedEnum)
  12844. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12845. << PrevEnum->isScoped()
  12846. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12847. return PrevTagDecl;
  12848. }
  12849. QualType EnumUnderlyingTy;
  12850. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12851. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12852. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12853. EnumUnderlyingTy = QualType(T, 0);
  12854. // All conflicts with previous declarations are recovered by
  12855. // returning the previous declaration, unless this is a definition,
  12856. // in which case we want the caller to bail out.
  12857. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12858. ScopedEnum, EnumUnderlyingTy,
  12859. IsFixed, PrevEnum))
  12860. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12861. }
  12862. // C++11 [class.mem]p1:
  12863. // A member shall not be declared twice in the member-specification,
  12864. // except that a nested class or member class template can be declared
  12865. // and then later defined.
  12866. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12867. S->isDeclScope(PrevDecl)) {
  12868. Diag(NameLoc, diag::ext_member_redeclared);
  12869. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12870. }
  12871. if (!Invalid) {
  12872. // If this is a use, just return the declaration we found, unless
  12873. // we have attributes.
  12874. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12875. if (!Attrs.empty()) {
  12876. // FIXME: Diagnose these attributes. For now, we create a new
  12877. // declaration to hold them.
  12878. } else if (TUK == TUK_Reference &&
  12879. (PrevTagDecl->getFriendObjectKind() ==
  12880. Decl::FOK_Undeclared ||
  12881. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12882. SS.isEmpty()) {
  12883. // This declaration is a reference to an existing entity, but
  12884. // has different visibility from that entity: it either makes
  12885. // a friend visible or it makes a type visible in a new module.
  12886. // In either case, create a new declaration. We only do this if
  12887. // the declaration would have meant the same thing if no prior
  12888. // declaration were found, that is, if it was found in the same
  12889. // scope where we would have injected a declaration.
  12890. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12891. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12892. return PrevTagDecl;
  12893. // This is in the injected scope, create a new declaration in
  12894. // that scope.
  12895. S = getTagInjectionScope(S, getLangOpts());
  12896. } else {
  12897. return PrevTagDecl;
  12898. }
  12899. }
  12900. // Diagnose attempts to redefine a tag.
  12901. if (TUK == TUK_Definition) {
  12902. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  12903. // If we're defining a specialization and the previous definition
  12904. // is from an implicit instantiation, don't emit an error
  12905. // here; we'll catch this in the general case below.
  12906. bool IsExplicitSpecializationAfterInstantiation = false;
  12907. if (isMemberSpecialization) {
  12908. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  12909. IsExplicitSpecializationAfterInstantiation =
  12910. RD->getTemplateSpecializationKind() !=
  12911. TSK_ExplicitSpecialization;
  12912. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  12913. IsExplicitSpecializationAfterInstantiation =
  12914. ED->getTemplateSpecializationKind() !=
  12915. TSK_ExplicitSpecialization;
  12916. }
  12917. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  12918. // not keep more that one definition around (merge them). However,
  12919. // ensure the decl passes the structural compatibility check in
  12920. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  12921. NamedDecl *Hidden = nullptr;
  12922. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  12923. // There is a definition of this tag, but it is not visible. We
  12924. // explicitly make use of C++'s one definition rule here, and
  12925. // assume that this definition is identical to the hidden one
  12926. // we already have. Make the existing definition visible and
  12927. // use it in place of this one.
  12928. if (!getLangOpts().CPlusPlus) {
  12929. // Postpone making the old definition visible until after we
  12930. // complete parsing the new one and do the structural
  12931. // comparison.
  12932. SkipBody->CheckSameAsPrevious = true;
  12933. SkipBody->New = createTagFromNewDecl();
  12934. SkipBody->Previous = Def;
  12935. return Def;
  12936. } else {
  12937. SkipBody->ShouldSkip = true;
  12938. SkipBody->Previous = Def;
  12939. makeMergedDefinitionVisible(Hidden);
  12940. // Carry on and handle it like a normal definition. We'll
  12941. // skip starting the definitiion later.
  12942. }
  12943. } else if (!IsExplicitSpecializationAfterInstantiation) {
  12944. // A redeclaration in function prototype scope in C isn't
  12945. // visible elsewhere, so merely issue a warning.
  12946. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  12947. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  12948. else
  12949. Diag(NameLoc, diag::err_redefinition) << Name;
  12950. notePreviousDefinition(Def,
  12951. NameLoc.isValid() ? NameLoc : KWLoc);
  12952. // If this is a redefinition, recover by making this
  12953. // struct be anonymous, which will make any later
  12954. // references get the previous definition.
  12955. Name = nullptr;
  12956. Previous.clear();
  12957. Invalid = true;
  12958. }
  12959. } else {
  12960. // If the type is currently being defined, complain
  12961. // about a nested redefinition.
  12962. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  12963. if (TD->isBeingDefined()) {
  12964. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  12965. Diag(PrevTagDecl->getLocation(),
  12966. diag::note_previous_definition);
  12967. Name = nullptr;
  12968. Previous.clear();
  12969. Invalid = true;
  12970. }
  12971. }
  12972. // Okay, this is definition of a previously declared or referenced
  12973. // tag. We're going to create a new Decl for it.
  12974. }
  12975. // Okay, we're going to make a redeclaration. If this is some kind
  12976. // of reference, make sure we build the redeclaration in the same DC
  12977. // as the original, and ignore the current access specifier.
  12978. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12979. SearchDC = PrevTagDecl->getDeclContext();
  12980. AS = AS_none;
  12981. }
  12982. }
  12983. // If we get here we have (another) forward declaration or we
  12984. // have a definition. Just create a new decl.
  12985. } else {
  12986. // If we get here, this is a definition of a new tag type in a nested
  12987. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  12988. // new decl/type. We set PrevDecl to NULL so that the entities
  12989. // have distinct types.
  12990. Previous.clear();
  12991. }
  12992. // If we get here, we're going to create a new Decl. If PrevDecl
  12993. // is non-NULL, it's a definition of the tag declared by
  12994. // PrevDecl. If it's NULL, we have a new definition.
  12995. // Otherwise, PrevDecl is not a tag, but was found with tag
  12996. // lookup. This is only actually possible in C++, where a few
  12997. // things like templates still live in the tag namespace.
  12998. } else {
  12999. // Use a better diagnostic if an elaborated-type-specifier
  13000. // found the wrong kind of type on the first
  13001. // (non-redeclaration) lookup.
  13002. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  13003. !Previous.isForRedeclaration()) {
  13004. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13005. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  13006. << Kind;
  13007. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  13008. Invalid = true;
  13009. // Otherwise, only diagnose if the declaration is in scope.
  13010. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  13011. SS.isNotEmpty() || isMemberSpecialization)) {
  13012. // do nothing
  13013. // Diagnose implicit declarations introduced by elaborated types.
  13014. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  13015. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  13016. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  13017. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13018. Invalid = true;
  13019. // Otherwise it's a declaration. Call out a particularly common
  13020. // case here.
  13021. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  13022. unsigned Kind = 0;
  13023. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  13024. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  13025. << Name << Kind << TND->getUnderlyingType();
  13026. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  13027. Invalid = true;
  13028. // Otherwise, diagnose.
  13029. } else {
  13030. // The tag name clashes with something else in the target scope,
  13031. // issue an error and recover by making this tag be anonymous.
  13032. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  13033. notePreviousDefinition(PrevDecl, NameLoc);
  13034. Name = nullptr;
  13035. Invalid = true;
  13036. }
  13037. // The existing declaration isn't relevant to us; we're in a
  13038. // new scope, so clear out the previous declaration.
  13039. Previous.clear();
  13040. }
  13041. }
  13042. CreateNewDecl:
  13043. TagDecl *PrevDecl = nullptr;
  13044. if (Previous.isSingleResult())
  13045. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  13046. // If there is an identifier, use the location of the identifier as the
  13047. // location of the decl, otherwise use the location of the struct/union
  13048. // keyword.
  13049. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  13050. // Otherwise, create a new declaration. If there is a previous
  13051. // declaration of the same entity, the two will be linked via
  13052. // PrevDecl.
  13053. TagDecl *New;
  13054. if (Kind == TTK_Enum) {
  13055. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13056. // enum X { A, B, C } D; D should chain to X.
  13057. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  13058. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  13059. ScopedEnumUsesClassTag, IsFixed);
  13060. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  13061. StdAlignValT = cast<EnumDecl>(New);
  13062. // If this is an undefined enum, warn.
  13063. if (TUK != TUK_Definition && !Invalid) {
  13064. TagDecl *Def;
  13065. if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
  13066. // C++0x: 7.2p2: opaque-enum-declaration.
  13067. // Conflicts are diagnosed above. Do nothing.
  13068. }
  13069. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  13070. Diag(Loc, diag::ext_forward_ref_enum_def)
  13071. << New;
  13072. Diag(Def->getLocation(), diag::note_previous_definition);
  13073. } else {
  13074. unsigned DiagID = diag::ext_forward_ref_enum;
  13075. if (getLangOpts().MSVCCompat)
  13076. DiagID = diag::ext_ms_forward_ref_enum;
  13077. else if (getLangOpts().CPlusPlus)
  13078. DiagID = diag::err_forward_ref_enum;
  13079. Diag(Loc, DiagID);
  13080. }
  13081. }
  13082. if (EnumUnderlying) {
  13083. EnumDecl *ED = cast<EnumDecl>(New);
  13084. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  13085. ED->setIntegerTypeSourceInfo(TI);
  13086. else
  13087. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  13088. ED->setPromotionType(ED->getIntegerType());
  13089. assert(ED->isComplete() && "enum with type should be complete");
  13090. }
  13091. } else {
  13092. // struct/union/class
  13093. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  13094. // struct X { int A; } D; D should chain to X.
  13095. if (getLangOpts().CPlusPlus) {
  13096. // FIXME: Look for a way to use RecordDecl for simple structs.
  13097. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13098. cast_or_null<CXXRecordDecl>(PrevDecl));
  13099. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  13100. StdBadAlloc = cast<CXXRecordDecl>(New);
  13101. } else
  13102. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  13103. cast_or_null<RecordDecl>(PrevDecl));
  13104. }
  13105. // C++11 [dcl.type]p3:
  13106. // A type-specifier-seq shall not define a class or enumeration [...].
  13107. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  13108. TUK == TUK_Definition) {
  13109. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  13110. << Context.getTagDeclType(New);
  13111. Invalid = true;
  13112. }
  13113. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  13114. DC->getDeclKind() == Decl::Enum) {
  13115. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  13116. << Context.getTagDeclType(New);
  13117. Invalid = true;
  13118. }
  13119. // Maybe add qualifier info.
  13120. if (SS.isNotEmpty()) {
  13121. if (SS.isSet()) {
  13122. // If this is either a declaration or a definition, check the
  13123. // nested-name-specifier against the current context.
  13124. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  13125. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  13126. isMemberSpecialization))
  13127. Invalid = true;
  13128. New->setQualifierInfo(SS.getWithLocInContext(Context));
  13129. if (TemplateParameterLists.size() > 0) {
  13130. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  13131. }
  13132. }
  13133. else
  13134. Invalid = true;
  13135. }
  13136. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  13137. // Add alignment attributes if necessary; these attributes are checked when
  13138. // the ASTContext lays out the structure.
  13139. //
  13140. // It is important for implementing the correct semantics that this
  13141. // happen here (in ActOnTag). The #pragma pack stack is
  13142. // maintained as a result of parser callbacks which can occur at
  13143. // many points during the parsing of a struct declaration (because
  13144. // the #pragma tokens are effectively skipped over during the
  13145. // parsing of the struct).
  13146. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
  13147. AddAlignmentAttributesForRecord(RD);
  13148. AddMsStructLayoutForRecord(RD);
  13149. }
  13150. }
  13151. if (ModulePrivateLoc.isValid()) {
  13152. if (isMemberSpecialization)
  13153. Diag(New->getLocation(), diag::err_module_private_specialization)
  13154. << 2
  13155. << FixItHint::CreateRemoval(ModulePrivateLoc);
  13156. // __module_private__ does not apply to local classes. However, we only
  13157. // diagnose this as an error when the declaration specifiers are
  13158. // freestanding. Here, we just ignore the __module_private__.
  13159. else if (!SearchDC->isFunctionOrMethod())
  13160. New->setModulePrivate();
  13161. }
  13162. // If this is a specialization of a member class (of a class template),
  13163. // check the specialization.
  13164. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  13165. Invalid = true;
  13166. // If we're declaring or defining a tag in function prototype scope in C,
  13167. // note that this type can only be used within the function and add it to
  13168. // the list of decls to inject into the function definition scope.
  13169. if ((Name || Kind == TTK_Enum) &&
  13170. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  13171. if (getLangOpts().CPlusPlus) {
  13172. // C++ [dcl.fct]p6:
  13173. // Types shall not be defined in return or parameter types.
  13174. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  13175. Diag(Loc, diag::err_type_defined_in_param_type)
  13176. << Name;
  13177. Invalid = true;
  13178. }
  13179. } else if (!PrevDecl) {
  13180. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  13181. }
  13182. }
  13183. if (Invalid)
  13184. New->setInvalidDecl();
  13185. // Set the lexical context. If the tag has a C++ scope specifier, the
  13186. // lexical context will be different from the semantic context.
  13187. New->setLexicalDeclContext(CurContext);
  13188. // Mark this as a friend decl if applicable.
  13189. // In Microsoft mode, a friend declaration also acts as a forward
  13190. // declaration so we always pass true to setObjectOfFriendDecl to make
  13191. // the tag name visible.
  13192. if (TUK == TUK_Friend)
  13193. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  13194. // Set the access specifier.
  13195. if (!Invalid && SearchDC->isRecord())
  13196. SetMemberAccessSpecifier(New, PrevDecl, AS);
  13197. if (PrevDecl)
  13198. CheckRedeclarationModuleOwnership(New, PrevDecl);
  13199. if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
  13200. New->startDefinition();
  13201. ProcessDeclAttributeList(S, New, Attrs);
  13202. AddPragmaAttributes(S, New);
  13203. // If this has an identifier, add it to the scope stack.
  13204. if (TUK == TUK_Friend) {
  13205. // We might be replacing an existing declaration in the lookup tables;
  13206. // if so, borrow its access specifier.
  13207. if (PrevDecl)
  13208. New->setAccess(PrevDecl->getAccess());
  13209. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  13210. DC->makeDeclVisibleInContext(New);
  13211. if (Name) // can be null along some error paths
  13212. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  13213. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  13214. } else if (Name) {
  13215. S = getNonFieldDeclScope(S);
  13216. PushOnScopeChains(New, S, true);
  13217. } else {
  13218. CurContext->addDecl(New);
  13219. }
  13220. // If this is the C FILE type, notify the AST context.
  13221. if (IdentifierInfo *II = New->getIdentifier())
  13222. if (!New->isInvalidDecl() &&
  13223. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  13224. II->isStr("FILE"))
  13225. Context.setFILEDecl(New);
  13226. if (PrevDecl)
  13227. mergeDeclAttributes(New, PrevDecl);
  13228. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13229. // record.
  13230. AddPushedVisibilityAttribute(New);
  13231. if (isMemberSpecialization && !New->isInvalidDecl())
  13232. CompleteMemberSpecialization(New, Previous);
  13233. OwnedDecl = true;
  13234. // In C++, don't return an invalid declaration. We can't recover well from
  13235. // the cases where we make the type anonymous.
  13236. if (Invalid && getLangOpts().CPlusPlus) {
  13237. if (New->isBeingDefined())
  13238. if (auto RD = dyn_cast<RecordDecl>(New))
  13239. RD->completeDefinition();
  13240. return nullptr;
  13241. } else if (SkipBody && SkipBody->ShouldSkip) {
  13242. return SkipBody->Previous;
  13243. } else {
  13244. return New;
  13245. }
  13246. }
  13247. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  13248. AdjustDeclIfTemplate(TagD);
  13249. TagDecl *Tag = cast<TagDecl>(TagD);
  13250. // Enter the tag context.
  13251. PushDeclContext(S, Tag);
  13252. ActOnDocumentableDecl(TagD);
  13253. // If there's a #pragma GCC visibility in scope, set the visibility of this
  13254. // record.
  13255. AddPushedVisibilityAttribute(Tag);
  13256. }
  13257. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  13258. SkipBodyInfo &SkipBody) {
  13259. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  13260. return false;
  13261. // Make the previous decl visible.
  13262. makeMergedDefinitionVisible(SkipBody.Previous);
  13263. return true;
  13264. }
  13265. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  13266. assert(isa<ObjCContainerDecl>(IDecl) &&
  13267. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  13268. DeclContext *OCD = cast<DeclContext>(IDecl);
  13269. assert(getContainingDC(OCD) == CurContext &&
  13270. "The next DeclContext should be lexically contained in the current one.");
  13271. CurContext = OCD;
  13272. return IDecl;
  13273. }
  13274. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  13275. SourceLocation FinalLoc,
  13276. bool IsFinalSpelledSealed,
  13277. SourceLocation LBraceLoc) {
  13278. AdjustDeclIfTemplate(TagD);
  13279. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  13280. FieldCollector->StartClass();
  13281. if (!Record->getIdentifier())
  13282. return;
  13283. if (FinalLoc.isValid())
  13284. Record->addAttr(new (Context)
  13285. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  13286. // C++ [class]p2:
  13287. // [...] The class-name is also inserted into the scope of the
  13288. // class itself; this is known as the injected-class-name. For
  13289. // purposes of access checking, the injected-class-name is treated
  13290. // as if it were a public member name.
  13291. CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
  13292. Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
  13293. Record->getLocation(), Record->getIdentifier(),
  13294. /*PrevDecl=*/nullptr,
  13295. /*DelayTypeCreation=*/true);
  13296. Context.getTypeDeclType(InjectedClassName, Record);
  13297. InjectedClassName->setImplicit();
  13298. InjectedClassName->setAccess(AS_public);
  13299. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  13300. InjectedClassName->setDescribedClassTemplate(Template);
  13301. PushOnScopeChains(InjectedClassName, S);
  13302. assert(InjectedClassName->isInjectedClassName() &&
  13303. "Broken injected-class-name");
  13304. }
  13305. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  13306. SourceRange BraceRange) {
  13307. AdjustDeclIfTemplate(TagD);
  13308. TagDecl *Tag = cast<TagDecl>(TagD);
  13309. Tag->setBraceRange(BraceRange);
  13310. // Make sure we "complete" the definition even it is invalid.
  13311. if (Tag->isBeingDefined()) {
  13312. assert(Tag->isInvalidDecl() && "We should already have completed it");
  13313. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13314. RD->completeDefinition();
  13315. }
  13316. if (isa<CXXRecordDecl>(Tag)) {
  13317. FieldCollector->FinishClass();
  13318. }
  13319. // Exit this scope of this tag's definition.
  13320. PopDeclContext();
  13321. if (getCurLexicalContext()->isObjCContainer() &&
  13322. Tag->getDeclContext()->isFileContext())
  13323. Tag->setTopLevelDeclInObjCContainer();
  13324. // Notify the consumer that we've defined a tag.
  13325. if (!Tag->isInvalidDecl())
  13326. Consumer.HandleTagDeclDefinition(Tag);
  13327. }
  13328. void Sema::ActOnObjCContainerFinishDefinition() {
  13329. // Exit this scope of this interface definition.
  13330. PopDeclContext();
  13331. }
  13332. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  13333. assert(DC == CurContext && "Mismatch of container contexts");
  13334. OriginalLexicalContext = DC;
  13335. ActOnObjCContainerFinishDefinition();
  13336. }
  13337. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  13338. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  13339. OriginalLexicalContext = nullptr;
  13340. }
  13341. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  13342. AdjustDeclIfTemplate(TagD);
  13343. TagDecl *Tag = cast<TagDecl>(TagD);
  13344. Tag->setInvalidDecl();
  13345. // Make sure we "complete" the definition even it is invalid.
  13346. if (Tag->isBeingDefined()) {
  13347. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  13348. RD->completeDefinition();
  13349. }
  13350. // We're undoing ActOnTagStartDefinition here, not
  13351. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  13352. // the FieldCollector.
  13353. PopDeclContext();
  13354. }
  13355. // Note that FieldName may be null for anonymous bitfields.
  13356. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  13357. IdentifierInfo *FieldName,
  13358. QualType FieldTy, bool IsMsStruct,
  13359. Expr *BitWidth, bool *ZeroWidth) {
  13360. // Default to true; that shouldn't confuse checks for emptiness
  13361. if (ZeroWidth)
  13362. *ZeroWidth = true;
  13363. // C99 6.7.2.1p4 - verify the field type.
  13364. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  13365. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  13366. // Handle incomplete types with specific error.
  13367. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  13368. return ExprError();
  13369. if (FieldName)
  13370. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  13371. << FieldName << FieldTy << BitWidth->getSourceRange();
  13372. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  13373. << FieldTy << BitWidth->getSourceRange();
  13374. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  13375. UPPC_BitFieldWidth))
  13376. return ExprError();
  13377. // If the bit-width is type- or value-dependent, don't try to check
  13378. // it now.
  13379. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  13380. return BitWidth;
  13381. llvm::APSInt Value;
  13382. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  13383. if (ICE.isInvalid())
  13384. return ICE;
  13385. BitWidth = ICE.get();
  13386. if (Value != 0 && ZeroWidth)
  13387. *ZeroWidth = false;
  13388. // Zero-width bitfield is ok for anonymous field.
  13389. if (Value == 0 && FieldName)
  13390. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  13391. if (Value.isSigned() && Value.isNegative()) {
  13392. if (FieldName)
  13393. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  13394. << FieldName << Value.toString(10);
  13395. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  13396. << Value.toString(10);
  13397. }
  13398. if (!FieldTy->isDependentType()) {
  13399. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  13400. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  13401. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  13402. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  13403. // ABI.
  13404. bool CStdConstraintViolation =
  13405. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13406. bool MSBitfieldViolation =
  13407. Value.ugt(TypeStorageSize) &&
  13408. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13409. if (CStdConstraintViolation || MSBitfieldViolation) {
  13410. unsigned DiagWidth =
  13411. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13412. if (FieldName)
  13413. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13414. << FieldName << (unsigned)Value.getZExtValue()
  13415. << !CStdConstraintViolation << DiagWidth;
  13416. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13417. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13418. << DiagWidth;
  13419. }
  13420. // Warn on types where the user might conceivably expect to get all
  13421. // specified bits as value bits: that's all integral types other than
  13422. // 'bool'.
  13423. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13424. if (FieldName)
  13425. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13426. << FieldName << (unsigned)Value.getZExtValue()
  13427. << (unsigned)TypeWidth;
  13428. else
  13429. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13430. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13431. }
  13432. }
  13433. return BitWidth;
  13434. }
  13435. /// ActOnField - Each field of a C struct/union is passed into this in order
  13436. /// to create a FieldDecl object for it.
  13437. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13438. Declarator &D, Expr *BitfieldWidth) {
  13439. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13440. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13441. /*InitStyle=*/ICIS_NoInit, AS_public);
  13442. return Res;
  13443. }
  13444. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13445. ///
  13446. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13447. SourceLocation DeclStart,
  13448. Declarator &D, Expr *BitWidth,
  13449. InClassInitStyle InitStyle,
  13450. AccessSpecifier AS) {
  13451. if (D.isDecompositionDeclarator()) {
  13452. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13453. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13454. << Decomp.getSourceRange();
  13455. return nullptr;
  13456. }
  13457. IdentifierInfo *II = D.getIdentifier();
  13458. SourceLocation Loc = DeclStart;
  13459. if (II) Loc = D.getIdentifierLoc();
  13460. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13461. QualType T = TInfo->getType();
  13462. if (getLangOpts().CPlusPlus) {
  13463. CheckExtraCXXDefaultArguments(D);
  13464. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13465. UPPC_DataMemberType)) {
  13466. D.setInvalidType();
  13467. T = Context.IntTy;
  13468. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13469. }
  13470. }
  13471. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13472. if (D.getDeclSpec().isInlineSpecified())
  13473. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13474. << getLangOpts().CPlusPlus17;
  13475. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13476. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13477. diag::err_invalid_thread)
  13478. << DeclSpec::getSpecifierName(TSCS);
  13479. // Check to see if this name was declared as a member previously
  13480. NamedDecl *PrevDecl = nullptr;
  13481. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13482. ForVisibleRedeclaration);
  13483. LookupName(Previous, S);
  13484. switch (Previous.getResultKind()) {
  13485. case LookupResult::Found:
  13486. case LookupResult::FoundUnresolvedValue:
  13487. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13488. break;
  13489. case LookupResult::FoundOverloaded:
  13490. PrevDecl = Previous.getRepresentativeDecl();
  13491. break;
  13492. case LookupResult::NotFound:
  13493. case LookupResult::NotFoundInCurrentInstantiation:
  13494. case LookupResult::Ambiguous:
  13495. break;
  13496. }
  13497. Previous.suppressDiagnostics();
  13498. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13499. // Maybe we will complain about the shadowed template parameter.
  13500. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13501. // Just pretend that we didn't see the previous declaration.
  13502. PrevDecl = nullptr;
  13503. }
  13504. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13505. PrevDecl = nullptr;
  13506. bool Mutable
  13507. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13508. SourceLocation TSSL = D.getBeginLoc();
  13509. FieldDecl *NewFD
  13510. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13511. TSSL, AS, PrevDecl, &D);
  13512. if (NewFD->isInvalidDecl())
  13513. Record->setInvalidDecl();
  13514. if (D.getDeclSpec().isModulePrivateSpecified())
  13515. NewFD->setModulePrivate();
  13516. if (NewFD->isInvalidDecl() && PrevDecl) {
  13517. // Don't introduce NewFD into scope; there's already something
  13518. // with the same name in the same scope.
  13519. } else if (II) {
  13520. PushOnScopeChains(NewFD, S);
  13521. } else
  13522. Record->addDecl(NewFD);
  13523. return NewFD;
  13524. }
  13525. /// Build a new FieldDecl and check its well-formedness.
  13526. ///
  13527. /// This routine builds a new FieldDecl given the fields name, type,
  13528. /// record, etc. \p PrevDecl should refer to any previous declaration
  13529. /// with the same name and in the same scope as the field to be
  13530. /// created.
  13531. ///
  13532. /// \returns a new FieldDecl.
  13533. ///
  13534. /// \todo The Declarator argument is a hack. It will be removed once
  13535. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13536. TypeSourceInfo *TInfo,
  13537. RecordDecl *Record, SourceLocation Loc,
  13538. bool Mutable, Expr *BitWidth,
  13539. InClassInitStyle InitStyle,
  13540. SourceLocation TSSL,
  13541. AccessSpecifier AS, NamedDecl *PrevDecl,
  13542. Declarator *D) {
  13543. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13544. bool InvalidDecl = false;
  13545. if (D) InvalidDecl = D->isInvalidType();
  13546. // If we receive a broken type, recover by assuming 'int' and
  13547. // marking this declaration as invalid.
  13548. if (T.isNull()) {
  13549. InvalidDecl = true;
  13550. T = Context.IntTy;
  13551. }
  13552. QualType EltTy = Context.getBaseElementType(T);
  13553. if (!EltTy->isDependentType()) {
  13554. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13555. // Fields of incomplete type force their record to be invalid.
  13556. Record->setInvalidDecl();
  13557. InvalidDecl = true;
  13558. } else {
  13559. NamedDecl *Def;
  13560. EltTy->isIncompleteType(&Def);
  13561. if (Def && Def->isInvalidDecl()) {
  13562. Record->setInvalidDecl();
  13563. InvalidDecl = true;
  13564. }
  13565. }
  13566. }
  13567. // TR 18037 does not allow fields to be declared with address space
  13568. if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
  13569. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13570. Diag(Loc, diag::err_field_with_address_space);
  13571. Record->setInvalidDecl();
  13572. InvalidDecl = true;
  13573. }
  13574. if (LangOpts.OpenCL) {
  13575. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13576. // used as structure or union field: image, sampler, event or block types.
  13577. if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
  13578. T->isBlockPointerType()) {
  13579. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13580. Record->setInvalidDecl();
  13581. InvalidDecl = true;
  13582. }
  13583. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13584. if (BitWidth) {
  13585. Diag(Loc, diag::err_opencl_bitfields);
  13586. InvalidDecl = true;
  13587. }
  13588. }
  13589. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13590. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13591. T.hasQualifiers()) {
  13592. InvalidDecl = true;
  13593. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13594. }
  13595. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13596. // than a variably modified type.
  13597. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13598. bool SizeIsNegative;
  13599. llvm::APSInt Oversized;
  13600. TypeSourceInfo *FixedTInfo =
  13601. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13602. SizeIsNegative,
  13603. Oversized);
  13604. if (FixedTInfo) {
  13605. Diag(Loc, diag::warn_illegal_constant_array_size);
  13606. TInfo = FixedTInfo;
  13607. T = FixedTInfo->getType();
  13608. } else {
  13609. if (SizeIsNegative)
  13610. Diag(Loc, diag::err_typecheck_negative_array_size);
  13611. else if (Oversized.getBoolValue())
  13612. Diag(Loc, diag::err_array_too_large)
  13613. << Oversized.toString(10);
  13614. else
  13615. Diag(Loc, diag::err_typecheck_field_variable_size);
  13616. InvalidDecl = true;
  13617. }
  13618. }
  13619. // Fields can not have abstract class types
  13620. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  13621. diag::err_abstract_type_in_decl,
  13622. AbstractFieldType))
  13623. InvalidDecl = true;
  13624. bool ZeroWidth = false;
  13625. if (InvalidDecl)
  13626. BitWidth = nullptr;
  13627. // If this is declared as a bit-field, check the bit-field.
  13628. if (BitWidth) {
  13629. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  13630. &ZeroWidth).get();
  13631. if (!BitWidth) {
  13632. InvalidDecl = true;
  13633. BitWidth = nullptr;
  13634. ZeroWidth = false;
  13635. }
  13636. }
  13637. // Check that 'mutable' is consistent with the type of the declaration.
  13638. if (!InvalidDecl && Mutable) {
  13639. unsigned DiagID = 0;
  13640. if (T->isReferenceType())
  13641. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  13642. : diag::err_mutable_reference;
  13643. else if (T.isConstQualified())
  13644. DiagID = diag::err_mutable_const;
  13645. if (DiagID) {
  13646. SourceLocation ErrLoc = Loc;
  13647. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  13648. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  13649. Diag(ErrLoc, DiagID);
  13650. if (DiagID != diag::ext_mutable_reference) {
  13651. Mutable = false;
  13652. InvalidDecl = true;
  13653. }
  13654. }
  13655. }
  13656. // C++11 [class.union]p8 (DR1460):
  13657. // At most one variant member of a union may have a
  13658. // brace-or-equal-initializer.
  13659. if (InitStyle != ICIS_NoInit)
  13660. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  13661. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  13662. BitWidth, Mutable, InitStyle);
  13663. if (InvalidDecl)
  13664. NewFD->setInvalidDecl();
  13665. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  13666. Diag(Loc, diag::err_duplicate_member) << II;
  13667. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13668. NewFD->setInvalidDecl();
  13669. }
  13670. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  13671. if (Record->isUnion()) {
  13672. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13673. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13674. if (RDecl->getDefinition()) {
  13675. // C++ [class.union]p1: An object of a class with a non-trivial
  13676. // constructor, a non-trivial copy constructor, a non-trivial
  13677. // destructor, or a non-trivial copy assignment operator
  13678. // cannot be a member of a union, nor can an array of such
  13679. // objects.
  13680. if (CheckNontrivialField(NewFD))
  13681. NewFD->setInvalidDecl();
  13682. }
  13683. }
  13684. // C++ [class.union]p1: If a union contains a member of reference type,
  13685. // the program is ill-formed, except when compiling with MSVC extensions
  13686. // enabled.
  13687. if (EltTy->isReferenceType()) {
  13688. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13689. diag::ext_union_member_of_reference_type :
  13690. diag::err_union_member_of_reference_type)
  13691. << NewFD->getDeclName() << EltTy;
  13692. if (!getLangOpts().MicrosoftExt)
  13693. NewFD->setInvalidDecl();
  13694. }
  13695. }
  13696. }
  13697. // FIXME: We need to pass in the attributes given an AST
  13698. // representation, not a parser representation.
  13699. if (D) {
  13700. // FIXME: The current scope is almost... but not entirely... correct here.
  13701. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13702. if (NewFD->hasAttrs())
  13703. CheckAlignasUnderalignment(NewFD);
  13704. }
  13705. // In auto-retain/release, infer strong retension for fields of
  13706. // retainable type.
  13707. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13708. NewFD->setInvalidDecl();
  13709. if (T.isObjCGCWeak())
  13710. Diag(Loc, diag::warn_attribute_weak_on_field);
  13711. NewFD->setAccess(AS);
  13712. return NewFD;
  13713. }
  13714. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13715. assert(FD);
  13716. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13717. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13718. return false;
  13719. QualType EltTy = Context.getBaseElementType(FD->getType());
  13720. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13721. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13722. if (RDecl->getDefinition()) {
  13723. // We check for copy constructors before constructors
  13724. // because otherwise we'll never get complaints about
  13725. // copy constructors.
  13726. CXXSpecialMember member = CXXInvalid;
  13727. // We're required to check for any non-trivial constructors. Since the
  13728. // implicit default constructor is suppressed if there are any
  13729. // user-declared constructors, we just need to check that there is a
  13730. // trivial default constructor and a trivial copy constructor. (We don't
  13731. // worry about move constructors here, since this is a C++98 check.)
  13732. if (RDecl->hasNonTrivialCopyConstructor())
  13733. member = CXXCopyConstructor;
  13734. else if (!RDecl->hasTrivialDefaultConstructor())
  13735. member = CXXDefaultConstructor;
  13736. else if (RDecl->hasNonTrivialCopyAssignment())
  13737. member = CXXCopyAssignment;
  13738. else if (RDecl->hasNonTrivialDestructor())
  13739. member = CXXDestructor;
  13740. if (member != CXXInvalid) {
  13741. if (!getLangOpts().CPlusPlus11 &&
  13742. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  13743. // Objective-C++ ARC: it is an error to have a non-trivial field of
  13744. // a union. However, system headers in Objective-C programs
  13745. // occasionally have Objective-C lifetime objects within unions,
  13746. // and rather than cause the program to fail, we make those
  13747. // members unavailable.
  13748. SourceLocation Loc = FD->getLocation();
  13749. if (getSourceManager().isInSystemHeader(Loc)) {
  13750. if (!FD->hasAttr<UnavailableAttr>())
  13751. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13752. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  13753. return false;
  13754. }
  13755. }
  13756. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  13757. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  13758. diag::err_illegal_union_or_anon_struct_member)
  13759. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  13760. DiagnoseNontrivial(RDecl, member);
  13761. return !getLangOpts().CPlusPlus11;
  13762. }
  13763. }
  13764. }
  13765. return false;
  13766. }
  13767. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  13768. /// AST enum value.
  13769. static ObjCIvarDecl::AccessControl
  13770. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  13771. switch (ivarVisibility) {
  13772. default: llvm_unreachable("Unknown visitibility kind");
  13773. case tok::objc_private: return ObjCIvarDecl::Private;
  13774. case tok::objc_public: return ObjCIvarDecl::Public;
  13775. case tok::objc_protected: return ObjCIvarDecl::Protected;
  13776. case tok::objc_package: return ObjCIvarDecl::Package;
  13777. }
  13778. }
  13779. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  13780. /// in order to create an IvarDecl object for it.
  13781. Decl *Sema::ActOnIvar(Scope *S,
  13782. SourceLocation DeclStart,
  13783. Declarator &D, Expr *BitfieldWidth,
  13784. tok::ObjCKeywordKind Visibility) {
  13785. IdentifierInfo *II = D.getIdentifier();
  13786. Expr *BitWidth = (Expr*)BitfieldWidth;
  13787. SourceLocation Loc = DeclStart;
  13788. if (II) Loc = D.getIdentifierLoc();
  13789. // FIXME: Unnamed fields can be handled in various different ways, for
  13790. // example, unnamed unions inject all members into the struct namespace!
  13791. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13792. QualType T = TInfo->getType();
  13793. if (BitWidth) {
  13794. // 6.7.2.1p3, 6.7.2.1p4
  13795. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13796. if (!BitWidth)
  13797. D.setInvalidType();
  13798. } else {
  13799. // Not a bitfield.
  13800. // validate II.
  13801. }
  13802. if (T->isReferenceType()) {
  13803. Diag(Loc, diag::err_ivar_reference_type);
  13804. D.setInvalidType();
  13805. }
  13806. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13807. // than a variably modified type.
  13808. else if (T->isVariablyModifiedType()) {
  13809. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13810. D.setInvalidType();
  13811. }
  13812. // Get the visibility (access control) for this ivar.
  13813. ObjCIvarDecl::AccessControl ac =
  13814. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13815. : ObjCIvarDecl::None;
  13816. // Must set ivar's DeclContext to its enclosing interface.
  13817. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13818. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13819. return nullptr;
  13820. ObjCContainerDecl *EnclosingContext;
  13821. if (ObjCImplementationDecl *IMPDecl =
  13822. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13823. if (LangOpts.ObjCRuntime.isFragile()) {
  13824. // Case of ivar declared in an implementation. Context is that of its class.
  13825. EnclosingContext = IMPDecl->getClassInterface();
  13826. assert(EnclosingContext && "Implementation has no class interface!");
  13827. }
  13828. else
  13829. EnclosingContext = EnclosingDecl;
  13830. } else {
  13831. if (ObjCCategoryDecl *CDecl =
  13832. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13833. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13834. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13835. return nullptr;
  13836. }
  13837. }
  13838. EnclosingContext = EnclosingDecl;
  13839. }
  13840. // Construct the decl.
  13841. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13842. DeclStart, Loc, II, T,
  13843. TInfo, ac, (Expr *)BitfieldWidth);
  13844. if (II) {
  13845. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13846. ForVisibleRedeclaration);
  13847. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13848. && !isa<TagDecl>(PrevDecl)) {
  13849. Diag(Loc, diag::err_duplicate_member) << II;
  13850. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13851. NewID->setInvalidDecl();
  13852. }
  13853. }
  13854. // Process attributes attached to the ivar.
  13855. ProcessDeclAttributes(S, NewID, D);
  13856. if (D.isInvalidType())
  13857. NewID->setInvalidDecl();
  13858. // In ARC, infer 'retaining' for ivars of retainable type.
  13859. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13860. NewID->setInvalidDecl();
  13861. if (D.getDeclSpec().isModulePrivateSpecified())
  13862. NewID->setModulePrivate();
  13863. if (II) {
  13864. // FIXME: When interfaces are DeclContexts, we'll need to add
  13865. // these to the interface.
  13866. S->AddDecl(NewID);
  13867. IdResolver.AddDecl(NewID);
  13868. }
  13869. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13870. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13871. Diag(Loc, diag::warn_ivars_in_interface);
  13872. return NewID;
  13873. }
  13874. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13875. /// class and class extensions. For every class \@interface and class
  13876. /// extension \@interface, if the last ivar is a bitfield of any type,
  13877. /// then add an implicit `char :0` ivar to the end of that interface.
  13878. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13879. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13880. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13881. return;
  13882. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13883. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13884. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  13885. return;
  13886. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13887. if (!ID) {
  13888. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13889. if (!CD->IsClassExtension())
  13890. return;
  13891. }
  13892. // No need to add this to end of @implementation.
  13893. else
  13894. return;
  13895. }
  13896. // All conditions are met. Add a new bitfield to the tail end of ivars.
  13897. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  13898. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  13899. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  13900. DeclLoc, DeclLoc, nullptr,
  13901. Context.CharTy,
  13902. Context.getTrivialTypeSourceInfo(Context.CharTy,
  13903. DeclLoc),
  13904. ObjCIvarDecl::Private, BW,
  13905. true);
  13906. AllIvarDecls.push_back(Ivar);
  13907. }
  13908. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  13909. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  13910. SourceLocation RBrac,
  13911. const ParsedAttributesView &Attrs) {
  13912. assert(EnclosingDecl && "missing record or interface decl");
  13913. // If this is an Objective-C @implementation or category and we have
  13914. // new fields here we should reset the layout of the interface since
  13915. // it will now change.
  13916. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  13917. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  13918. switch (DC->getKind()) {
  13919. default: break;
  13920. case Decl::ObjCCategory:
  13921. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  13922. break;
  13923. case Decl::ObjCImplementation:
  13924. Context.
  13925. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  13926. break;
  13927. }
  13928. }
  13929. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  13930. CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
  13931. // Start counting up the number of named members; make sure to include
  13932. // members of anonymous structs and unions in the total.
  13933. unsigned NumNamedMembers = 0;
  13934. if (Record) {
  13935. for (const auto *I : Record->decls()) {
  13936. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  13937. if (IFD->getDeclName())
  13938. ++NumNamedMembers;
  13939. }
  13940. }
  13941. // Verify that all the fields are okay.
  13942. SmallVector<FieldDecl*, 32> RecFields;
  13943. bool ObjCFieldLifetimeErrReported = false;
  13944. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  13945. i != end; ++i) {
  13946. FieldDecl *FD = cast<FieldDecl>(*i);
  13947. // Get the type for the field.
  13948. const Type *FDTy = FD->getType().getTypePtr();
  13949. if (!FD->isAnonymousStructOrUnion()) {
  13950. // Remember all fields written by the user.
  13951. RecFields.push_back(FD);
  13952. }
  13953. // If the field is already invalid for some reason, don't emit more
  13954. // diagnostics about it.
  13955. if (FD->isInvalidDecl()) {
  13956. EnclosingDecl->setInvalidDecl();
  13957. continue;
  13958. }
  13959. // C99 6.7.2.1p2:
  13960. // A structure or union shall not contain a member with
  13961. // incomplete or function type (hence, a structure shall not
  13962. // contain an instance of itself, but may contain a pointer to
  13963. // an instance of itself), except that the last member of a
  13964. // structure with more than one named member may have incomplete
  13965. // array type; such a structure (and any union containing,
  13966. // possibly recursively, a member that is such a structure)
  13967. // shall not be a member of a structure or an element of an
  13968. // array.
  13969. bool IsLastField = (i + 1 == Fields.end());
  13970. if (FDTy->isFunctionType()) {
  13971. // Field declared as a function.
  13972. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  13973. << FD->getDeclName();
  13974. FD->setInvalidDecl();
  13975. EnclosingDecl->setInvalidDecl();
  13976. continue;
  13977. } else if (FDTy->isIncompleteArrayType() &&
  13978. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  13979. if (Record) {
  13980. // Flexible array member.
  13981. // Microsoft and g++ is more permissive regarding flexible array.
  13982. // It will accept flexible array in union and also
  13983. // as the sole element of a struct/class.
  13984. unsigned DiagID = 0;
  13985. if (!Record->isUnion() && !IsLastField) {
  13986. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  13987. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  13988. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  13989. FD->setInvalidDecl();
  13990. EnclosingDecl->setInvalidDecl();
  13991. continue;
  13992. } else if (Record->isUnion())
  13993. DiagID = getLangOpts().MicrosoftExt
  13994. ? diag::ext_flexible_array_union_ms
  13995. : getLangOpts().CPlusPlus
  13996. ? diag::ext_flexible_array_union_gnu
  13997. : diag::err_flexible_array_union;
  13998. else if (NumNamedMembers < 1)
  13999. DiagID = getLangOpts().MicrosoftExt
  14000. ? diag::ext_flexible_array_empty_aggregate_ms
  14001. : getLangOpts().CPlusPlus
  14002. ? diag::ext_flexible_array_empty_aggregate_gnu
  14003. : diag::err_flexible_array_empty_aggregate;
  14004. if (DiagID)
  14005. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  14006. << Record->getTagKind();
  14007. // While the layout of types that contain virtual bases is not specified
  14008. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  14009. // virtual bases after the derived members. This would make a flexible
  14010. // array member declared at the end of an object not adjacent to the end
  14011. // of the type.
  14012. if (CXXRecord && CXXRecord->getNumVBases() != 0)
  14013. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  14014. << FD->getDeclName() << Record->getTagKind();
  14015. if (!getLangOpts().C99)
  14016. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  14017. << FD->getDeclName() << Record->getTagKind();
  14018. // If the element type has a non-trivial destructor, we would not
  14019. // implicitly destroy the elements, so disallow it for now.
  14020. //
  14021. // FIXME: GCC allows this. We should probably either implicitly delete
  14022. // the destructor of the containing class, or just allow this.
  14023. QualType BaseElem = Context.getBaseElementType(FD->getType());
  14024. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  14025. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  14026. << FD->getDeclName() << FD->getType();
  14027. FD->setInvalidDecl();
  14028. EnclosingDecl->setInvalidDecl();
  14029. continue;
  14030. }
  14031. // Okay, we have a legal flexible array member at the end of the struct.
  14032. Record->setHasFlexibleArrayMember(true);
  14033. } else {
  14034. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  14035. // unless they are followed by another ivar. That check is done
  14036. // elsewhere, after synthesized ivars are known.
  14037. }
  14038. } else if (!FDTy->isDependentType() &&
  14039. RequireCompleteType(FD->getLocation(), FD->getType(),
  14040. diag::err_field_incomplete)) {
  14041. // Incomplete type
  14042. FD->setInvalidDecl();
  14043. EnclosingDecl->setInvalidDecl();
  14044. continue;
  14045. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  14046. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  14047. // A type which contains a flexible array member is considered to be a
  14048. // flexible array member.
  14049. Record->setHasFlexibleArrayMember(true);
  14050. if (!Record->isUnion()) {
  14051. // If this is a struct/class and this is not the last element, reject
  14052. // it. Note that GCC supports variable sized arrays in the middle of
  14053. // structures.
  14054. if (!IsLastField)
  14055. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  14056. << FD->getDeclName() << FD->getType();
  14057. else {
  14058. // We support flexible arrays at the end of structs in
  14059. // other structs as an extension.
  14060. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  14061. << FD->getDeclName();
  14062. }
  14063. }
  14064. }
  14065. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  14066. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  14067. diag::err_abstract_type_in_decl,
  14068. AbstractIvarType)) {
  14069. // Ivars can not have abstract class types
  14070. FD->setInvalidDecl();
  14071. }
  14072. if (Record && FDTTy->getDecl()->hasObjectMember())
  14073. Record->setHasObjectMember(true);
  14074. if (Record && FDTTy->getDecl()->hasVolatileMember())
  14075. Record->setHasVolatileMember(true);
  14076. } else if (FDTy->isObjCObjectType()) {
  14077. /// A field cannot be an Objective-c object
  14078. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  14079. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  14080. QualType T = Context.getObjCObjectPointerType(FD->getType());
  14081. FD->setType(T);
  14082. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  14083. Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
  14084. // It's an error in ARC or Weak if a field has lifetime.
  14085. // We don't want to report this in a system header, though,
  14086. // so we just make the field unavailable.
  14087. // FIXME: that's really not sufficient; we need to make the type
  14088. // itself invalid to, say, initialize or copy.
  14089. QualType T = FD->getType();
  14090. if (T.hasNonTrivialObjCLifetime()) {
  14091. SourceLocation loc = FD->getLocation();
  14092. if (getSourceManager().isInSystemHeader(loc)) {
  14093. if (!FD->hasAttr<UnavailableAttr>()) {
  14094. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  14095. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  14096. }
  14097. } else {
  14098. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  14099. << T->isBlockPointerType() << Record->getTagKind();
  14100. }
  14101. ObjCFieldLifetimeErrReported = true;
  14102. }
  14103. } else if (getLangOpts().ObjC &&
  14104. getLangOpts().getGC() != LangOptions::NonGC &&
  14105. Record && !Record->hasObjectMember()) {
  14106. if (FD->getType()->isObjCObjectPointerType() ||
  14107. FD->getType().isObjCGCStrong())
  14108. Record->setHasObjectMember(true);
  14109. else if (Context.getAsArrayType(FD->getType())) {
  14110. QualType BaseType = Context.getBaseElementType(FD->getType());
  14111. if (BaseType->isRecordType() &&
  14112. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  14113. Record->setHasObjectMember(true);
  14114. else if (BaseType->isObjCObjectPointerType() ||
  14115. BaseType.isObjCGCStrong())
  14116. Record->setHasObjectMember(true);
  14117. }
  14118. }
  14119. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  14120. QualType FT = FD->getType();
  14121. if (FT.isNonTrivialToPrimitiveDefaultInitialize())
  14122. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  14123. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  14124. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
  14125. Record->setNonTrivialToPrimitiveCopy(true);
  14126. if (FT.isDestructedType()) {
  14127. Record->setNonTrivialToPrimitiveDestroy(true);
  14128. Record->setParamDestroyedInCallee(true);
  14129. }
  14130. if (const auto *RT = FT->getAs<RecordType>()) {
  14131. if (RT->getDecl()->getArgPassingRestrictions() ==
  14132. RecordDecl::APK_CanNeverPassInRegs)
  14133. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14134. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  14135. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  14136. }
  14137. if (Record && FD->getType().isVolatileQualified())
  14138. Record->setHasVolatileMember(true);
  14139. // Keep track of the number of named members.
  14140. if (FD->getIdentifier())
  14141. ++NumNamedMembers;
  14142. }
  14143. // Okay, we successfully defined 'Record'.
  14144. if (Record) {
  14145. bool Completed = false;
  14146. if (CXXRecord) {
  14147. if (!CXXRecord->isInvalidDecl()) {
  14148. // Set access bits correctly on the directly-declared conversions.
  14149. for (CXXRecordDecl::conversion_iterator
  14150. I = CXXRecord->conversion_begin(),
  14151. E = CXXRecord->conversion_end(); I != E; ++I)
  14152. I.setAccess((*I)->getAccess());
  14153. }
  14154. if (!CXXRecord->isDependentType()) {
  14155. // Add any implicitly-declared members to this class.
  14156. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  14157. if (!CXXRecord->isInvalidDecl()) {
  14158. // If we have virtual base classes, we may end up finding multiple
  14159. // final overriders for a given virtual function. Check for this
  14160. // problem now.
  14161. if (CXXRecord->getNumVBases()) {
  14162. CXXFinalOverriderMap FinalOverriders;
  14163. CXXRecord->getFinalOverriders(FinalOverriders);
  14164. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  14165. MEnd = FinalOverriders.end();
  14166. M != MEnd; ++M) {
  14167. for (OverridingMethods::iterator SO = M->second.begin(),
  14168. SOEnd = M->second.end();
  14169. SO != SOEnd; ++SO) {
  14170. assert(SO->second.size() > 0 &&
  14171. "Virtual function without overriding functions?");
  14172. if (SO->second.size() == 1)
  14173. continue;
  14174. // C++ [class.virtual]p2:
  14175. // In a derived class, if a virtual member function of a base
  14176. // class subobject has more than one final overrider the
  14177. // program is ill-formed.
  14178. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  14179. << (const NamedDecl *)M->first << Record;
  14180. Diag(M->first->getLocation(),
  14181. diag::note_overridden_virtual_function);
  14182. for (OverridingMethods::overriding_iterator
  14183. OM = SO->second.begin(),
  14184. OMEnd = SO->second.end();
  14185. OM != OMEnd; ++OM)
  14186. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  14187. << (const NamedDecl *)M->first << OM->Method->getParent();
  14188. Record->setInvalidDecl();
  14189. }
  14190. }
  14191. CXXRecord->completeDefinition(&FinalOverriders);
  14192. Completed = true;
  14193. }
  14194. }
  14195. }
  14196. }
  14197. if (!Completed)
  14198. Record->completeDefinition();
  14199. // Handle attributes before checking the layout.
  14200. ProcessDeclAttributeList(S, Record, Attrs);
  14201. // We may have deferred checking for a deleted destructor. Check now.
  14202. if (CXXRecord) {
  14203. auto *Dtor = CXXRecord->getDestructor();
  14204. if (Dtor && Dtor->isImplicit() &&
  14205. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  14206. CXXRecord->setImplicitDestructorIsDeleted();
  14207. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  14208. }
  14209. }
  14210. if (Record->hasAttrs()) {
  14211. CheckAlignasUnderalignment(Record);
  14212. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  14213. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  14214. IA->getRange(), IA->getBestCase(),
  14215. IA->getSemanticSpelling());
  14216. }
  14217. // Check if the structure/union declaration is a type that can have zero
  14218. // size in C. For C this is a language extension, for C++ it may cause
  14219. // compatibility problems.
  14220. bool CheckForZeroSize;
  14221. if (!getLangOpts().CPlusPlus) {
  14222. CheckForZeroSize = true;
  14223. } else {
  14224. // For C++ filter out types that cannot be referenced in C code.
  14225. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  14226. CheckForZeroSize =
  14227. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  14228. !CXXRecord->isDependentType() &&
  14229. CXXRecord->isCLike();
  14230. }
  14231. if (CheckForZeroSize) {
  14232. bool ZeroSize = true;
  14233. bool IsEmpty = true;
  14234. unsigned NonBitFields = 0;
  14235. for (RecordDecl::field_iterator I = Record->field_begin(),
  14236. E = Record->field_end();
  14237. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  14238. IsEmpty = false;
  14239. if (I->isUnnamedBitfield()) {
  14240. if (!I->isZeroLengthBitField(Context))
  14241. ZeroSize = false;
  14242. } else {
  14243. ++NonBitFields;
  14244. QualType FieldType = I->getType();
  14245. if (FieldType->isIncompleteType() ||
  14246. !Context.getTypeSizeInChars(FieldType).isZero())
  14247. ZeroSize = false;
  14248. }
  14249. }
  14250. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  14251. // allowed in C++, but warn if its declaration is inside
  14252. // extern "C" block.
  14253. if (ZeroSize) {
  14254. Diag(RecLoc, getLangOpts().CPlusPlus ?
  14255. diag::warn_zero_size_struct_union_in_extern_c :
  14256. diag::warn_zero_size_struct_union_compat)
  14257. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  14258. }
  14259. // Structs without named members are extension in C (C99 6.7.2.1p7),
  14260. // but are accepted by GCC.
  14261. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  14262. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  14263. diag::ext_no_named_members_in_struct_union)
  14264. << Record->isUnion();
  14265. }
  14266. }
  14267. } else {
  14268. ObjCIvarDecl **ClsFields =
  14269. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  14270. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  14271. ID->setEndOfDefinitionLoc(RBrac);
  14272. // Add ivar's to class's DeclContext.
  14273. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14274. ClsFields[i]->setLexicalDeclContext(ID);
  14275. ID->addDecl(ClsFields[i]);
  14276. }
  14277. // Must enforce the rule that ivars in the base classes may not be
  14278. // duplicates.
  14279. if (ID->getSuperClass())
  14280. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  14281. } else if (ObjCImplementationDecl *IMPDecl =
  14282. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  14283. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  14284. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  14285. // Ivar declared in @implementation never belongs to the implementation.
  14286. // Only it is in implementation's lexical context.
  14287. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  14288. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  14289. IMPDecl->setIvarLBraceLoc(LBrac);
  14290. IMPDecl->setIvarRBraceLoc(RBrac);
  14291. } else if (ObjCCategoryDecl *CDecl =
  14292. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  14293. // case of ivars in class extension; all other cases have been
  14294. // reported as errors elsewhere.
  14295. // FIXME. Class extension does not have a LocEnd field.
  14296. // CDecl->setLocEnd(RBrac);
  14297. // Add ivar's to class extension's DeclContext.
  14298. // Diagnose redeclaration of private ivars.
  14299. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  14300. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  14301. if (IDecl) {
  14302. if (const ObjCIvarDecl *ClsIvar =
  14303. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14304. Diag(ClsFields[i]->getLocation(),
  14305. diag::err_duplicate_ivar_declaration);
  14306. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  14307. continue;
  14308. }
  14309. for (const auto *Ext : IDecl->known_extensions()) {
  14310. if (const ObjCIvarDecl *ClsExtIvar
  14311. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  14312. Diag(ClsFields[i]->getLocation(),
  14313. diag::err_duplicate_ivar_declaration);
  14314. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  14315. continue;
  14316. }
  14317. }
  14318. }
  14319. ClsFields[i]->setLexicalDeclContext(CDecl);
  14320. CDecl->addDecl(ClsFields[i]);
  14321. }
  14322. CDecl->setIvarLBraceLoc(LBrac);
  14323. CDecl->setIvarRBraceLoc(RBrac);
  14324. }
  14325. }
  14326. }
  14327. /// Determine whether the given integral value is representable within
  14328. /// the given type T.
  14329. static bool isRepresentableIntegerValue(ASTContext &Context,
  14330. llvm::APSInt &Value,
  14331. QualType T) {
  14332. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  14333. "Integral type required!");
  14334. unsigned BitWidth = Context.getIntWidth(T);
  14335. if (Value.isUnsigned() || Value.isNonNegative()) {
  14336. if (T->isSignedIntegerOrEnumerationType())
  14337. --BitWidth;
  14338. return Value.getActiveBits() <= BitWidth;
  14339. }
  14340. return Value.getMinSignedBits() <= BitWidth;
  14341. }
  14342. // Given an integral type, return the next larger integral type
  14343. // (or a NULL type of no such type exists).
  14344. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  14345. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  14346. // enum checking below.
  14347. assert((T->isIntegralType(Context) ||
  14348. T->isEnumeralType()) && "Integral type required!");
  14349. const unsigned NumTypes = 4;
  14350. QualType SignedIntegralTypes[NumTypes] = {
  14351. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  14352. };
  14353. QualType UnsignedIntegralTypes[NumTypes] = {
  14354. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  14355. Context.UnsignedLongLongTy
  14356. };
  14357. unsigned BitWidth = Context.getTypeSize(T);
  14358. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  14359. : UnsignedIntegralTypes;
  14360. for (unsigned I = 0; I != NumTypes; ++I)
  14361. if (Context.getTypeSize(Types[I]) > BitWidth)
  14362. return Types[I];
  14363. return QualType();
  14364. }
  14365. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  14366. EnumConstantDecl *LastEnumConst,
  14367. SourceLocation IdLoc,
  14368. IdentifierInfo *Id,
  14369. Expr *Val) {
  14370. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14371. llvm::APSInt EnumVal(IntWidth);
  14372. QualType EltTy;
  14373. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  14374. Val = nullptr;
  14375. if (Val)
  14376. Val = DefaultLvalueConversion(Val).get();
  14377. if (Val) {
  14378. if (Enum->isDependentType() || Val->isTypeDependent())
  14379. EltTy = Context.DependentTy;
  14380. else {
  14381. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  14382. !getLangOpts().MSVCCompat) {
  14383. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  14384. // constant-expression in the enumerator-definition shall be a converted
  14385. // constant expression of the underlying type.
  14386. EltTy = Enum->getIntegerType();
  14387. ExprResult Converted =
  14388. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  14389. CCEK_Enumerator);
  14390. if (Converted.isInvalid())
  14391. Val = nullptr;
  14392. else
  14393. Val = Converted.get();
  14394. } else if (!Val->isValueDependent() &&
  14395. !(Val = VerifyIntegerConstantExpression(Val,
  14396. &EnumVal).get())) {
  14397. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  14398. } else {
  14399. if (Enum->isComplete()) {
  14400. EltTy = Enum->getIntegerType();
  14401. // In Obj-C and Microsoft mode, require the enumeration value to be
  14402. // representable in the underlying type of the enumeration. In C++11,
  14403. // we perform a non-narrowing conversion as part of converted constant
  14404. // expression checking.
  14405. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14406. if (getLangOpts().MSVCCompat) {
  14407. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14408. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14409. } else
  14410. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14411. } else
  14412. Val = ImpCastExprToType(Val, EltTy,
  14413. EltTy->isBooleanType() ?
  14414. CK_IntegralToBoolean : CK_IntegralCast)
  14415. .get();
  14416. } else if (getLangOpts().CPlusPlus) {
  14417. // C++11 [dcl.enum]p5:
  14418. // If the underlying type is not fixed, the type of each enumerator
  14419. // is the type of its initializing value:
  14420. // - If an initializer is specified for an enumerator, the
  14421. // initializing value has the same type as the expression.
  14422. EltTy = Val->getType();
  14423. } else {
  14424. // C99 6.7.2.2p2:
  14425. // The expression that defines the value of an enumeration constant
  14426. // shall be an integer constant expression that has a value
  14427. // representable as an int.
  14428. // Complain if the value is not representable in an int.
  14429. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14430. Diag(IdLoc, diag::ext_enum_value_not_int)
  14431. << EnumVal.toString(10) << Val->getSourceRange()
  14432. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14433. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14434. // Force the type of the expression to 'int'.
  14435. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14436. }
  14437. EltTy = Val->getType();
  14438. }
  14439. }
  14440. }
  14441. }
  14442. if (!Val) {
  14443. if (Enum->isDependentType())
  14444. EltTy = Context.DependentTy;
  14445. else if (!LastEnumConst) {
  14446. // C++0x [dcl.enum]p5:
  14447. // If the underlying type is not fixed, the type of each enumerator
  14448. // is the type of its initializing value:
  14449. // - If no initializer is specified for the first enumerator, the
  14450. // initializing value has an unspecified integral type.
  14451. //
  14452. // GCC uses 'int' for its unspecified integral type, as does
  14453. // C99 6.7.2.2p3.
  14454. if (Enum->isFixed()) {
  14455. EltTy = Enum->getIntegerType();
  14456. }
  14457. else {
  14458. EltTy = Context.IntTy;
  14459. }
  14460. } else {
  14461. // Assign the last value + 1.
  14462. EnumVal = LastEnumConst->getInitVal();
  14463. ++EnumVal;
  14464. EltTy = LastEnumConst->getType();
  14465. // Check for overflow on increment.
  14466. if (EnumVal < LastEnumConst->getInitVal()) {
  14467. // C++0x [dcl.enum]p5:
  14468. // If the underlying type is not fixed, the type of each enumerator
  14469. // is the type of its initializing value:
  14470. //
  14471. // - Otherwise the type of the initializing value is the same as
  14472. // the type of the initializing value of the preceding enumerator
  14473. // unless the incremented value is not representable in that type,
  14474. // in which case the type is an unspecified integral type
  14475. // sufficient to contain the incremented value. If no such type
  14476. // exists, the program is ill-formed.
  14477. QualType T = getNextLargerIntegralType(Context, EltTy);
  14478. if (T.isNull() || Enum->isFixed()) {
  14479. // There is no integral type larger enough to represent this
  14480. // value. Complain, then allow the value to wrap around.
  14481. EnumVal = LastEnumConst->getInitVal();
  14482. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14483. ++EnumVal;
  14484. if (Enum->isFixed())
  14485. // When the underlying type is fixed, this is ill-formed.
  14486. Diag(IdLoc, diag::err_enumerator_wrapped)
  14487. << EnumVal.toString(10)
  14488. << EltTy;
  14489. else
  14490. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14491. << EnumVal.toString(10);
  14492. } else {
  14493. EltTy = T;
  14494. }
  14495. // Retrieve the last enumerator's value, extent that type to the
  14496. // type that is supposed to be large enough to represent the incremented
  14497. // value, then increment.
  14498. EnumVal = LastEnumConst->getInitVal();
  14499. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14500. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14501. ++EnumVal;
  14502. // If we're not in C++, diagnose the overflow of enumerator values,
  14503. // which in C99 means that the enumerator value is not representable in
  14504. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14505. // permits enumerator values that are representable in some larger
  14506. // integral type.
  14507. if (!getLangOpts().CPlusPlus && !T.isNull())
  14508. Diag(IdLoc, diag::warn_enum_value_overflow);
  14509. } else if (!getLangOpts().CPlusPlus &&
  14510. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14511. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14512. Diag(IdLoc, diag::ext_enum_value_not_int)
  14513. << EnumVal.toString(10) << 1;
  14514. }
  14515. }
  14516. }
  14517. if (!EltTy->isDependentType()) {
  14518. // Make the enumerator value match the signedness and size of the
  14519. // enumerator's type.
  14520. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14521. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14522. }
  14523. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14524. Val, EnumVal);
  14525. }
  14526. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14527. SourceLocation IILoc) {
  14528. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14529. !getLangOpts().CPlusPlus)
  14530. return SkipBodyInfo();
  14531. // We have an anonymous enum definition. Look up the first enumerator to
  14532. // determine if we should merge the definition with an existing one and
  14533. // skip the body.
  14534. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14535. forRedeclarationInCurContext());
  14536. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14537. if (!PrevECD)
  14538. return SkipBodyInfo();
  14539. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14540. NamedDecl *Hidden;
  14541. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14542. SkipBodyInfo Skip;
  14543. Skip.Previous = Hidden;
  14544. return Skip;
  14545. }
  14546. return SkipBodyInfo();
  14547. }
  14548. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14549. SourceLocation IdLoc, IdentifierInfo *Id,
  14550. const ParsedAttributesView &Attrs,
  14551. SourceLocation EqualLoc, Expr *Val) {
  14552. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14553. EnumConstantDecl *LastEnumConst =
  14554. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14555. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14556. // we find one that is.
  14557. S = getNonFieldDeclScope(S);
  14558. // Verify that there isn't already something declared with this name in this
  14559. // scope.
  14560. LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
  14561. LookupName(R, S);
  14562. NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
  14563. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14564. // Maybe we will complain about the shadowed template parameter.
  14565. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14566. // Just pretend that we didn't see the previous declaration.
  14567. PrevDecl = nullptr;
  14568. }
  14569. // C++ [class.mem]p15:
  14570. // If T is the name of a class, then each of the following shall have a name
  14571. // different from T:
  14572. // - every enumerator of every member of class T that is an unscoped
  14573. // enumerated type
  14574. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14575. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14576. DeclarationNameInfo(Id, IdLoc));
  14577. EnumConstantDecl *New =
  14578. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14579. if (!New)
  14580. return nullptr;
  14581. if (PrevDecl) {
  14582. if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
  14583. // Check for other kinds of shadowing not already handled.
  14584. CheckShadow(New, PrevDecl, R);
  14585. }
  14586. // When in C++, we may get a TagDecl with the same name; in this case the
  14587. // enum constant will 'hide' the tag.
  14588. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14589. "Received TagDecl when not in C++!");
  14590. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14591. if (isa<EnumConstantDecl>(PrevDecl))
  14592. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14593. else
  14594. Diag(IdLoc, diag::err_redefinition) << Id;
  14595. notePreviousDefinition(PrevDecl, IdLoc);
  14596. return nullptr;
  14597. }
  14598. }
  14599. // Process attributes.
  14600. ProcessDeclAttributeList(S, New, Attrs);
  14601. AddPragmaAttributes(S, New);
  14602. // Register this decl in the current scope stack.
  14603. New->setAccess(TheEnumDecl->getAccess());
  14604. PushOnScopeChains(New, S);
  14605. ActOnDocumentableDecl(New);
  14606. return New;
  14607. }
  14608. // Returns true when the enum initial expression does not trigger the
  14609. // duplicate enum warning. A few common cases are exempted as follows:
  14610. // Element2 = Element1
  14611. // Element2 = Element1 + 1
  14612. // Element2 = Element1 - 1
  14613. // Where Element2 and Element1 are from the same enum.
  14614. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14615. Expr *InitExpr = ECD->getInitExpr();
  14616. if (!InitExpr)
  14617. return true;
  14618. InitExpr = InitExpr->IgnoreImpCasts();
  14619. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14620. if (!BO->isAdditiveOp())
  14621. return true;
  14622. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14623. if (!IL)
  14624. return true;
  14625. if (IL->getValue() != 1)
  14626. return true;
  14627. InitExpr = BO->getLHS();
  14628. }
  14629. // This checks if the elements are from the same enum.
  14630. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  14631. if (!DRE)
  14632. return true;
  14633. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  14634. if (!EnumConstant)
  14635. return true;
  14636. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  14637. Enum)
  14638. return true;
  14639. return false;
  14640. }
  14641. // Emits a warning when an element is implicitly set a value that
  14642. // a previous element has already been set to.
  14643. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  14644. EnumDecl *Enum, QualType EnumType) {
  14645. // Avoid anonymous enums
  14646. if (!Enum->getIdentifier())
  14647. return;
  14648. // Only check for small enums.
  14649. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  14650. return;
  14651. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  14652. return;
  14653. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  14654. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  14655. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  14656. typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
  14657. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  14658. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  14659. llvm::APSInt Val = D->getInitVal();
  14660. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  14661. };
  14662. DuplicatesVector DupVector;
  14663. ValueToVectorMap EnumMap;
  14664. // Populate the EnumMap with all values represented by enum constants without
  14665. // an initializer.
  14666. for (auto *Element : Elements) {
  14667. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  14668. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  14669. // this constant. Skip this enum since it may be ill-formed.
  14670. if (!ECD) {
  14671. return;
  14672. }
  14673. // Constants with initalizers are handled in the next loop.
  14674. if (ECD->getInitExpr())
  14675. continue;
  14676. // Duplicate values are handled in the next loop.
  14677. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  14678. }
  14679. if (EnumMap.size() == 0)
  14680. return;
  14681. // Create vectors for any values that has duplicates.
  14682. for (auto *Element : Elements) {
  14683. // The last loop returned if any constant was null.
  14684. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  14685. if (!ValidDuplicateEnum(ECD, Enum))
  14686. continue;
  14687. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  14688. if (Iter == EnumMap.end())
  14689. continue;
  14690. DeclOrVector& Entry = Iter->second;
  14691. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14692. // Ensure constants are different.
  14693. if (D == ECD)
  14694. continue;
  14695. // Create new vector and push values onto it.
  14696. auto Vec = llvm::make_unique<ECDVector>();
  14697. Vec->push_back(D);
  14698. Vec->push_back(ECD);
  14699. // Update entry to point to the duplicates vector.
  14700. Entry = Vec.get();
  14701. // Store the vector somewhere we can consult later for quick emission of
  14702. // diagnostics.
  14703. DupVector.emplace_back(std::move(Vec));
  14704. continue;
  14705. }
  14706. ECDVector *Vec = Entry.get<ECDVector*>();
  14707. // Make sure constants are not added more than once.
  14708. if (*Vec->begin() == ECD)
  14709. continue;
  14710. Vec->push_back(ECD);
  14711. }
  14712. // Emit diagnostics.
  14713. for (const auto &Vec : DupVector) {
  14714. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14715. // Emit warning for one enum constant.
  14716. auto *FirstECD = Vec->front();
  14717. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  14718. << FirstECD << FirstECD->getInitVal().toString(10)
  14719. << FirstECD->getSourceRange();
  14720. // Emit one note for each of the remaining enum constants with
  14721. // the same value.
  14722. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  14723. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  14724. << ECD << ECD->getInitVal().toString(10)
  14725. << ECD->getSourceRange();
  14726. }
  14727. }
  14728. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14729. bool AllowMask) const {
  14730. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  14731. assert(ED->isCompleteDefinition() && "expected enum definition");
  14732. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  14733. llvm::APInt &FlagBits = R.first->second;
  14734. if (R.second) {
  14735. for (auto *E : ED->enumerators()) {
  14736. const auto &EVal = E->getInitVal();
  14737. // Only single-bit enumerators introduce new flag values.
  14738. if (EVal.isPowerOf2())
  14739. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  14740. }
  14741. }
  14742. // A value is in a flag enum if either its bits are a subset of the enum's
  14743. // flag bits (the first condition) or we are allowing masks and the same is
  14744. // true of its complement (the second condition). When masks are allowed, we
  14745. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  14746. //
  14747. // While it's true that any value could be used as a mask, the assumption is
  14748. // that a mask will have all of the insignificant bits set. Anything else is
  14749. // likely a logic error.
  14750. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  14751. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  14752. }
  14753. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  14754. Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
  14755. const ParsedAttributesView &Attrs) {
  14756. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  14757. QualType EnumType = Context.getTypeDeclType(Enum);
  14758. ProcessDeclAttributeList(S, Enum, Attrs);
  14759. if (Enum->isDependentType()) {
  14760. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14761. EnumConstantDecl *ECD =
  14762. cast_or_null<EnumConstantDecl>(Elements[i]);
  14763. if (!ECD) continue;
  14764. ECD->setType(EnumType);
  14765. }
  14766. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  14767. return;
  14768. }
  14769. // TODO: If the result value doesn't fit in an int, it must be a long or long
  14770. // long value. ISO C does not support this, but GCC does as an extension,
  14771. // emit a warning.
  14772. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14773. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  14774. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  14775. // Verify that all the values are okay, compute the size of the values, and
  14776. // reverse the list.
  14777. unsigned NumNegativeBits = 0;
  14778. unsigned NumPositiveBits = 0;
  14779. // Keep track of whether all elements have type int.
  14780. bool AllElementsInt = true;
  14781. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14782. EnumConstantDecl *ECD =
  14783. cast_or_null<EnumConstantDecl>(Elements[i]);
  14784. if (!ECD) continue; // Already issued a diagnostic.
  14785. const llvm::APSInt &InitVal = ECD->getInitVal();
  14786. // Keep track of the size of positive and negative values.
  14787. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  14788. NumPositiveBits = std::max(NumPositiveBits,
  14789. (unsigned)InitVal.getActiveBits());
  14790. else
  14791. NumNegativeBits = std::max(NumNegativeBits,
  14792. (unsigned)InitVal.getMinSignedBits());
  14793. // Keep track of whether every enum element has type int (very common).
  14794. if (AllElementsInt)
  14795. AllElementsInt = ECD->getType() == Context.IntTy;
  14796. }
  14797. // Figure out the type that should be used for this enum.
  14798. QualType BestType;
  14799. unsigned BestWidth;
  14800. // C++0x N3000 [conv.prom]p3:
  14801. // An rvalue of an unscoped enumeration type whose underlying
  14802. // type is not fixed can be converted to an rvalue of the first
  14803. // of the following types that can represent all the values of
  14804. // the enumeration: int, unsigned int, long int, unsigned long
  14805. // int, long long int, or unsigned long long int.
  14806. // C99 6.4.4.3p2:
  14807. // An identifier declared as an enumeration constant has type int.
  14808. // The C99 rule is modified by a gcc extension
  14809. QualType BestPromotionType;
  14810. bool Packed = Enum->hasAttr<PackedAttr>();
  14811. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14812. // enum definitions.
  14813. if (LangOpts.ShortEnums)
  14814. Packed = true;
  14815. // If the enum already has a type because it is fixed or dictated by the
  14816. // target, promote that type instead of analyzing the enumerators.
  14817. if (Enum->isComplete()) {
  14818. BestType = Enum->getIntegerType();
  14819. if (BestType->isPromotableIntegerType())
  14820. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14821. else
  14822. BestPromotionType = BestType;
  14823. BestWidth = Context.getIntWidth(BestType);
  14824. }
  14825. else if (NumNegativeBits) {
  14826. // If there is a negative value, figure out the smallest integer type (of
  14827. // int/long/longlong) that fits.
  14828. // If it's packed, check also if it fits a char or a short.
  14829. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14830. BestType = Context.SignedCharTy;
  14831. BestWidth = CharWidth;
  14832. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14833. NumPositiveBits < ShortWidth) {
  14834. BestType = Context.ShortTy;
  14835. BestWidth = ShortWidth;
  14836. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14837. BestType = Context.IntTy;
  14838. BestWidth = IntWidth;
  14839. } else {
  14840. BestWidth = Context.getTargetInfo().getLongWidth();
  14841. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14842. BestType = Context.LongTy;
  14843. } else {
  14844. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14845. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14846. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14847. BestType = Context.LongLongTy;
  14848. }
  14849. }
  14850. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14851. } else {
  14852. // If there is no negative value, figure out the smallest type that fits
  14853. // all of the enumerator values.
  14854. // If it's packed, check also if it fits a char or a short.
  14855. if (Packed && NumPositiveBits <= CharWidth) {
  14856. BestType = Context.UnsignedCharTy;
  14857. BestPromotionType = Context.IntTy;
  14858. BestWidth = CharWidth;
  14859. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14860. BestType = Context.UnsignedShortTy;
  14861. BestPromotionType = Context.IntTy;
  14862. BestWidth = ShortWidth;
  14863. } else if (NumPositiveBits <= IntWidth) {
  14864. BestType = Context.UnsignedIntTy;
  14865. BestWidth = IntWidth;
  14866. BestPromotionType
  14867. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14868. ? Context.UnsignedIntTy : Context.IntTy;
  14869. } else if (NumPositiveBits <=
  14870. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14871. BestType = Context.UnsignedLongTy;
  14872. BestPromotionType
  14873. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14874. ? Context.UnsignedLongTy : Context.LongTy;
  14875. } else {
  14876. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14877. assert(NumPositiveBits <= BestWidth &&
  14878. "How could an initializer get larger than ULL?");
  14879. BestType = Context.UnsignedLongLongTy;
  14880. BestPromotionType
  14881. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14882. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14883. }
  14884. }
  14885. // Loop over all of the enumerator constants, changing their types to match
  14886. // the type of the enum if needed.
  14887. for (auto *D : Elements) {
  14888. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14889. if (!ECD) continue; // Already issued a diagnostic.
  14890. // Standard C says the enumerators have int type, but we allow, as an
  14891. // extension, the enumerators to be larger than int size. If each
  14892. // enumerator value fits in an int, type it as an int, otherwise type it the
  14893. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  14894. // that X has type 'int', not 'unsigned'.
  14895. // Determine whether the value fits into an int.
  14896. llvm::APSInt InitVal = ECD->getInitVal();
  14897. // If it fits into an integer type, force it. Otherwise force it to match
  14898. // the enum decl type.
  14899. QualType NewTy;
  14900. unsigned NewWidth;
  14901. bool NewSign;
  14902. if (!getLangOpts().CPlusPlus &&
  14903. !Enum->isFixed() &&
  14904. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  14905. NewTy = Context.IntTy;
  14906. NewWidth = IntWidth;
  14907. NewSign = true;
  14908. } else if (ECD->getType() == BestType) {
  14909. // Already the right type!
  14910. if (getLangOpts().CPlusPlus)
  14911. // C++ [dcl.enum]p4: Following the closing brace of an
  14912. // enum-specifier, each enumerator has the type of its
  14913. // enumeration.
  14914. ECD->setType(EnumType);
  14915. continue;
  14916. } else {
  14917. NewTy = BestType;
  14918. NewWidth = BestWidth;
  14919. NewSign = BestType->isSignedIntegerOrEnumerationType();
  14920. }
  14921. // Adjust the APSInt value.
  14922. InitVal = InitVal.extOrTrunc(NewWidth);
  14923. InitVal.setIsSigned(NewSign);
  14924. ECD->setInitVal(InitVal);
  14925. // Adjust the Expr initializer and type.
  14926. if (ECD->getInitExpr() &&
  14927. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  14928. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  14929. CK_IntegralCast,
  14930. ECD->getInitExpr(),
  14931. /*base paths*/ nullptr,
  14932. VK_RValue));
  14933. if (getLangOpts().CPlusPlus)
  14934. // C++ [dcl.enum]p4: Following the closing brace of an
  14935. // enum-specifier, each enumerator has the type of its
  14936. // enumeration.
  14937. ECD->setType(EnumType);
  14938. else
  14939. ECD->setType(NewTy);
  14940. }
  14941. Enum->completeDefinition(BestType, BestPromotionType,
  14942. NumPositiveBits, NumNegativeBits);
  14943. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  14944. if (Enum->isClosedFlag()) {
  14945. for (Decl *D : Elements) {
  14946. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  14947. if (!ECD) continue; // Already issued a diagnostic.
  14948. llvm::APSInt InitVal = ECD->getInitVal();
  14949. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  14950. !IsValueInFlagEnum(Enum, InitVal, true))
  14951. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  14952. << ECD << Enum;
  14953. }
  14954. }
  14955. // Now that the enum type is defined, ensure it's not been underaligned.
  14956. if (Enum->hasAttrs())
  14957. CheckAlignasUnderalignment(Enum);
  14958. }
  14959. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  14960. SourceLocation StartLoc,
  14961. SourceLocation EndLoc) {
  14962. StringLiteral *AsmString = cast<StringLiteral>(expr);
  14963. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  14964. AsmString, StartLoc,
  14965. EndLoc);
  14966. CurContext->addDecl(New);
  14967. return New;
  14968. }
  14969. static void checkModuleImportContext(Sema &S, Module *M,
  14970. SourceLocation ImportLoc, DeclContext *DC,
  14971. bool FromInclude = false) {
  14972. SourceLocation ExternCLoc;
  14973. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  14974. switch (LSD->getLanguage()) {
  14975. case LinkageSpecDecl::lang_c:
  14976. if (ExternCLoc.isInvalid())
  14977. ExternCLoc = LSD->getBeginLoc();
  14978. break;
  14979. case LinkageSpecDecl::lang_cxx:
  14980. break;
  14981. }
  14982. DC = LSD->getParent();
  14983. }
  14984. while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
  14985. DC = DC->getParent();
  14986. if (!isa<TranslationUnitDecl>(DC)) {
  14987. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  14988. ? diag::ext_module_import_not_at_top_level_noop
  14989. : diag::err_module_import_not_at_top_level_fatal)
  14990. << M->getFullModuleName() << DC;
  14991. S.Diag(cast<Decl>(DC)->getBeginLoc(),
  14992. diag::note_module_import_not_at_top_level)
  14993. << DC;
  14994. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  14995. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  14996. << M->getFullModuleName();
  14997. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  14998. }
  14999. }
  15000. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
  15001. SourceLocation ModuleLoc,
  15002. ModuleDeclKind MDK,
  15003. ModuleIdPath Path) {
  15004. assert(getLangOpts().ModulesTS &&
  15005. "should only have module decl in modules TS");
  15006. // A module implementation unit requires that we are not compiling a module
  15007. // of any kind. A module interface unit requires that we are not compiling a
  15008. // module map.
  15009. switch (getLangOpts().getCompilingModule()) {
  15010. case LangOptions::CMK_None:
  15011. // It's OK to compile a module interface as a normal translation unit.
  15012. break;
  15013. case LangOptions::CMK_ModuleInterface:
  15014. if (MDK != ModuleDeclKind::Implementation)
  15015. break;
  15016. // We were asked to compile a module interface unit but this is a module
  15017. // implementation unit. That indicates the 'export' is missing.
  15018. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  15019. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  15020. MDK = ModuleDeclKind::Interface;
  15021. break;
  15022. case LangOptions::CMK_ModuleMap:
  15023. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  15024. return nullptr;
  15025. case LangOptions::CMK_HeaderModule:
  15026. Diag(ModuleLoc, diag::err_module_decl_in_header_module);
  15027. return nullptr;
  15028. }
  15029. assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
  15030. // FIXME: Most of this work should be done by the preprocessor rather than
  15031. // here, in order to support macro import.
  15032. // Only one module-declaration is permitted per source file.
  15033. if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
  15034. Diag(ModuleLoc, diag::err_module_redeclaration);
  15035. Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
  15036. diag::note_prev_module_declaration);
  15037. return nullptr;
  15038. }
  15039. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  15040. // modules, the dots here are just another character that can appear in a
  15041. // module name.
  15042. std::string ModuleName;
  15043. for (auto &Piece : Path) {
  15044. if (!ModuleName.empty())
  15045. ModuleName += ".";
  15046. ModuleName += Piece.first->getName();
  15047. }
  15048. // If a module name was explicitly specified on the command line, it must be
  15049. // correct.
  15050. if (!getLangOpts().CurrentModule.empty() &&
  15051. getLangOpts().CurrentModule != ModuleName) {
  15052. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  15053. << SourceRange(Path.front().second, Path.back().second)
  15054. << getLangOpts().CurrentModule;
  15055. return nullptr;
  15056. }
  15057. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  15058. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  15059. Module *Mod;
  15060. switch (MDK) {
  15061. case ModuleDeclKind::Interface: {
  15062. // We can't have parsed or imported a definition of this module or parsed a
  15063. // module map defining it already.
  15064. if (auto *M = Map.findModule(ModuleName)) {
  15065. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  15066. if (M->DefinitionLoc.isValid())
  15067. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  15068. else if (const auto *FE = M->getASTFile())
  15069. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  15070. << FE->getName();
  15071. Mod = M;
  15072. break;
  15073. }
  15074. // Create a Module for the module that we're defining.
  15075. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  15076. ModuleScopes.front().Module);
  15077. assert(Mod && "module creation should not fail");
  15078. break;
  15079. }
  15080. case ModuleDeclKind::Partition:
  15081. // FIXME: Check we are in a submodule of the named module.
  15082. return nullptr;
  15083. case ModuleDeclKind::Implementation:
  15084. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  15085. PP.getIdentifierInfo(ModuleName), Path[0].second);
  15086. Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
  15087. Module::AllVisible,
  15088. /*IsIncludeDirective=*/false);
  15089. if (!Mod) {
  15090. Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
  15091. // Create an empty module interface unit for error recovery.
  15092. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  15093. ModuleScopes.front().Module);
  15094. }
  15095. break;
  15096. }
  15097. // Switch from the global module to the named module.
  15098. ModuleScopes.back().Module = Mod;
  15099. ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
  15100. VisibleModules.setVisible(Mod, ModuleLoc);
  15101. // From now on, we have an owning module for all declarations we see.
  15102. // However, those declarations are module-private unless explicitly
  15103. // exported.
  15104. auto *TU = Context.getTranslationUnitDecl();
  15105. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  15106. TU->setLocalOwningModule(Mod);
  15107. // FIXME: Create a ModuleDecl.
  15108. return nullptr;
  15109. }
  15110. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  15111. SourceLocation ImportLoc,
  15112. ModuleIdPath Path) {
  15113. // Flatten the module path for a Modules TS module name.
  15114. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
  15115. if (getLangOpts().ModulesTS) {
  15116. std::string ModuleName;
  15117. for (auto &Piece : Path) {
  15118. if (!ModuleName.empty())
  15119. ModuleName += ".";
  15120. ModuleName += Piece.first->getName();
  15121. }
  15122. ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
  15123. Path = ModuleIdPath(ModuleNameLoc);
  15124. }
  15125. Module *Mod =
  15126. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  15127. /*IsIncludeDirective=*/false);
  15128. if (!Mod)
  15129. return true;
  15130. VisibleModules.setVisible(Mod, ImportLoc);
  15131. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  15132. // FIXME: we should support importing a submodule within a different submodule
  15133. // of the same top-level module. Until we do, make it an error rather than
  15134. // silently ignoring the import.
  15135. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  15136. // warn on a redundant import of the current module?
  15137. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  15138. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  15139. Diag(ImportLoc, getLangOpts().isCompilingModule()
  15140. ? diag::err_module_self_import
  15141. : diag::err_module_import_in_implementation)
  15142. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  15143. SmallVector<SourceLocation, 2> IdentifierLocs;
  15144. Module *ModCheck = Mod;
  15145. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  15146. // If we've run out of module parents, just drop the remaining identifiers.
  15147. // We need the length to be consistent.
  15148. if (!ModCheck)
  15149. break;
  15150. ModCheck = ModCheck->Parent;
  15151. IdentifierLocs.push_back(Path[I].second);
  15152. }
  15153. ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
  15154. Mod, IdentifierLocs);
  15155. if (!ModuleScopes.empty())
  15156. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  15157. CurContext->addDecl(Import);
  15158. // Re-export the module if needed.
  15159. if (Import->isExported() &&
  15160. !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
  15161. getCurrentModule()->Exports.emplace_back(Mod, false);
  15162. return Import;
  15163. }
  15164. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  15165. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  15166. BuildModuleInclude(DirectiveLoc, Mod);
  15167. }
  15168. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  15169. // Determine whether we're in the #include buffer for a module. The #includes
  15170. // in that buffer do not qualify as module imports; they're just an
  15171. // implementation detail of us building the module.
  15172. //
  15173. // FIXME: Should we even get ActOnModuleInclude calls for those?
  15174. bool IsInModuleIncludes =
  15175. TUKind == TU_Module &&
  15176. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  15177. bool ShouldAddImport = !IsInModuleIncludes;
  15178. // If this module import was due to an inclusion directive, create an
  15179. // implicit import declaration to capture it in the AST.
  15180. if (ShouldAddImport) {
  15181. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  15182. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  15183. DirectiveLoc, Mod,
  15184. DirectiveLoc);
  15185. if (!ModuleScopes.empty())
  15186. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  15187. TU->addDecl(ImportD);
  15188. Consumer.HandleImplicitImportDecl(ImportD);
  15189. }
  15190. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  15191. VisibleModules.setVisible(Mod, DirectiveLoc);
  15192. }
  15193. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  15194. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  15195. ModuleScopes.push_back({});
  15196. ModuleScopes.back().Module = Mod;
  15197. if (getLangOpts().ModulesLocalVisibility)
  15198. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  15199. VisibleModules.setVisible(Mod, DirectiveLoc);
  15200. // The enclosing context is now part of this module.
  15201. // FIXME: Consider creating a child DeclContext to hold the entities
  15202. // lexically within the module.
  15203. if (getLangOpts().trackLocalOwningModule()) {
  15204. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  15205. cast<Decl>(DC)->setModuleOwnershipKind(
  15206. getLangOpts().ModulesLocalVisibility
  15207. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  15208. : Decl::ModuleOwnershipKind::Visible);
  15209. cast<Decl>(DC)->setLocalOwningModule(Mod);
  15210. }
  15211. }
  15212. }
  15213. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  15214. if (getLangOpts().ModulesLocalVisibility) {
  15215. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  15216. // Leaving a module hides namespace names, so our visible namespace cache
  15217. // is now out of date.
  15218. VisibleNamespaceCache.clear();
  15219. }
  15220. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  15221. "left the wrong module scope");
  15222. ModuleScopes.pop_back();
  15223. // We got to the end of processing a local module. Create an
  15224. // ImportDecl as we would for an imported module.
  15225. FileID File = getSourceManager().getFileID(EomLoc);
  15226. SourceLocation DirectiveLoc;
  15227. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  15228. // We reached the end of a #included module header. Use the #include loc.
  15229. assert(File != getSourceManager().getMainFileID() &&
  15230. "end of submodule in main source file");
  15231. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  15232. } else {
  15233. // We reached an EOM pragma. Use the pragma location.
  15234. DirectiveLoc = EomLoc;
  15235. }
  15236. BuildModuleInclude(DirectiveLoc, Mod);
  15237. // Any further declarations are in whatever module we returned to.
  15238. if (getLangOpts().trackLocalOwningModule()) {
  15239. // The parser guarantees that this is the same context that we entered
  15240. // the module within.
  15241. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  15242. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  15243. if (!getCurrentModule())
  15244. cast<Decl>(DC)->setModuleOwnershipKind(
  15245. Decl::ModuleOwnershipKind::Unowned);
  15246. }
  15247. }
  15248. }
  15249. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  15250. Module *Mod) {
  15251. // Bail if we're not allowed to implicitly import a module here.
  15252. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  15253. VisibleModules.isVisible(Mod))
  15254. return;
  15255. // Create the implicit import declaration.
  15256. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  15257. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  15258. Loc, Mod, Loc);
  15259. TU->addDecl(ImportD);
  15260. Consumer.HandleImplicitImportDecl(ImportD);
  15261. // Make the module visible.
  15262. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  15263. VisibleModules.setVisible(Mod, Loc);
  15264. }
  15265. /// We have parsed the start of an export declaration, including the '{'
  15266. /// (if present).
  15267. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  15268. SourceLocation LBraceLoc) {
  15269. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  15270. // C++ Modules TS draft:
  15271. // An export-declaration shall appear in the purview of a module other than
  15272. // the global module.
  15273. if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
  15274. Diag(ExportLoc, diag::err_export_not_in_module_interface);
  15275. // An export-declaration [...] shall not contain more than one
  15276. // export keyword.
  15277. //
  15278. // The intent here is that an export-declaration cannot appear within another
  15279. // export-declaration.
  15280. if (D->isExported())
  15281. Diag(ExportLoc, diag::err_export_within_export);
  15282. CurContext->addDecl(D);
  15283. PushDeclContext(S, D);
  15284. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  15285. return D;
  15286. }
  15287. /// Complete the definition of an export declaration.
  15288. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  15289. auto *ED = cast<ExportDecl>(D);
  15290. if (RBraceLoc.isValid())
  15291. ED->setRBraceLoc(RBraceLoc);
  15292. // FIXME: Diagnose export of internal-linkage declaration (including
  15293. // anonymous namespace).
  15294. PopDeclContext();
  15295. return D;
  15296. }
  15297. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  15298. IdentifierInfo* AliasName,
  15299. SourceLocation PragmaLoc,
  15300. SourceLocation NameLoc,
  15301. SourceLocation AliasNameLoc) {
  15302. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  15303. LookupOrdinaryName);
  15304. AsmLabelAttr *Attr =
  15305. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  15306. // If a declaration that:
  15307. // 1) declares a function or a variable
  15308. // 2) has external linkage
  15309. // already exists, add a label attribute to it.
  15310. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15311. if (isDeclExternC(PrevDecl))
  15312. PrevDecl->addAttr(Attr);
  15313. else
  15314. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  15315. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  15316. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  15317. } else
  15318. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  15319. }
  15320. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  15321. SourceLocation PragmaLoc,
  15322. SourceLocation NameLoc) {
  15323. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  15324. if (PrevDecl) {
  15325. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  15326. } else {
  15327. (void)WeakUndeclaredIdentifiers.insert(
  15328. std::pair<IdentifierInfo*,WeakInfo>
  15329. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  15330. }
  15331. }
  15332. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  15333. IdentifierInfo* AliasName,
  15334. SourceLocation PragmaLoc,
  15335. SourceLocation NameLoc,
  15336. SourceLocation AliasNameLoc) {
  15337. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  15338. LookupOrdinaryName);
  15339. WeakInfo W = WeakInfo(Name, NameLoc);
  15340. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  15341. if (!PrevDecl->hasAttr<AliasAttr>())
  15342. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  15343. DeclApplyPragmaWeak(TUScope, ND, W);
  15344. } else {
  15345. (void)WeakUndeclaredIdentifiers.insert(
  15346. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  15347. }
  15348. }
  15349. Decl *Sema::getObjCDeclContext() const {
  15350. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  15351. }