SemaDecl.cpp 654 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886
  1. //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements semantic analysis for declarations.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TypeLocBuilder.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTLambda.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/CharUnits.h"
  19. #include "clang/AST/CommentDiagnostic.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/EvaluatedExprVisitor.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/Basic/Builtins.h"
  27. #include "clang/Basic/PartialDiagnostic.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
  31. #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
  32. #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
  33. #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
  34. #include "clang/Sema/CXXFieldCollector.h"
  35. #include "clang/Sema/DeclSpec.h"
  36. #include "clang/Sema/DelayedDiagnostic.h"
  37. #include "clang/Sema/Initialization.h"
  38. #include "clang/Sema/Lookup.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/SemaInternal.h"
  43. #include "clang/Sema/Template.h"
  44. #include "llvm/ADT/SmallString.h"
  45. #include "llvm/ADT/Triple.h"
  46. #include <algorithm>
  47. #include <cstring>
  48. #include <functional>
  49. using namespace clang;
  50. using namespace sema;
  51. Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
  52. if (OwnedType) {
  53. Decl *Group[2] = { OwnedType, Ptr };
  54. return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
  55. }
  56. return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
  57. }
  58. namespace {
  59. class TypeNameValidatorCCC : public CorrectionCandidateCallback {
  60. public:
  61. TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
  62. bool AllowTemplates = false,
  63. bool AllowNonTemplates = true)
  64. : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
  65. AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
  66. WantExpressionKeywords = false;
  67. WantCXXNamedCasts = false;
  68. WantRemainingKeywords = false;
  69. }
  70. bool ValidateCandidate(const TypoCorrection &candidate) override {
  71. if (NamedDecl *ND = candidate.getCorrectionDecl()) {
  72. if (!AllowInvalidDecl && ND->isInvalidDecl())
  73. return false;
  74. if (getAsTypeTemplateDecl(ND))
  75. return AllowTemplates;
  76. bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  77. if (!IsType)
  78. return false;
  79. if (AllowNonTemplates)
  80. return true;
  81. // An injected-class-name of a class template (specialization) is valid
  82. // as a template or as a non-template.
  83. if (AllowTemplates) {
  84. auto *RD = dyn_cast<CXXRecordDecl>(ND);
  85. if (!RD || !RD->isInjectedClassName())
  86. return false;
  87. RD = cast<CXXRecordDecl>(RD->getDeclContext());
  88. return RD->getDescribedClassTemplate() ||
  89. isa<ClassTemplateSpecializationDecl>(RD);
  90. }
  91. return false;
  92. }
  93. return !WantClassName && candidate.isKeyword();
  94. }
  95. private:
  96. bool AllowInvalidDecl;
  97. bool WantClassName;
  98. bool AllowTemplates;
  99. bool AllowNonTemplates;
  100. };
  101. } // end anonymous namespace
  102. /// Determine whether the token kind starts a simple-type-specifier.
  103. bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
  104. switch (Kind) {
  105. // FIXME: Take into account the current language when deciding whether a
  106. // token kind is a valid type specifier
  107. case tok::kw_short:
  108. case tok::kw_long:
  109. case tok::kw___int64:
  110. case tok::kw___int128:
  111. case tok::kw_signed:
  112. case tok::kw_unsigned:
  113. case tok::kw_void:
  114. case tok::kw_char:
  115. case tok::kw_int:
  116. case tok::kw_half:
  117. case tok::kw_float:
  118. case tok::kw_double:
  119. case tok::kw__Float16:
  120. case tok::kw___float128:
  121. case tok::kw_wchar_t:
  122. case tok::kw_bool:
  123. case tok::kw___underlying_type:
  124. case tok::kw___auto_type:
  125. return true;
  126. case tok::annot_typename:
  127. case tok::kw_char16_t:
  128. case tok::kw_char32_t:
  129. case tok::kw_typeof:
  130. case tok::annot_decltype:
  131. case tok::kw_decltype:
  132. return getLangOpts().CPlusPlus;
  133. case tok::kw_char8_t:
  134. return getLangOpts().Char8;
  135. default:
  136. break;
  137. }
  138. return false;
  139. }
  140. namespace {
  141. enum class UnqualifiedTypeNameLookupResult {
  142. NotFound,
  143. FoundNonType,
  144. FoundType
  145. };
  146. } // end anonymous namespace
  147. /// Tries to perform unqualified lookup of the type decls in bases for
  148. /// dependent class.
  149. /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
  150. /// type decl, \a FoundType if only type decls are found.
  151. static UnqualifiedTypeNameLookupResult
  152. lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
  153. SourceLocation NameLoc,
  154. const CXXRecordDecl *RD) {
  155. if (!RD->hasDefinition())
  156. return UnqualifiedTypeNameLookupResult::NotFound;
  157. // Look for type decls in base classes.
  158. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  159. UnqualifiedTypeNameLookupResult::NotFound;
  160. for (const auto &Base : RD->bases()) {
  161. const CXXRecordDecl *BaseRD = nullptr;
  162. if (auto *BaseTT = Base.getType()->getAs<TagType>())
  163. BaseRD = BaseTT->getAsCXXRecordDecl();
  164. else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
  165. // Look for type decls in dependent base classes that have known primary
  166. // templates.
  167. if (!TST || !TST->isDependentType())
  168. continue;
  169. auto *TD = TST->getTemplateName().getAsTemplateDecl();
  170. if (!TD)
  171. continue;
  172. if (auto *BasePrimaryTemplate =
  173. dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
  174. if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
  175. BaseRD = BasePrimaryTemplate;
  176. else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
  177. if (const ClassTemplatePartialSpecializationDecl *PS =
  178. CTD->findPartialSpecialization(Base.getType()))
  179. if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
  180. BaseRD = PS;
  181. }
  182. }
  183. }
  184. if (BaseRD) {
  185. for (NamedDecl *ND : BaseRD->lookup(&II)) {
  186. if (!isa<TypeDecl>(ND))
  187. return UnqualifiedTypeNameLookupResult::FoundNonType;
  188. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  189. }
  190. if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
  191. switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
  192. case UnqualifiedTypeNameLookupResult::FoundNonType:
  193. return UnqualifiedTypeNameLookupResult::FoundNonType;
  194. case UnqualifiedTypeNameLookupResult::FoundType:
  195. FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
  196. break;
  197. case UnqualifiedTypeNameLookupResult::NotFound:
  198. break;
  199. }
  200. }
  201. }
  202. }
  203. return FoundTypeDecl;
  204. }
  205. static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
  206. const IdentifierInfo &II,
  207. SourceLocation NameLoc) {
  208. // Lookup in the parent class template context, if any.
  209. const CXXRecordDecl *RD = nullptr;
  210. UnqualifiedTypeNameLookupResult FoundTypeDecl =
  211. UnqualifiedTypeNameLookupResult::NotFound;
  212. for (DeclContext *DC = S.CurContext;
  213. DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
  214. DC = DC->getParent()) {
  215. // Look for type decls in dependent base classes that have known primary
  216. // templates.
  217. RD = dyn_cast<CXXRecordDecl>(DC);
  218. if (RD && RD->getDescribedClassTemplate())
  219. FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
  220. }
  221. if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
  222. return nullptr;
  223. // We found some types in dependent base classes. Recover as if the user
  224. // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
  225. // lookup during template instantiation.
  226. S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
  227. ASTContext &Context = S.Context;
  228. auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
  229. cast<Type>(Context.getRecordType(RD)));
  230. QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
  231. CXXScopeSpec SS;
  232. SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  233. TypeLocBuilder Builder;
  234. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  235. DepTL.setNameLoc(NameLoc);
  236. DepTL.setElaboratedKeywordLoc(SourceLocation());
  237. DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
  238. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  239. }
  240. /// If the identifier refers to a type name within this scope,
  241. /// return the declaration of that type.
  242. ///
  243. /// This routine performs ordinary name lookup of the identifier II
  244. /// within the given scope, with optional C++ scope specifier SS, to
  245. /// determine whether the name refers to a type. If so, returns an
  246. /// opaque pointer (actually a QualType) corresponding to that
  247. /// type. Otherwise, returns NULL.
  248. ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
  249. Scope *S, CXXScopeSpec *SS,
  250. bool isClassName, bool HasTrailingDot,
  251. ParsedType ObjectTypePtr,
  252. bool IsCtorOrDtorName,
  253. bool WantNontrivialTypeSourceInfo,
  254. bool IsClassTemplateDeductionContext,
  255. IdentifierInfo **CorrectedII) {
  256. // FIXME: Consider allowing this outside C++1z mode as an extension.
  257. bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
  258. getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
  259. !isClassName && !HasTrailingDot;
  260. // Determine where we will perform name lookup.
  261. DeclContext *LookupCtx = nullptr;
  262. if (ObjectTypePtr) {
  263. QualType ObjectType = ObjectTypePtr.get();
  264. if (ObjectType->isRecordType())
  265. LookupCtx = computeDeclContext(ObjectType);
  266. } else if (SS && SS->isNotEmpty()) {
  267. LookupCtx = computeDeclContext(*SS, false);
  268. if (!LookupCtx) {
  269. if (isDependentScopeSpecifier(*SS)) {
  270. // C++ [temp.res]p3:
  271. // A qualified-id that refers to a type and in which the
  272. // nested-name-specifier depends on a template-parameter (14.6.2)
  273. // shall be prefixed by the keyword typename to indicate that the
  274. // qualified-id denotes a type, forming an
  275. // elaborated-type-specifier (7.1.5.3).
  276. //
  277. // We therefore do not perform any name lookup if the result would
  278. // refer to a member of an unknown specialization.
  279. if (!isClassName && !IsCtorOrDtorName)
  280. return nullptr;
  281. // We know from the grammar that this name refers to a type,
  282. // so build a dependent node to describe the type.
  283. if (WantNontrivialTypeSourceInfo)
  284. return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
  285. NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
  286. QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
  287. II, NameLoc);
  288. return ParsedType::make(T);
  289. }
  290. return nullptr;
  291. }
  292. if (!LookupCtx->isDependentContext() &&
  293. RequireCompleteDeclContext(*SS, LookupCtx))
  294. return nullptr;
  295. }
  296. // FIXME: LookupNestedNameSpecifierName isn't the right kind of
  297. // lookup for class-names.
  298. LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
  299. LookupOrdinaryName;
  300. LookupResult Result(*this, &II, NameLoc, Kind);
  301. if (LookupCtx) {
  302. // Perform "qualified" name lookup into the declaration context we
  303. // computed, which is either the type of the base of a member access
  304. // expression or the declaration context associated with a prior
  305. // nested-name-specifier.
  306. LookupQualifiedName(Result, LookupCtx);
  307. if (ObjectTypePtr && Result.empty()) {
  308. // C++ [basic.lookup.classref]p3:
  309. // If the unqualified-id is ~type-name, the type-name is looked up
  310. // in the context of the entire postfix-expression. If the type T of
  311. // the object expression is of a class type C, the type-name is also
  312. // looked up in the scope of class C. At least one of the lookups shall
  313. // find a name that refers to (possibly cv-qualified) T.
  314. LookupName(Result, S);
  315. }
  316. } else {
  317. // Perform unqualified name lookup.
  318. LookupName(Result, S);
  319. // For unqualified lookup in a class template in MSVC mode, look into
  320. // dependent base classes where the primary class template is known.
  321. if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
  322. if (ParsedType TypeInBase =
  323. recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
  324. return TypeInBase;
  325. }
  326. }
  327. NamedDecl *IIDecl = nullptr;
  328. switch (Result.getResultKind()) {
  329. case LookupResult::NotFound:
  330. case LookupResult::NotFoundInCurrentInstantiation:
  331. if (CorrectedII) {
  332. TypoCorrection Correction =
  333. CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
  334. llvm::make_unique<TypeNameValidatorCCC>(
  335. true, isClassName, AllowDeducedTemplate),
  336. CTK_ErrorRecovery);
  337. IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
  338. TemplateTy Template;
  339. bool MemberOfUnknownSpecialization;
  340. UnqualifiedId TemplateName;
  341. TemplateName.setIdentifier(NewII, NameLoc);
  342. NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
  343. CXXScopeSpec NewSS, *NewSSPtr = SS;
  344. if (SS && NNS) {
  345. NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  346. NewSSPtr = &NewSS;
  347. }
  348. if (Correction && (NNS || NewII != &II) &&
  349. // Ignore a correction to a template type as the to-be-corrected
  350. // identifier is not a template (typo correction for template names
  351. // is handled elsewhere).
  352. !(getLangOpts().CPlusPlus && NewSSPtr &&
  353. isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
  354. Template, MemberOfUnknownSpecialization))) {
  355. ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
  356. isClassName, HasTrailingDot, ObjectTypePtr,
  357. IsCtorOrDtorName,
  358. WantNontrivialTypeSourceInfo,
  359. IsClassTemplateDeductionContext);
  360. if (Ty) {
  361. diagnoseTypo(Correction,
  362. PDiag(diag::err_unknown_type_or_class_name_suggest)
  363. << Result.getLookupName() << isClassName);
  364. if (SS && NNS)
  365. SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
  366. *CorrectedII = NewII;
  367. return Ty;
  368. }
  369. }
  370. }
  371. // If typo correction failed or was not performed, fall through
  372. LLVM_FALLTHROUGH;
  373. case LookupResult::FoundOverloaded:
  374. case LookupResult::FoundUnresolvedValue:
  375. Result.suppressDiagnostics();
  376. return nullptr;
  377. case LookupResult::Ambiguous:
  378. // Recover from type-hiding ambiguities by hiding the type. We'll
  379. // do the lookup again when looking for an object, and we can
  380. // diagnose the error then. If we don't do this, then the error
  381. // about hiding the type will be immediately followed by an error
  382. // that only makes sense if the identifier was treated like a type.
  383. if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
  384. Result.suppressDiagnostics();
  385. return nullptr;
  386. }
  387. // Look to see if we have a type anywhere in the list of results.
  388. for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
  389. Res != ResEnd; ++Res) {
  390. if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
  391. (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
  392. if (!IIDecl ||
  393. (*Res)->getLocation().getRawEncoding() <
  394. IIDecl->getLocation().getRawEncoding())
  395. IIDecl = *Res;
  396. }
  397. }
  398. if (!IIDecl) {
  399. // None of the entities we found is a type, so there is no way
  400. // to even assume that the result is a type. In this case, don't
  401. // complain about the ambiguity. The parser will either try to
  402. // perform this lookup again (e.g., as an object name), which
  403. // will produce the ambiguity, or will complain that it expected
  404. // a type name.
  405. Result.suppressDiagnostics();
  406. return nullptr;
  407. }
  408. // We found a type within the ambiguous lookup; diagnose the
  409. // ambiguity and then return that type. This might be the right
  410. // answer, or it might not be, but it suppresses any attempt to
  411. // perform the name lookup again.
  412. break;
  413. case LookupResult::Found:
  414. IIDecl = Result.getFoundDecl();
  415. break;
  416. }
  417. assert(IIDecl && "Didn't find decl");
  418. QualType T;
  419. if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
  420. // C++ [class.qual]p2: A lookup that would find the injected-class-name
  421. // instead names the constructors of the class, except when naming a class.
  422. // This is ill-formed when we're not actually forming a ctor or dtor name.
  423. auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
  424. auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
  425. if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
  426. FoundRD->isInjectedClassName() &&
  427. declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
  428. Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
  429. << &II << /*Type*/1;
  430. DiagnoseUseOfDecl(IIDecl, NameLoc);
  431. T = Context.getTypeDeclType(TD);
  432. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  433. } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
  434. (void)DiagnoseUseOfDecl(IDecl, NameLoc);
  435. if (!HasTrailingDot)
  436. T = Context.getObjCInterfaceType(IDecl);
  437. } else if (AllowDeducedTemplate) {
  438. if (auto *TD = getAsTypeTemplateDecl(IIDecl))
  439. T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
  440. QualType(), false);
  441. }
  442. if (T.isNull()) {
  443. // If it's not plausibly a type, suppress diagnostics.
  444. Result.suppressDiagnostics();
  445. return nullptr;
  446. }
  447. // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
  448. // constructor or destructor name (in such a case, the scope specifier
  449. // will be attached to the enclosing Expr or Decl node).
  450. if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
  451. !isa<ObjCInterfaceDecl>(IIDecl)) {
  452. if (WantNontrivialTypeSourceInfo) {
  453. // Construct a type with type-source information.
  454. TypeLocBuilder Builder;
  455. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  456. T = getElaboratedType(ETK_None, *SS, T);
  457. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  458. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  459. ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
  460. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  461. } else {
  462. T = getElaboratedType(ETK_None, *SS, T);
  463. }
  464. }
  465. return ParsedType::make(T);
  466. }
  467. // Builds a fake NNS for the given decl context.
  468. static NestedNameSpecifier *
  469. synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
  470. for (;; DC = DC->getLookupParent()) {
  471. DC = DC->getPrimaryContext();
  472. auto *ND = dyn_cast<NamespaceDecl>(DC);
  473. if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
  474. return NestedNameSpecifier::Create(Context, nullptr, ND);
  475. else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
  476. return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  477. RD->getTypeForDecl());
  478. else if (isa<TranslationUnitDecl>(DC))
  479. return NestedNameSpecifier::GlobalSpecifier(Context);
  480. }
  481. llvm_unreachable("something isn't in TU scope?");
  482. }
  483. /// Find the parent class with dependent bases of the innermost enclosing method
  484. /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
  485. /// up allowing unqualified dependent type names at class-level, which MSVC
  486. /// correctly rejects.
  487. static const CXXRecordDecl *
  488. findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
  489. for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
  490. DC = DC->getPrimaryContext();
  491. if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
  492. if (MD->getParent()->hasAnyDependentBases())
  493. return MD->getParent();
  494. }
  495. return nullptr;
  496. }
  497. ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
  498. SourceLocation NameLoc,
  499. bool IsTemplateTypeArg) {
  500. assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
  501. NestedNameSpecifier *NNS = nullptr;
  502. if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
  503. // If we weren't able to parse a default template argument, delay lookup
  504. // until instantiation time by making a non-dependent DependentTypeName. We
  505. // pretend we saw a NestedNameSpecifier referring to the current scope, and
  506. // lookup is retried.
  507. // FIXME: This hurts our diagnostic quality, since we get errors like "no
  508. // type named 'Foo' in 'current_namespace'" when the user didn't write any
  509. // name specifiers.
  510. NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
  511. Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
  512. } else if (const CXXRecordDecl *RD =
  513. findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
  514. // Build a DependentNameType that will perform lookup into RD at
  515. // instantiation time.
  516. NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
  517. RD->getTypeForDecl());
  518. // Diagnose that this identifier was undeclared, and retry the lookup during
  519. // template instantiation.
  520. Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
  521. << RD;
  522. } else {
  523. // This is not a situation that we should recover from.
  524. return ParsedType();
  525. }
  526. QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
  527. // Build type location information. We synthesized the qualifier, so we have
  528. // to build a fake NestedNameSpecifierLoc.
  529. NestedNameSpecifierLocBuilder NNSLocBuilder;
  530. NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
  531. NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
  532. TypeLocBuilder Builder;
  533. DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
  534. DepTL.setNameLoc(NameLoc);
  535. DepTL.setElaboratedKeywordLoc(SourceLocation());
  536. DepTL.setQualifierLoc(QualifierLoc);
  537. return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  538. }
  539. /// isTagName() - This method is called *for error recovery purposes only*
  540. /// to determine if the specified name is a valid tag name ("struct foo"). If
  541. /// so, this returns the TST for the tag corresponding to it (TST_enum,
  542. /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
  543. /// cases in C where the user forgot to specify the tag.
  544. DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
  545. // Do a tag name lookup in this scope.
  546. LookupResult R(*this, &II, SourceLocation(), LookupTagName);
  547. LookupName(R, S, false);
  548. R.suppressDiagnostics();
  549. if (R.getResultKind() == LookupResult::Found)
  550. if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
  551. switch (TD->getTagKind()) {
  552. case TTK_Struct: return DeclSpec::TST_struct;
  553. case TTK_Interface: return DeclSpec::TST_interface;
  554. case TTK_Union: return DeclSpec::TST_union;
  555. case TTK_Class: return DeclSpec::TST_class;
  556. case TTK_Enum: return DeclSpec::TST_enum;
  557. }
  558. }
  559. return DeclSpec::TST_unspecified;
  560. }
  561. /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
  562. /// if a CXXScopeSpec's type is equal to the type of one of the base classes
  563. /// then downgrade the missing typename error to a warning.
  564. /// This is needed for MSVC compatibility; Example:
  565. /// @code
  566. /// template<class T> class A {
  567. /// public:
  568. /// typedef int TYPE;
  569. /// };
  570. /// template<class T> class B : public A<T> {
  571. /// public:
  572. /// A<T>::TYPE a; // no typename required because A<T> is a base class.
  573. /// };
  574. /// @endcode
  575. bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
  576. if (CurContext->isRecord()) {
  577. if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
  578. return true;
  579. const Type *Ty = SS->getScopeRep()->getAsType();
  580. CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
  581. for (const auto &Base : RD->bases())
  582. if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
  583. return true;
  584. return S->isFunctionPrototypeScope();
  585. }
  586. return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
  587. }
  588. void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
  589. SourceLocation IILoc,
  590. Scope *S,
  591. CXXScopeSpec *SS,
  592. ParsedType &SuggestedType,
  593. bool IsTemplateName) {
  594. // Don't report typename errors for editor placeholders.
  595. if (II->isEditorPlaceholder())
  596. return;
  597. // We don't have anything to suggest (yet).
  598. SuggestedType = nullptr;
  599. // There may have been a typo in the name of the type. Look up typo
  600. // results, in case we have something that we can suggest.
  601. if (TypoCorrection Corrected =
  602. CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
  603. llvm::make_unique<TypeNameValidatorCCC>(
  604. false, false, IsTemplateName, !IsTemplateName),
  605. CTK_ErrorRecovery)) {
  606. // FIXME: Support error recovery for the template-name case.
  607. bool CanRecover = !IsTemplateName;
  608. if (Corrected.isKeyword()) {
  609. // We corrected to a keyword.
  610. diagnoseTypo(Corrected,
  611. PDiag(IsTemplateName ? diag::err_no_template_suggest
  612. : diag::err_unknown_typename_suggest)
  613. << II);
  614. II = Corrected.getCorrectionAsIdentifierInfo();
  615. } else {
  616. // We found a similarly-named type or interface; suggest that.
  617. if (!SS || !SS->isSet()) {
  618. diagnoseTypo(Corrected,
  619. PDiag(IsTemplateName ? diag::err_no_template_suggest
  620. : diag::err_unknown_typename_suggest)
  621. << II, CanRecover);
  622. } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
  623. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  624. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  625. II->getName().equals(CorrectedStr);
  626. diagnoseTypo(Corrected,
  627. PDiag(IsTemplateName
  628. ? diag::err_no_member_template_suggest
  629. : diag::err_unknown_nested_typename_suggest)
  630. << II << DC << DroppedSpecifier << SS->getRange(),
  631. CanRecover);
  632. } else {
  633. llvm_unreachable("could not have corrected a typo here");
  634. }
  635. if (!CanRecover)
  636. return;
  637. CXXScopeSpec tmpSS;
  638. if (Corrected.getCorrectionSpecifier())
  639. tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
  640. SourceRange(IILoc));
  641. // FIXME: Support class template argument deduction here.
  642. SuggestedType =
  643. getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
  644. tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
  645. /*IsCtorOrDtorName=*/false,
  646. /*NonTrivialTypeSourceInfo=*/true);
  647. }
  648. return;
  649. }
  650. if (getLangOpts().CPlusPlus && !IsTemplateName) {
  651. // See if II is a class template that the user forgot to pass arguments to.
  652. UnqualifiedId Name;
  653. Name.setIdentifier(II, IILoc);
  654. CXXScopeSpec EmptySS;
  655. TemplateTy TemplateResult;
  656. bool MemberOfUnknownSpecialization;
  657. if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
  658. Name, nullptr, true, TemplateResult,
  659. MemberOfUnknownSpecialization) == TNK_Type_template) {
  660. diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
  661. return;
  662. }
  663. }
  664. // FIXME: Should we move the logic that tries to recover from a missing tag
  665. // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
  666. if (!SS || (!SS->isSet() && !SS->isInvalid()))
  667. Diag(IILoc, IsTemplateName ? diag::err_no_template
  668. : diag::err_unknown_typename)
  669. << II;
  670. else if (DeclContext *DC = computeDeclContext(*SS, false))
  671. Diag(IILoc, IsTemplateName ? diag::err_no_member_template
  672. : diag::err_typename_nested_not_found)
  673. << II << DC << SS->getRange();
  674. else if (isDependentScopeSpecifier(*SS)) {
  675. unsigned DiagID = diag::err_typename_missing;
  676. if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
  677. DiagID = diag::ext_typename_missing;
  678. Diag(SS->getRange().getBegin(), DiagID)
  679. << SS->getScopeRep() << II->getName()
  680. << SourceRange(SS->getRange().getBegin(), IILoc)
  681. << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
  682. SuggestedType = ActOnTypenameType(S, SourceLocation(),
  683. *SS, *II, IILoc).get();
  684. } else {
  685. assert(SS && SS->isInvalid() &&
  686. "Invalid scope specifier has already been diagnosed");
  687. }
  688. }
  689. /// Determine whether the given result set contains either a type name
  690. /// or
  691. static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
  692. bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
  693. NextToken.is(tok::less);
  694. for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
  695. if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
  696. return true;
  697. if (CheckTemplate && isa<TemplateDecl>(*I))
  698. return true;
  699. }
  700. return false;
  701. }
  702. static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
  703. Scope *S, CXXScopeSpec &SS,
  704. IdentifierInfo *&Name,
  705. SourceLocation NameLoc) {
  706. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
  707. SemaRef.LookupParsedName(R, S, &SS);
  708. if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
  709. StringRef FixItTagName;
  710. switch (Tag->getTagKind()) {
  711. case TTK_Class:
  712. FixItTagName = "class ";
  713. break;
  714. case TTK_Enum:
  715. FixItTagName = "enum ";
  716. break;
  717. case TTK_Struct:
  718. FixItTagName = "struct ";
  719. break;
  720. case TTK_Interface:
  721. FixItTagName = "__interface ";
  722. break;
  723. case TTK_Union:
  724. FixItTagName = "union ";
  725. break;
  726. }
  727. StringRef TagName = FixItTagName.drop_back();
  728. SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
  729. << Name << TagName << SemaRef.getLangOpts().CPlusPlus
  730. << FixItHint::CreateInsertion(NameLoc, FixItTagName);
  731. for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
  732. I != IEnd; ++I)
  733. SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
  734. << Name << TagName;
  735. // Replace lookup results with just the tag decl.
  736. Result.clear(Sema::LookupTagName);
  737. SemaRef.LookupParsedName(Result, S, &SS);
  738. return true;
  739. }
  740. return false;
  741. }
  742. /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
  743. static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
  744. QualType T, SourceLocation NameLoc) {
  745. ASTContext &Context = S.Context;
  746. TypeLocBuilder Builder;
  747. Builder.pushTypeSpec(T).setNameLoc(NameLoc);
  748. T = S.getElaboratedType(ETK_None, SS, T);
  749. ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
  750. ElabTL.setElaboratedKeywordLoc(SourceLocation());
  751. ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
  752. return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
  753. }
  754. Sema::NameClassification
  755. Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
  756. SourceLocation NameLoc, const Token &NextToken,
  757. bool IsAddressOfOperand,
  758. std::unique_ptr<CorrectionCandidateCallback> CCC) {
  759. DeclarationNameInfo NameInfo(Name, NameLoc);
  760. ObjCMethodDecl *CurMethod = getCurMethodDecl();
  761. if (NextToken.is(tok::coloncolon)) {
  762. NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
  763. BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
  764. } else if (getLangOpts().CPlusPlus && SS.isSet() &&
  765. isCurrentClassName(*Name, S, &SS)) {
  766. // Per [class.qual]p2, this names the constructors of SS, not the
  767. // injected-class-name. We don't have a classification for that.
  768. // There's not much point caching this result, since the parser
  769. // will reject it later.
  770. return NameClassification::Unknown();
  771. }
  772. LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
  773. LookupParsedName(Result, S, &SS, !CurMethod);
  774. // For unqualified lookup in a class template in MSVC mode, look into
  775. // dependent base classes where the primary class template is known.
  776. if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
  777. if (ParsedType TypeInBase =
  778. recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
  779. return TypeInBase;
  780. }
  781. // Perform lookup for Objective-C instance variables (including automatically
  782. // synthesized instance variables), if we're in an Objective-C method.
  783. // FIXME: This lookup really, really needs to be folded in to the normal
  784. // unqualified lookup mechanism.
  785. if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
  786. ExprResult E = LookupInObjCMethod(Result, S, Name, true);
  787. if (E.get() || E.isInvalid())
  788. return E;
  789. }
  790. bool SecondTry = false;
  791. bool IsFilteredTemplateName = false;
  792. Corrected:
  793. switch (Result.getResultKind()) {
  794. case LookupResult::NotFound:
  795. // If an unqualified-id is followed by a '(', then we have a function
  796. // call.
  797. if (!SS.isSet() && NextToken.is(tok::l_paren)) {
  798. // In C++, this is an ADL-only call.
  799. // FIXME: Reference?
  800. if (getLangOpts().CPlusPlus)
  801. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
  802. // C90 6.3.2.2:
  803. // If the expression that precedes the parenthesized argument list in a
  804. // function call consists solely of an identifier, and if no
  805. // declaration is visible for this identifier, the identifier is
  806. // implicitly declared exactly as if, in the innermost block containing
  807. // the function call, the declaration
  808. //
  809. // extern int identifier ();
  810. //
  811. // appeared.
  812. //
  813. // We also allow this in C99 as an extension.
  814. if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
  815. Result.addDecl(D);
  816. Result.resolveKind();
  817. return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
  818. }
  819. }
  820. // In C, we first see whether there is a tag type by the same name, in
  821. // which case it's likely that the user just forgot to write "enum",
  822. // "struct", or "union".
  823. if (!getLangOpts().CPlusPlus && !SecondTry &&
  824. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  825. break;
  826. }
  827. // Perform typo correction to determine if there is another name that is
  828. // close to this name.
  829. if (!SecondTry && CCC) {
  830. SecondTry = true;
  831. if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
  832. Result.getLookupKind(), S,
  833. &SS, std::move(CCC),
  834. CTK_ErrorRecovery)) {
  835. unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
  836. unsigned QualifiedDiag = diag::err_no_member_suggest;
  837. NamedDecl *FirstDecl = Corrected.getFoundDecl();
  838. NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
  839. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  840. UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
  841. UnqualifiedDiag = diag::err_no_template_suggest;
  842. QualifiedDiag = diag::err_no_member_template_suggest;
  843. } else if (UnderlyingFirstDecl &&
  844. (isa<TypeDecl>(UnderlyingFirstDecl) ||
  845. isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
  846. isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
  847. UnqualifiedDiag = diag::err_unknown_typename_suggest;
  848. QualifiedDiag = diag::err_unknown_nested_typename_suggest;
  849. }
  850. if (SS.isEmpty()) {
  851. diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
  852. } else {// FIXME: is this even reachable? Test it.
  853. std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
  854. bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
  855. Name->getName().equals(CorrectedStr);
  856. diagnoseTypo(Corrected, PDiag(QualifiedDiag)
  857. << Name << computeDeclContext(SS, false)
  858. << DroppedSpecifier << SS.getRange());
  859. }
  860. // Update the name, so that the caller has the new name.
  861. Name = Corrected.getCorrectionAsIdentifierInfo();
  862. // Typo correction corrected to a keyword.
  863. if (Corrected.isKeyword())
  864. return Name;
  865. // Also update the LookupResult...
  866. // FIXME: This should probably go away at some point
  867. Result.clear();
  868. Result.setLookupName(Corrected.getCorrection());
  869. if (FirstDecl)
  870. Result.addDecl(FirstDecl);
  871. // If we found an Objective-C instance variable, let
  872. // LookupInObjCMethod build the appropriate expression to
  873. // reference the ivar.
  874. // FIXME: This is a gross hack.
  875. if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
  876. Result.clear();
  877. ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
  878. return E;
  879. }
  880. goto Corrected;
  881. }
  882. }
  883. // We failed to correct; just fall through and let the parser deal with it.
  884. Result.suppressDiagnostics();
  885. return NameClassification::Unknown();
  886. case LookupResult::NotFoundInCurrentInstantiation: {
  887. // We performed name lookup into the current instantiation, and there were
  888. // dependent bases, so we treat this result the same way as any other
  889. // dependent nested-name-specifier.
  890. // C++ [temp.res]p2:
  891. // A name used in a template declaration or definition and that is
  892. // dependent on a template-parameter is assumed not to name a type
  893. // unless the applicable name lookup finds a type name or the name is
  894. // qualified by the keyword typename.
  895. //
  896. // FIXME: If the next token is '<', we might want to ask the parser to
  897. // perform some heroics to see if we actually have a
  898. // template-argument-list, which would indicate a missing 'template'
  899. // keyword here.
  900. return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
  901. NameInfo, IsAddressOfOperand,
  902. /*TemplateArgs=*/nullptr);
  903. }
  904. case LookupResult::Found:
  905. case LookupResult::FoundOverloaded:
  906. case LookupResult::FoundUnresolvedValue:
  907. break;
  908. case LookupResult::Ambiguous:
  909. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  910. hasAnyAcceptableTemplateNames(Result)) {
  911. // C++ [temp.local]p3:
  912. // A lookup that finds an injected-class-name (10.2) can result in an
  913. // ambiguity in certain cases (for example, if it is found in more than
  914. // one base class). If all of the injected-class-names that are found
  915. // refer to specializations of the same class template, and if the name
  916. // is followed by a template-argument-list, the reference refers to the
  917. // class template itself and not a specialization thereof, and is not
  918. // ambiguous.
  919. //
  920. // This filtering can make an ambiguous result into an unambiguous one,
  921. // so try again after filtering out template names.
  922. FilterAcceptableTemplateNames(Result);
  923. if (!Result.isAmbiguous()) {
  924. IsFilteredTemplateName = true;
  925. break;
  926. }
  927. }
  928. // Diagnose the ambiguity and return an error.
  929. return NameClassification::Error();
  930. }
  931. if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
  932. (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
  933. // C++ [temp.names]p3:
  934. // After name lookup (3.4) finds that a name is a template-name or that
  935. // an operator-function-id or a literal- operator-id refers to a set of
  936. // overloaded functions any member of which is a function template if
  937. // this is followed by a <, the < is always taken as the delimiter of a
  938. // template-argument-list and never as the less-than operator.
  939. if (!IsFilteredTemplateName)
  940. FilterAcceptableTemplateNames(Result);
  941. if (!Result.empty()) {
  942. bool IsFunctionTemplate;
  943. bool IsVarTemplate;
  944. TemplateName Template;
  945. if (Result.end() - Result.begin() > 1) {
  946. IsFunctionTemplate = true;
  947. Template = Context.getOverloadedTemplateName(Result.begin(),
  948. Result.end());
  949. } else {
  950. TemplateDecl *TD
  951. = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
  952. IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
  953. IsVarTemplate = isa<VarTemplateDecl>(TD);
  954. if (SS.isSet() && !SS.isInvalid())
  955. Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
  956. /*TemplateKeyword=*/false,
  957. TD);
  958. else
  959. Template = TemplateName(TD);
  960. }
  961. if (IsFunctionTemplate) {
  962. // Function templates always go through overload resolution, at which
  963. // point we'll perform the various checks (e.g., accessibility) we need
  964. // to based on which function we selected.
  965. Result.suppressDiagnostics();
  966. return NameClassification::FunctionTemplate(Template);
  967. }
  968. return IsVarTemplate ? NameClassification::VarTemplate(Template)
  969. : NameClassification::TypeTemplate(Template);
  970. }
  971. }
  972. NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
  973. if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
  974. DiagnoseUseOfDecl(Type, NameLoc);
  975. MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
  976. QualType T = Context.getTypeDeclType(Type);
  977. if (SS.isNotEmpty())
  978. return buildNestedType(*this, SS, T, NameLoc);
  979. return ParsedType::make(T);
  980. }
  981. ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
  982. if (!Class) {
  983. // FIXME: It's unfortunate that we don't have a Type node for handling this.
  984. if (ObjCCompatibleAliasDecl *Alias =
  985. dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
  986. Class = Alias->getClassInterface();
  987. }
  988. if (Class) {
  989. DiagnoseUseOfDecl(Class, NameLoc);
  990. if (NextToken.is(tok::period)) {
  991. // Interface. <something> is parsed as a property reference expression.
  992. // Just return "unknown" as a fall-through for now.
  993. Result.suppressDiagnostics();
  994. return NameClassification::Unknown();
  995. }
  996. QualType T = Context.getObjCInterfaceType(Class);
  997. return ParsedType::make(T);
  998. }
  999. // We can have a type template here if we're classifying a template argument.
  1000. if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
  1001. !isa<VarTemplateDecl>(FirstDecl))
  1002. return NameClassification::TypeTemplate(
  1003. TemplateName(cast<TemplateDecl>(FirstDecl)));
  1004. // Check for a tag type hidden by a non-type decl in a few cases where it
  1005. // seems likely a type is wanted instead of the non-type that was found.
  1006. bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
  1007. if ((NextToken.is(tok::identifier) ||
  1008. (NextIsOp &&
  1009. FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
  1010. isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
  1011. TypeDecl *Type = Result.getAsSingle<TypeDecl>();
  1012. DiagnoseUseOfDecl(Type, NameLoc);
  1013. QualType T = Context.getTypeDeclType(Type);
  1014. if (SS.isNotEmpty())
  1015. return buildNestedType(*this, SS, T, NameLoc);
  1016. return ParsedType::make(T);
  1017. }
  1018. if (FirstDecl->isCXXClassMember())
  1019. return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
  1020. nullptr, S);
  1021. bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
  1022. return BuildDeclarationNameExpr(SS, Result, ADL);
  1023. }
  1024. Sema::TemplateNameKindForDiagnostics
  1025. Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
  1026. auto *TD = Name.getAsTemplateDecl();
  1027. if (!TD)
  1028. return TemplateNameKindForDiagnostics::DependentTemplate;
  1029. if (isa<ClassTemplateDecl>(TD))
  1030. return TemplateNameKindForDiagnostics::ClassTemplate;
  1031. if (isa<FunctionTemplateDecl>(TD))
  1032. return TemplateNameKindForDiagnostics::FunctionTemplate;
  1033. if (isa<VarTemplateDecl>(TD))
  1034. return TemplateNameKindForDiagnostics::VarTemplate;
  1035. if (isa<TypeAliasTemplateDecl>(TD))
  1036. return TemplateNameKindForDiagnostics::AliasTemplate;
  1037. if (isa<TemplateTemplateParmDecl>(TD))
  1038. return TemplateNameKindForDiagnostics::TemplateTemplateParam;
  1039. return TemplateNameKindForDiagnostics::DependentTemplate;
  1040. }
  1041. // Determines the context to return to after temporarily entering a
  1042. // context. This depends in an unnecessarily complicated way on the
  1043. // exact ordering of callbacks from the parser.
  1044. DeclContext *Sema::getContainingDC(DeclContext *DC) {
  1045. // Functions defined inline within classes aren't parsed until we've
  1046. // finished parsing the top-level class, so the top-level class is
  1047. // the context we'll need to return to.
  1048. // A Lambda call operator whose parent is a class must not be treated
  1049. // as an inline member function. A Lambda can be used legally
  1050. // either as an in-class member initializer or a default argument. These
  1051. // are parsed once the class has been marked complete and so the containing
  1052. // context would be the nested class (when the lambda is defined in one);
  1053. // If the class is not complete, then the lambda is being used in an
  1054. // ill-formed fashion (such as to specify the width of a bit-field, or
  1055. // in an array-bound) - in which case we still want to return the
  1056. // lexically containing DC (which could be a nested class).
  1057. if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
  1058. DC = DC->getLexicalParent();
  1059. // A function not defined within a class will always return to its
  1060. // lexical context.
  1061. if (!isa<CXXRecordDecl>(DC))
  1062. return DC;
  1063. // A C++ inline method/friend is parsed *after* the topmost class
  1064. // it was declared in is fully parsed ("complete"); the topmost
  1065. // class is the context we need to return to.
  1066. while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
  1067. DC = RD;
  1068. // Return the declaration context of the topmost class the inline method is
  1069. // declared in.
  1070. return DC;
  1071. }
  1072. return DC->getLexicalParent();
  1073. }
  1074. void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
  1075. assert(getContainingDC(DC) == CurContext &&
  1076. "The next DeclContext should be lexically contained in the current one.");
  1077. CurContext = DC;
  1078. S->setEntity(DC);
  1079. }
  1080. void Sema::PopDeclContext() {
  1081. assert(CurContext && "DeclContext imbalance!");
  1082. CurContext = getContainingDC(CurContext);
  1083. assert(CurContext && "Popped translation unit!");
  1084. }
  1085. Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
  1086. Decl *D) {
  1087. // Unlike PushDeclContext, the context to which we return is not necessarily
  1088. // the containing DC of TD, because the new context will be some pre-existing
  1089. // TagDecl definition instead of a fresh one.
  1090. auto Result = static_cast<SkippedDefinitionContext>(CurContext);
  1091. CurContext = cast<TagDecl>(D)->getDefinition();
  1092. assert(CurContext && "skipping definition of undefined tag");
  1093. // Start lookups from the parent of the current context; we don't want to look
  1094. // into the pre-existing complete definition.
  1095. S->setEntity(CurContext->getLookupParent());
  1096. return Result;
  1097. }
  1098. void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
  1099. CurContext = static_cast<decltype(CurContext)>(Context);
  1100. }
  1101. /// EnterDeclaratorContext - Used when we must lookup names in the context
  1102. /// of a declarator's nested name specifier.
  1103. ///
  1104. void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
  1105. // C++0x [basic.lookup.unqual]p13:
  1106. // A name used in the definition of a static data member of class
  1107. // X (after the qualified-id of the static member) is looked up as
  1108. // if the name was used in a member function of X.
  1109. // C++0x [basic.lookup.unqual]p14:
  1110. // If a variable member of a namespace is defined outside of the
  1111. // scope of its namespace then any name used in the definition of
  1112. // the variable member (after the declarator-id) is looked up as
  1113. // if the definition of the variable member occurred in its
  1114. // namespace.
  1115. // Both of these imply that we should push a scope whose context
  1116. // is the semantic context of the declaration. We can't use
  1117. // PushDeclContext here because that context is not necessarily
  1118. // lexically contained in the current context. Fortunately,
  1119. // the containing scope should have the appropriate information.
  1120. assert(!S->getEntity() && "scope already has entity");
  1121. #ifndef NDEBUG
  1122. Scope *Ancestor = S->getParent();
  1123. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1124. assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
  1125. #endif
  1126. CurContext = DC;
  1127. S->setEntity(DC);
  1128. }
  1129. void Sema::ExitDeclaratorContext(Scope *S) {
  1130. assert(S->getEntity() == CurContext && "Context imbalance!");
  1131. // Switch back to the lexical context. The safety of this is
  1132. // enforced by an assert in EnterDeclaratorContext.
  1133. Scope *Ancestor = S->getParent();
  1134. while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
  1135. CurContext = Ancestor->getEntity();
  1136. // We don't need to do anything with the scope, which is going to
  1137. // disappear.
  1138. }
  1139. void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
  1140. // We assume that the caller has already called
  1141. // ActOnReenterTemplateScope so getTemplatedDecl() works.
  1142. FunctionDecl *FD = D->getAsFunction();
  1143. if (!FD)
  1144. return;
  1145. // Same implementation as PushDeclContext, but enters the context
  1146. // from the lexical parent, rather than the top-level class.
  1147. assert(CurContext == FD->getLexicalParent() &&
  1148. "The next DeclContext should be lexically contained in the current one.");
  1149. CurContext = FD;
  1150. S->setEntity(CurContext);
  1151. for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
  1152. ParmVarDecl *Param = FD->getParamDecl(P);
  1153. // If the parameter has an identifier, then add it to the scope
  1154. if (Param->getIdentifier()) {
  1155. S->AddDecl(Param);
  1156. IdResolver.AddDecl(Param);
  1157. }
  1158. }
  1159. }
  1160. void Sema::ActOnExitFunctionContext() {
  1161. // Same implementation as PopDeclContext, but returns to the lexical parent,
  1162. // rather than the top-level class.
  1163. assert(CurContext && "DeclContext imbalance!");
  1164. CurContext = CurContext->getLexicalParent();
  1165. assert(CurContext && "Popped translation unit!");
  1166. }
  1167. /// Determine whether we allow overloading of the function
  1168. /// PrevDecl with another declaration.
  1169. ///
  1170. /// This routine determines whether overloading is possible, not
  1171. /// whether some new function is actually an overload. It will return
  1172. /// true in C++ (where we can always provide overloads) or, as an
  1173. /// extension, in C when the previous function is already an
  1174. /// overloaded function declaration or has the "overloadable"
  1175. /// attribute.
  1176. static bool AllowOverloadingOfFunction(LookupResult &Previous,
  1177. ASTContext &Context,
  1178. const FunctionDecl *New) {
  1179. if (Context.getLangOpts().CPlusPlus)
  1180. return true;
  1181. if (Previous.getResultKind() == LookupResult::FoundOverloaded)
  1182. return true;
  1183. return Previous.getResultKind() == LookupResult::Found &&
  1184. (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
  1185. New->hasAttr<OverloadableAttr>());
  1186. }
  1187. /// Add this decl to the scope shadowed decl chains.
  1188. void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
  1189. // Move up the scope chain until we find the nearest enclosing
  1190. // non-transparent context. The declaration will be introduced into this
  1191. // scope.
  1192. while (S->getEntity() && S->getEntity()->isTransparentContext())
  1193. S = S->getParent();
  1194. // Add scoped declarations into their context, so that they can be
  1195. // found later. Declarations without a context won't be inserted
  1196. // into any context.
  1197. if (AddToContext)
  1198. CurContext->addDecl(D);
  1199. // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
  1200. // are function-local declarations.
  1201. if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
  1202. !D->getDeclContext()->getRedeclContext()->Equals(
  1203. D->getLexicalDeclContext()->getRedeclContext()) &&
  1204. !D->getLexicalDeclContext()->isFunctionOrMethod())
  1205. return;
  1206. // Template instantiations should also not be pushed into scope.
  1207. if (isa<FunctionDecl>(D) &&
  1208. cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
  1209. return;
  1210. // If this replaces anything in the current scope,
  1211. IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
  1212. IEnd = IdResolver.end();
  1213. for (; I != IEnd; ++I) {
  1214. if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
  1215. S->RemoveDecl(*I);
  1216. IdResolver.RemoveDecl(*I);
  1217. // Should only need to replace one decl.
  1218. break;
  1219. }
  1220. }
  1221. S->AddDecl(D);
  1222. if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
  1223. // Implicitly-generated labels may end up getting generated in an order that
  1224. // isn't strictly lexical, which breaks name lookup. Be careful to insert
  1225. // the label at the appropriate place in the identifier chain.
  1226. for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
  1227. DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
  1228. if (IDC == CurContext) {
  1229. if (!S->isDeclScope(*I))
  1230. continue;
  1231. } else if (IDC->Encloses(CurContext))
  1232. break;
  1233. }
  1234. IdResolver.InsertDeclAfter(I, D);
  1235. } else {
  1236. IdResolver.AddDecl(D);
  1237. }
  1238. }
  1239. void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  1240. if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
  1241. TUScope->AddDecl(D);
  1242. }
  1243. bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
  1244. bool AllowInlineNamespace) {
  1245. return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
  1246. }
  1247. Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
  1248. DeclContext *TargetDC = DC->getPrimaryContext();
  1249. do {
  1250. if (DeclContext *ScopeDC = S->getEntity())
  1251. if (ScopeDC->getPrimaryContext() == TargetDC)
  1252. return S;
  1253. } while ((S = S->getParent()));
  1254. return nullptr;
  1255. }
  1256. static bool isOutOfScopePreviousDeclaration(NamedDecl *,
  1257. DeclContext*,
  1258. ASTContext&);
  1259. /// Filters out lookup results that don't fall within the given scope
  1260. /// as determined by isDeclInScope.
  1261. void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
  1262. bool ConsiderLinkage,
  1263. bool AllowInlineNamespace) {
  1264. LookupResult::Filter F = R.makeFilter();
  1265. while (F.hasNext()) {
  1266. NamedDecl *D = F.next();
  1267. if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
  1268. continue;
  1269. if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
  1270. continue;
  1271. F.erase();
  1272. }
  1273. F.done();
  1274. }
  1275. /// We've determined that \p New is a redeclaration of \p Old. Check that they
  1276. /// have compatible owning modules.
  1277. bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
  1278. // FIXME: The Modules TS is not clear about how friend declarations are
  1279. // to be treated. It's not meaningful to have different owning modules for
  1280. // linkage in redeclarations of the same entity, so for now allow the
  1281. // redeclaration and change the owning modules to match.
  1282. if (New->getFriendObjectKind() &&
  1283. Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
  1284. New->setLocalOwningModule(Old->getOwningModule());
  1285. makeMergedDefinitionVisible(New);
  1286. return false;
  1287. }
  1288. Module *NewM = New->getOwningModule();
  1289. Module *OldM = Old->getOwningModule();
  1290. if (NewM == OldM)
  1291. return false;
  1292. // FIXME: Check proclaimed-ownership-declarations here too.
  1293. bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
  1294. bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
  1295. if (NewIsModuleInterface || OldIsModuleInterface) {
  1296. // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
  1297. // if a declaration of D [...] appears in the purview of a module, all
  1298. // other such declarations shall appear in the purview of the same module
  1299. Diag(New->getLocation(), diag::err_mismatched_owning_module)
  1300. << New
  1301. << NewIsModuleInterface
  1302. << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
  1303. << OldIsModuleInterface
  1304. << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
  1305. Diag(Old->getLocation(), diag::note_previous_declaration);
  1306. New->setInvalidDecl();
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. static bool isUsingDecl(NamedDecl *D) {
  1312. return isa<UsingShadowDecl>(D) ||
  1313. isa<UnresolvedUsingTypenameDecl>(D) ||
  1314. isa<UnresolvedUsingValueDecl>(D);
  1315. }
  1316. /// Removes using shadow declarations from the lookup results.
  1317. static void RemoveUsingDecls(LookupResult &R) {
  1318. LookupResult::Filter F = R.makeFilter();
  1319. while (F.hasNext())
  1320. if (isUsingDecl(F.next()))
  1321. F.erase();
  1322. F.done();
  1323. }
  1324. /// Check for this common pattern:
  1325. /// @code
  1326. /// class S {
  1327. /// S(const S&); // DO NOT IMPLEMENT
  1328. /// void operator=(const S&); // DO NOT IMPLEMENT
  1329. /// };
  1330. /// @endcode
  1331. static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
  1332. // FIXME: Should check for private access too but access is set after we get
  1333. // the decl here.
  1334. if (D->doesThisDeclarationHaveABody())
  1335. return false;
  1336. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
  1337. return CD->isCopyConstructor();
  1338. return D->isCopyAssignmentOperator();
  1339. }
  1340. // We need this to handle
  1341. //
  1342. // typedef struct {
  1343. // void *foo() { return 0; }
  1344. // } A;
  1345. //
  1346. // When we see foo we don't know if after the typedef we will get 'A' or '*A'
  1347. // for example. If 'A', foo will have external linkage. If we have '*A',
  1348. // foo will have no linkage. Since we can't know until we get to the end
  1349. // of the typedef, this function finds out if D might have non-external linkage.
  1350. // Callers should verify at the end of the TU if it D has external linkage or
  1351. // not.
  1352. bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
  1353. const DeclContext *DC = D->getDeclContext();
  1354. while (!DC->isTranslationUnit()) {
  1355. if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
  1356. if (!RD->hasNameForLinkage())
  1357. return true;
  1358. }
  1359. DC = DC->getParent();
  1360. }
  1361. return !D->isExternallyVisible();
  1362. }
  1363. // FIXME: This needs to be refactored; some other isInMainFile users want
  1364. // these semantics.
  1365. static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
  1366. if (S.TUKind != TU_Complete)
  1367. return false;
  1368. return S.SourceMgr.isInMainFile(Loc);
  1369. }
  1370. bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
  1371. assert(D);
  1372. if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
  1373. return false;
  1374. // Ignore all entities declared within templates, and out-of-line definitions
  1375. // of members of class templates.
  1376. if (D->getDeclContext()->isDependentContext() ||
  1377. D->getLexicalDeclContext()->isDependentContext())
  1378. return false;
  1379. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1380. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1381. return false;
  1382. // A non-out-of-line declaration of a member specialization was implicitly
  1383. // instantiated; it's the out-of-line declaration that we're interested in.
  1384. if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1385. FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
  1386. return false;
  1387. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  1388. if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
  1389. return false;
  1390. } else {
  1391. // 'static inline' functions are defined in headers; don't warn.
  1392. if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
  1393. return false;
  1394. }
  1395. if (FD->doesThisDeclarationHaveABody() &&
  1396. Context.DeclMustBeEmitted(FD))
  1397. return false;
  1398. } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1399. // Constants and utility variables are defined in headers with internal
  1400. // linkage; don't warn. (Unlike functions, there isn't a convenient marker
  1401. // like "inline".)
  1402. if (!isMainFileLoc(*this, VD->getLocation()))
  1403. return false;
  1404. if (Context.DeclMustBeEmitted(VD))
  1405. return false;
  1406. if (VD->isStaticDataMember() &&
  1407. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  1408. return false;
  1409. if (VD->isStaticDataMember() &&
  1410. VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
  1411. VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
  1412. return false;
  1413. if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
  1414. return false;
  1415. } else {
  1416. return false;
  1417. }
  1418. // Only warn for unused decls internal to the translation unit.
  1419. // FIXME: This seems like a bogus check; it suppresses -Wunused-function
  1420. // for inline functions defined in the main source file, for instance.
  1421. return mightHaveNonExternalLinkage(D);
  1422. }
  1423. void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
  1424. if (!D)
  1425. return;
  1426. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1427. const FunctionDecl *First = FD->getFirstDecl();
  1428. if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1429. return; // First should already be in the vector.
  1430. }
  1431. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1432. const VarDecl *First = VD->getFirstDecl();
  1433. if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
  1434. return; // First should already be in the vector.
  1435. }
  1436. if (ShouldWarnIfUnusedFileScopedDecl(D))
  1437. UnusedFileScopedDecls.push_back(D);
  1438. }
  1439. static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
  1440. if (D->isInvalidDecl())
  1441. return false;
  1442. bool Referenced = false;
  1443. if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
  1444. // For a decomposition declaration, warn if none of the bindings are
  1445. // referenced, instead of if the variable itself is referenced (which
  1446. // it is, by the bindings' expressions).
  1447. for (auto *BD : DD->bindings()) {
  1448. if (BD->isReferenced()) {
  1449. Referenced = true;
  1450. break;
  1451. }
  1452. }
  1453. } else if (!D->getDeclName()) {
  1454. return false;
  1455. } else if (D->isReferenced() || D->isUsed()) {
  1456. Referenced = true;
  1457. }
  1458. if (Referenced || D->hasAttr<UnusedAttr>() ||
  1459. D->hasAttr<ObjCPreciseLifetimeAttr>())
  1460. return false;
  1461. if (isa<LabelDecl>(D))
  1462. return true;
  1463. // Except for labels, we only care about unused decls that are local to
  1464. // functions.
  1465. bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
  1466. if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
  1467. // For dependent types, the diagnostic is deferred.
  1468. WithinFunction =
  1469. WithinFunction || (R->isLocalClass() && !R->isDependentType());
  1470. if (!WithinFunction)
  1471. return false;
  1472. if (isa<TypedefNameDecl>(D))
  1473. return true;
  1474. // White-list anything that isn't a local variable.
  1475. if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
  1476. return false;
  1477. // Types of valid local variables should be complete, so this should succeed.
  1478. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1479. // White-list anything with an __attribute__((unused)) type.
  1480. const auto *Ty = VD->getType().getTypePtr();
  1481. // Only look at the outermost level of typedef.
  1482. if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
  1483. if (TT->getDecl()->hasAttr<UnusedAttr>())
  1484. return false;
  1485. }
  1486. // If we failed to complete the type for some reason, or if the type is
  1487. // dependent, don't diagnose the variable.
  1488. if (Ty->isIncompleteType() || Ty->isDependentType())
  1489. return false;
  1490. // Look at the element type to ensure that the warning behaviour is
  1491. // consistent for both scalars and arrays.
  1492. Ty = Ty->getBaseElementTypeUnsafe();
  1493. if (const TagType *TT = Ty->getAs<TagType>()) {
  1494. const TagDecl *Tag = TT->getDecl();
  1495. if (Tag->hasAttr<UnusedAttr>())
  1496. return false;
  1497. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
  1498. if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
  1499. return false;
  1500. if (const Expr *Init = VD->getInit()) {
  1501. if (const ExprWithCleanups *Cleanups =
  1502. dyn_cast<ExprWithCleanups>(Init))
  1503. Init = Cleanups->getSubExpr();
  1504. const CXXConstructExpr *Construct =
  1505. dyn_cast<CXXConstructExpr>(Init);
  1506. if (Construct && !Construct->isElidable()) {
  1507. CXXConstructorDecl *CD = Construct->getConstructor();
  1508. if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
  1509. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  1510. return false;
  1511. }
  1512. }
  1513. }
  1514. }
  1515. // TODO: __attribute__((unused)) templates?
  1516. }
  1517. return true;
  1518. }
  1519. static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
  1520. FixItHint &Hint) {
  1521. if (isa<LabelDecl>(D)) {
  1522. SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
  1523. tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
  1524. if (AfterColon.isInvalid())
  1525. return;
  1526. Hint = FixItHint::CreateRemoval(CharSourceRange::
  1527. getCharRange(D->getLocStart(), 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(ASTContext::GetBuiltinTypeError Error) {
  1692. switch (Error) {
  1693. case ASTContext::GE_None:
  1694. return "";
  1695. case ASTContext::GE_Missing_stdio:
  1696. return "stdio.h";
  1697. case ASTContext::GE_Missing_setjmp:
  1698. return "setjmp.h";
  1699. case ASTContext::GE_Missing_ucontext:
  1700. return "ucontext.h";
  1701. }
  1702. llvm_unreachable("unhandled error kind");
  1703. }
  1704. /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
  1705. /// file scope. lazily create a decl for it. ForRedeclaration is true
  1706. /// if we're creating this built-in in anticipation of redeclaring the
  1707. /// built-in.
  1708. NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
  1709. Scope *S, bool ForRedeclaration,
  1710. SourceLocation Loc) {
  1711. LookupPredefedObjCSuperType(*this, S, II);
  1712. ASTContext::GetBuiltinTypeError Error;
  1713. QualType R = Context.GetBuiltinType(ID, Error);
  1714. if (Error) {
  1715. if (ForRedeclaration)
  1716. Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
  1717. << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
  1718. return nullptr;
  1719. }
  1720. if (!ForRedeclaration &&
  1721. (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
  1722. Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
  1723. Diag(Loc, diag::ext_implicit_lib_function_decl)
  1724. << Context.BuiltinInfo.getName(ID) << R;
  1725. if (Context.BuiltinInfo.getHeaderName(ID) &&
  1726. !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
  1727. Diag(Loc, diag::note_include_header_or_declare)
  1728. << Context.BuiltinInfo.getHeaderName(ID)
  1729. << Context.BuiltinInfo.getName(ID);
  1730. }
  1731. if (R.isNull())
  1732. return nullptr;
  1733. DeclContext *Parent = Context.getTranslationUnitDecl();
  1734. if (getLangOpts().CPlusPlus) {
  1735. LinkageSpecDecl *CLinkageDecl =
  1736. LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
  1737. LinkageSpecDecl::lang_c, false);
  1738. CLinkageDecl->setImplicit();
  1739. Parent->addDecl(CLinkageDecl);
  1740. Parent = CLinkageDecl;
  1741. }
  1742. FunctionDecl *New = FunctionDecl::Create(Context,
  1743. Parent,
  1744. Loc, Loc, II, R, /*TInfo=*/nullptr,
  1745. SC_Extern,
  1746. false,
  1747. R->isFunctionProtoType());
  1748. New->setImplicit();
  1749. // Create Decl objects for each parameter, adding them to the
  1750. // FunctionDecl.
  1751. if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
  1752. SmallVector<ParmVarDecl*, 16> Params;
  1753. for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
  1754. ParmVarDecl *parm =
  1755. ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
  1756. nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
  1757. SC_None, nullptr);
  1758. parm->setScopeInfo(0, i);
  1759. Params.push_back(parm);
  1760. }
  1761. New->setParams(Params);
  1762. }
  1763. AddKnownFunctionAttributes(New);
  1764. RegisterLocallyScopedExternCDecl(New, S);
  1765. // TUScope is the translation-unit scope to insert this function into.
  1766. // FIXME: This is hideous. We need to teach PushOnScopeChains to
  1767. // relate Scopes to DeclContexts, and probably eliminate CurContext
  1768. // entirely, but we're not there yet.
  1769. DeclContext *SavedContext = CurContext;
  1770. CurContext = Parent;
  1771. PushOnScopeChains(New, TUScope);
  1772. CurContext = SavedContext;
  1773. return New;
  1774. }
  1775. /// Typedef declarations don't have linkage, but they still denote the same
  1776. /// entity if their types are the same.
  1777. /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
  1778. /// isSameEntity.
  1779. static void filterNonConflictingPreviousTypedefDecls(Sema &S,
  1780. TypedefNameDecl *Decl,
  1781. LookupResult &Previous) {
  1782. // This is only interesting when modules are enabled.
  1783. if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
  1784. return;
  1785. // Empty sets are uninteresting.
  1786. if (Previous.empty())
  1787. return;
  1788. LookupResult::Filter Filter = Previous.makeFilter();
  1789. while (Filter.hasNext()) {
  1790. NamedDecl *Old = Filter.next();
  1791. // Non-hidden declarations are never ignored.
  1792. if (S.isVisible(Old))
  1793. continue;
  1794. // Declarations of the same entity are not ignored, even if they have
  1795. // different linkages.
  1796. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1797. if (S.Context.hasSameType(OldTD->getUnderlyingType(),
  1798. Decl->getUnderlyingType()))
  1799. continue;
  1800. // If both declarations give a tag declaration a typedef name for linkage
  1801. // purposes, then they declare the same entity.
  1802. if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
  1803. Decl->getAnonDeclWithTypedefName())
  1804. continue;
  1805. }
  1806. Filter.erase();
  1807. }
  1808. Filter.done();
  1809. }
  1810. bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
  1811. QualType OldType;
  1812. if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
  1813. OldType = OldTypedef->getUnderlyingType();
  1814. else
  1815. OldType = Context.getTypeDeclType(Old);
  1816. QualType NewType = New->getUnderlyingType();
  1817. if (NewType->isVariablyModifiedType()) {
  1818. // Must not redefine a typedef with a variably-modified type.
  1819. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1820. Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
  1821. << Kind << NewType;
  1822. if (Old->getLocation().isValid())
  1823. notePreviousDefinition(Old, New->getLocation());
  1824. New->setInvalidDecl();
  1825. return true;
  1826. }
  1827. if (OldType != NewType &&
  1828. !OldType->isDependentType() &&
  1829. !NewType->isDependentType() &&
  1830. !Context.hasSameType(OldType, NewType)) {
  1831. int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
  1832. Diag(New->getLocation(), diag::err_redefinition_different_typedef)
  1833. << Kind << NewType << OldType;
  1834. if (Old->getLocation().isValid())
  1835. notePreviousDefinition(Old, New->getLocation());
  1836. New->setInvalidDecl();
  1837. return true;
  1838. }
  1839. return false;
  1840. }
  1841. /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
  1842. /// same name and scope as a previous declaration 'Old'. Figure out
  1843. /// how to resolve this situation, merging decls or emitting
  1844. /// diagnostics as appropriate. If there was an error, set New to be invalid.
  1845. ///
  1846. void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
  1847. LookupResult &OldDecls) {
  1848. // If the new decl is known invalid already, don't bother doing any
  1849. // merging checks.
  1850. if (New->isInvalidDecl()) return;
  1851. // Allow multiple definitions for ObjC built-in typedefs.
  1852. // FIXME: Verify the underlying types are equivalent!
  1853. if (getLangOpts().ObjC1) {
  1854. const IdentifierInfo *TypeID = New->getIdentifier();
  1855. switch (TypeID->getLength()) {
  1856. default: break;
  1857. case 2:
  1858. {
  1859. if (!TypeID->isStr("id"))
  1860. break;
  1861. QualType T = New->getUnderlyingType();
  1862. if (!T->isPointerType())
  1863. break;
  1864. if (!T->isVoidPointerType()) {
  1865. QualType PT = T->getAs<PointerType>()->getPointeeType();
  1866. if (!PT->isStructureType())
  1867. break;
  1868. }
  1869. Context.setObjCIdRedefinitionType(T);
  1870. // Install the built-in type for 'id', ignoring the current definition.
  1871. New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
  1872. return;
  1873. }
  1874. case 5:
  1875. if (!TypeID->isStr("Class"))
  1876. break;
  1877. Context.setObjCClassRedefinitionType(New->getUnderlyingType());
  1878. // Install the built-in type for 'Class', ignoring the current definition.
  1879. New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
  1880. return;
  1881. case 3:
  1882. if (!TypeID->isStr("SEL"))
  1883. break;
  1884. Context.setObjCSelRedefinitionType(New->getUnderlyingType());
  1885. // Install the built-in type for 'SEL', ignoring the current definition.
  1886. New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
  1887. return;
  1888. }
  1889. // Fall through - the typedef name was not a builtin type.
  1890. }
  1891. // Verify the old decl was also a type.
  1892. TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
  1893. if (!Old) {
  1894. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  1895. << New->getDeclName();
  1896. NamedDecl *OldD = OldDecls.getRepresentativeDecl();
  1897. if (OldD->getLocation().isValid())
  1898. notePreviousDefinition(OldD, New->getLocation());
  1899. return New->setInvalidDecl();
  1900. }
  1901. // If the old declaration is invalid, just give up here.
  1902. if (Old->isInvalidDecl())
  1903. return New->setInvalidDecl();
  1904. if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
  1905. auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  1906. auto *NewTag = New->getAnonDeclWithTypedefName();
  1907. NamedDecl *Hidden = nullptr;
  1908. if (OldTag && NewTag &&
  1909. OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
  1910. !hasVisibleDefinition(OldTag, &Hidden)) {
  1911. // There is a definition of this tag, but it is not visible. Use it
  1912. // instead of our tag.
  1913. New->setTypeForDecl(OldTD->getTypeForDecl());
  1914. if (OldTD->isModed())
  1915. New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
  1916. OldTD->getUnderlyingType());
  1917. else
  1918. New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
  1919. // Make the old tag definition visible.
  1920. makeMergedDefinitionVisible(Hidden);
  1921. // If this was an unscoped enumeration, yank all of its enumerators
  1922. // out of the scope.
  1923. if (isa<EnumDecl>(NewTag)) {
  1924. Scope *EnumScope = getNonFieldDeclScope(S);
  1925. for (auto *D : NewTag->decls()) {
  1926. auto *ED = cast<EnumConstantDecl>(D);
  1927. assert(EnumScope->isDeclScope(ED));
  1928. EnumScope->RemoveDecl(ED);
  1929. IdResolver.RemoveDecl(ED);
  1930. ED->getLexicalDeclContext()->removeDecl(ED);
  1931. }
  1932. }
  1933. }
  1934. }
  1935. // If the typedef types are not identical, reject them in all languages and
  1936. // with any extensions enabled.
  1937. if (isIncompatibleTypedef(Old, New))
  1938. return;
  1939. // The types match. Link up the redeclaration chain and merge attributes if
  1940. // the old declaration was a typedef.
  1941. if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
  1942. New->setPreviousDecl(Typedef);
  1943. mergeDeclAttributes(New, Old);
  1944. }
  1945. if (getLangOpts().MicrosoftExt)
  1946. return;
  1947. if (getLangOpts().CPlusPlus) {
  1948. // C++ [dcl.typedef]p2:
  1949. // In a given non-class scope, a typedef specifier can be used to
  1950. // redefine the name of any type declared in that scope to refer
  1951. // to the type to which it already refers.
  1952. if (!isa<CXXRecordDecl>(CurContext))
  1953. return;
  1954. // C++0x [dcl.typedef]p4:
  1955. // In a given class scope, a typedef specifier can be used to redefine
  1956. // any class-name declared in that scope that is not also a typedef-name
  1957. // to refer to the type to which it already refers.
  1958. //
  1959. // This wording came in via DR424, which was a correction to the
  1960. // wording in DR56, which accidentally banned code like:
  1961. //
  1962. // struct S {
  1963. // typedef struct A { } A;
  1964. // };
  1965. //
  1966. // in the C++03 standard. We implement the C++0x semantics, which
  1967. // allow the above but disallow
  1968. //
  1969. // struct S {
  1970. // typedef int I;
  1971. // typedef int I;
  1972. // };
  1973. //
  1974. // since that was the intent of DR56.
  1975. if (!isa<TypedefNameDecl>(Old))
  1976. return;
  1977. Diag(New->getLocation(), diag::err_redefinition)
  1978. << New->getDeclName();
  1979. notePreviousDefinition(Old, New->getLocation());
  1980. return New->setInvalidDecl();
  1981. }
  1982. // Modules always permit redefinition of typedefs, as does C11.
  1983. if (getLangOpts().Modules || getLangOpts().C11)
  1984. return;
  1985. // If we have a redefinition of a typedef in C, emit a warning. This warning
  1986. // is normally mapped to an error, but can be controlled with
  1987. // -Wtypedef-redefinition. If either the original or the redefinition is
  1988. // in a system header, don't emit this for compatibility with GCC.
  1989. if (getDiagnostics().getSuppressSystemWarnings() &&
  1990. // Some standard types are defined implicitly in Clang (e.g. OpenCL).
  1991. (Old->isImplicit() ||
  1992. Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
  1993. Context.getSourceManager().isInSystemHeader(New->getLocation())))
  1994. return;
  1995. Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
  1996. << New->getDeclName();
  1997. notePreviousDefinition(Old, New->getLocation());
  1998. }
  1999. /// DeclhasAttr - returns true if decl Declaration already has the target
  2000. /// attribute.
  2001. static bool DeclHasAttr(const Decl *D, const Attr *A) {
  2002. const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
  2003. const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
  2004. for (const auto *i : D->attrs())
  2005. if (i->getKind() == A->getKind()) {
  2006. if (Ann) {
  2007. if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
  2008. return true;
  2009. continue;
  2010. }
  2011. // FIXME: Don't hardcode this check
  2012. if (OA && isa<OwnershipAttr>(i))
  2013. return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
  2014. return true;
  2015. }
  2016. return false;
  2017. }
  2018. static bool isAttributeTargetADefinition(Decl *D) {
  2019. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  2020. return VD->isThisDeclarationADefinition();
  2021. if (TagDecl *TD = dyn_cast<TagDecl>(D))
  2022. return TD->isCompleteDefinition() || TD->isBeingDefined();
  2023. return true;
  2024. }
  2025. /// Merge alignment attributes from \p Old to \p New, taking into account the
  2026. /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
  2027. ///
  2028. /// \return \c true if any attributes were added to \p New.
  2029. static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
  2030. // Look for alignas attributes on Old, and pick out whichever attribute
  2031. // specifies the strictest alignment requirement.
  2032. AlignedAttr *OldAlignasAttr = nullptr;
  2033. AlignedAttr *OldStrictestAlignAttr = nullptr;
  2034. unsigned OldAlign = 0;
  2035. for (auto *I : Old->specific_attrs<AlignedAttr>()) {
  2036. // FIXME: We have no way of representing inherited dependent alignments
  2037. // in a case like:
  2038. // template<int A, int B> struct alignas(A) X;
  2039. // template<int A, int B> struct alignas(B) X {};
  2040. // For now, we just ignore any alignas attributes which are not on the
  2041. // definition in such a case.
  2042. if (I->isAlignmentDependent())
  2043. return false;
  2044. if (I->isAlignas())
  2045. OldAlignasAttr = I;
  2046. unsigned Align = I->getAlignment(S.Context);
  2047. if (Align > OldAlign) {
  2048. OldAlign = Align;
  2049. OldStrictestAlignAttr = I;
  2050. }
  2051. }
  2052. // Look for alignas attributes on New.
  2053. AlignedAttr *NewAlignasAttr = nullptr;
  2054. unsigned NewAlign = 0;
  2055. for (auto *I : New->specific_attrs<AlignedAttr>()) {
  2056. if (I->isAlignmentDependent())
  2057. return false;
  2058. if (I->isAlignas())
  2059. NewAlignasAttr = I;
  2060. unsigned Align = I->getAlignment(S.Context);
  2061. if (Align > NewAlign)
  2062. NewAlign = Align;
  2063. }
  2064. if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
  2065. // Both declarations have 'alignas' attributes. We require them to match.
  2066. // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
  2067. // fall short. (If two declarations both have alignas, they must both match
  2068. // every definition, and so must match each other if there is a definition.)
  2069. // If either declaration only contains 'alignas(0)' specifiers, then it
  2070. // specifies the natural alignment for the type.
  2071. if (OldAlign == 0 || NewAlign == 0) {
  2072. QualType Ty;
  2073. if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
  2074. Ty = VD->getType();
  2075. else
  2076. Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
  2077. if (OldAlign == 0)
  2078. OldAlign = S.Context.getTypeAlign(Ty);
  2079. if (NewAlign == 0)
  2080. NewAlign = S.Context.getTypeAlign(Ty);
  2081. }
  2082. if (OldAlign != NewAlign) {
  2083. S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
  2084. << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
  2085. << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
  2086. S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
  2087. }
  2088. }
  2089. if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
  2090. // C++11 [dcl.align]p6:
  2091. // if any declaration of an entity has an alignment-specifier,
  2092. // every defining declaration of that entity shall specify an
  2093. // equivalent alignment.
  2094. // C11 6.7.5/7:
  2095. // If the definition of an object does not have an alignment
  2096. // specifier, any other declaration of that object shall also
  2097. // have no alignment specifier.
  2098. S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
  2099. << OldAlignasAttr;
  2100. S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
  2101. << OldAlignasAttr;
  2102. }
  2103. bool AnyAdded = false;
  2104. // Ensure we have an attribute representing the strictest alignment.
  2105. if (OldAlign > NewAlign) {
  2106. AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
  2107. Clone->setInherited(true);
  2108. New->addAttr(Clone);
  2109. AnyAdded = true;
  2110. }
  2111. // Ensure we have an alignas attribute if the old declaration had one.
  2112. if (OldAlignasAttr && !NewAlignasAttr &&
  2113. !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
  2114. AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
  2115. Clone->setInherited(true);
  2116. New->addAttr(Clone);
  2117. AnyAdded = true;
  2118. }
  2119. return AnyAdded;
  2120. }
  2121. static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
  2122. const InheritableAttr *Attr,
  2123. Sema::AvailabilityMergeKind AMK) {
  2124. // This function copies an attribute Attr from a previous declaration to the
  2125. // new declaration D if the new declaration doesn't itself have that attribute
  2126. // yet or if that attribute allows duplicates.
  2127. // If you're adding a new attribute that requires logic different from
  2128. // "use explicit attribute on decl if present, else use attribute from
  2129. // previous decl", for example if the attribute needs to be consistent
  2130. // between redeclarations, you need to call a custom merge function here.
  2131. InheritableAttr *NewAttr = nullptr;
  2132. unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
  2133. if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
  2134. NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
  2135. AA->isImplicit(), AA->getIntroduced(),
  2136. AA->getDeprecated(),
  2137. AA->getObsoleted(), AA->getUnavailable(),
  2138. AA->getMessage(), AA->getStrict(),
  2139. AA->getReplacement(), AMK,
  2140. AttrSpellingListIndex);
  2141. else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
  2142. NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2143. AttrSpellingListIndex);
  2144. else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
  2145. NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
  2146. AttrSpellingListIndex);
  2147. else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
  2148. NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
  2149. AttrSpellingListIndex);
  2150. else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
  2151. NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
  2152. AttrSpellingListIndex);
  2153. else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
  2154. NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
  2155. FA->getFormatIdx(), FA->getFirstArg(),
  2156. AttrSpellingListIndex);
  2157. else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
  2158. NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
  2159. AttrSpellingListIndex);
  2160. else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
  2161. NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
  2162. AttrSpellingListIndex,
  2163. IA->getSemanticSpelling());
  2164. else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
  2165. NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
  2166. &S.Context.Idents.get(AA->getSpelling()),
  2167. AttrSpellingListIndex);
  2168. else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
  2169. (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
  2170. isa<CUDAGlobalAttr>(Attr))) {
  2171. // CUDA target attributes are part of function signature for
  2172. // overloading purposes and must not be merged.
  2173. return false;
  2174. } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
  2175. NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
  2176. else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
  2177. NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
  2178. else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
  2179. NewAttr = S.mergeInternalLinkageAttr(
  2180. D, InternalLinkageA->getRange(),
  2181. &S.Context.Idents.get(InternalLinkageA->getSpelling()),
  2182. AttrSpellingListIndex);
  2183. else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
  2184. NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
  2185. &S.Context.Idents.get(CommonA->getSpelling()),
  2186. AttrSpellingListIndex);
  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 (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
  2199. NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
  2200. if (NewAttr) {
  2201. NewAttr->setInherited(true);
  2202. D->addAttr(NewAttr);
  2203. if (isa<MSInheritanceAttr>(NewAttr))
  2204. S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
  2205. return true;
  2206. }
  2207. return false;
  2208. }
  2209. static const NamedDecl *getDefinition(const Decl *D) {
  2210. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  2211. return TD->getDefinition();
  2212. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  2213. const VarDecl *Def = VD->getDefinition();
  2214. if (Def)
  2215. return Def;
  2216. return VD->getActingDefinition();
  2217. }
  2218. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  2219. return FD->getDefinition();
  2220. return nullptr;
  2221. }
  2222. static bool hasAttribute(const Decl *D, attr::Kind Kind) {
  2223. for (const auto *Attribute : D->attrs())
  2224. if (Attribute->getKind() == Kind)
  2225. return true;
  2226. return false;
  2227. }
  2228. /// checkNewAttributesAfterDef - If we already have a definition, check that
  2229. /// there are no new attributes in this declaration.
  2230. static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
  2231. if (!New->hasAttrs())
  2232. return;
  2233. const NamedDecl *Def = getDefinition(Old);
  2234. if (!Def || Def == New)
  2235. return;
  2236. AttrVec &NewAttributes = New->getAttrs();
  2237. for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
  2238. const Attr *NewAttribute = NewAttributes[I];
  2239. if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
  2240. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
  2241. Sema::SkipBodyInfo SkipBody;
  2242. S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
  2243. // If we're skipping this definition, drop the "alias" attribute.
  2244. if (SkipBody.ShouldSkip) {
  2245. NewAttributes.erase(NewAttributes.begin() + I);
  2246. --E;
  2247. continue;
  2248. }
  2249. } else {
  2250. VarDecl *VD = cast<VarDecl>(New);
  2251. unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
  2252. VarDecl::TentativeDefinition
  2253. ? diag::err_alias_after_tentative
  2254. : diag::err_redefinition;
  2255. S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
  2256. if (Diag == diag::err_redefinition)
  2257. S.notePreviousDefinition(Def, VD->getLocation());
  2258. else
  2259. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2260. VD->setInvalidDecl();
  2261. }
  2262. ++I;
  2263. continue;
  2264. }
  2265. if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
  2266. // Tentative definitions are only interesting for the alias check above.
  2267. if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
  2268. ++I;
  2269. continue;
  2270. }
  2271. }
  2272. if (hasAttribute(Def, NewAttribute->getKind())) {
  2273. ++I;
  2274. continue; // regular attr merging will take care of validating this.
  2275. }
  2276. if (isa<C11NoReturnAttr>(NewAttribute)) {
  2277. // C's _Noreturn is allowed to be added to a function after it is defined.
  2278. ++I;
  2279. continue;
  2280. } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
  2281. if (AA->isAlignas()) {
  2282. // C++11 [dcl.align]p6:
  2283. // if any declaration of an entity has an alignment-specifier,
  2284. // every defining declaration of that entity shall specify an
  2285. // equivalent alignment.
  2286. // C11 6.7.5/7:
  2287. // If the definition of an object does not have an alignment
  2288. // specifier, any other declaration of that object shall also
  2289. // have no alignment specifier.
  2290. S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
  2291. << AA;
  2292. S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
  2293. << AA;
  2294. NewAttributes.erase(NewAttributes.begin() + I);
  2295. --E;
  2296. continue;
  2297. }
  2298. }
  2299. S.Diag(NewAttribute->getLocation(),
  2300. diag::warn_attribute_precede_definition);
  2301. S.Diag(Def->getLocation(), diag::note_previous_definition);
  2302. NewAttributes.erase(NewAttributes.begin() + I);
  2303. --E;
  2304. }
  2305. }
  2306. /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
  2307. void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
  2308. AvailabilityMergeKind AMK) {
  2309. if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
  2310. UsedAttr *NewAttr = OldAttr->clone(Context);
  2311. NewAttr->setInherited(true);
  2312. New->addAttr(NewAttr);
  2313. }
  2314. if (!Old->hasAttrs() && !New->hasAttrs())
  2315. return;
  2316. // Attributes declared post-definition are currently ignored.
  2317. checkNewAttributesAfterDef(*this, New, Old);
  2318. if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
  2319. if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
  2320. if (OldA->getLabel() != NewA->getLabel()) {
  2321. // This redeclaration changes __asm__ label.
  2322. Diag(New->getLocation(), diag::err_different_asm_label);
  2323. Diag(OldA->getLocation(), diag::note_previous_declaration);
  2324. }
  2325. } else if (Old->isUsed()) {
  2326. // This redeclaration adds an __asm__ label to a declaration that has
  2327. // already been ODR-used.
  2328. Diag(New->getLocation(), diag::err_late_asm_label_name)
  2329. << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
  2330. }
  2331. }
  2332. // Re-declaration cannot add abi_tag's.
  2333. if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
  2334. if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
  2335. for (const auto &NewTag : NewAbiTagAttr->tags()) {
  2336. if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
  2337. NewTag) == OldAbiTagAttr->tags_end()) {
  2338. Diag(NewAbiTagAttr->getLocation(),
  2339. diag::err_new_abi_tag_on_redeclaration)
  2340. << NewTag;
  2341. Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
  2342. }
  2343. }
  2344. } else {
  2345. Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
  2346. Diag(Old->getLocation(), diag::note_previous_declaration);
  2347. }
  2348. }
  2349. // This redeclaration adds a section attribute.
  2350. if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
  2351. if (auto *VD = dyn_cast<VarDecl>(New)) {
  2352. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
  2353. Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
  2354. Diag(Old->getLocation(), diag::note_previous_declaration);
  2355. }
  2356. }
  2357. }
  2358. if (!Old->hasAttrs())
  2359. return;
  2360. bool foundAny = New->hasAttrs();
  2361. // Ensure that any moving of objects within the allocated map is done before
  2362. // we process them.
  2363. if (!foundAny) New->setAttrs(AttrVec());
  2364. for (auto *I : Old->specific_attrs<InheritableAttr>()) {
  2365. // Ignore deprecated/unavailable/availability attributes if requested.
  2366. AvailabilityMergeKind LocalAMK = AMK_None;
  2367. if (isa<DeprecatedAttr>(I) ||
  2368. isa<UnavailableAttr>(I) ||
  2369. isa<AvailabilityAttr>(I)) {
  2370. switch (AMK) {
  2371. case AMK_None:
  2372. continue;
  2373. case AMK_Redeclaration:
  2374. case AMK_Override:
  2375. case AMK_ProtocolImplementation:
  2376. LocalAMK = AMK;
  2377. break;
  2378. }
  2379. }
  2380. // Already handled.
  2381. if (isa<UsedAttr>(I))
  2382. continue;
  2383. if (mergeDeclAttribute(*this, New, I, LocalAMK))
  2384. foundAny = true;
  2385. }
  2386. if (mergeAlignedAttrs(*this, New, Old))
  2387. foundAny = true;
  2388. if (!foundAny) New->dropAttrs();
  2389. }
  2390. /// mergeParamDeclAttributes - Copy attributes from the old parameter
  2391. /// to the new one.
  2392. static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
  2393. const ParmVarDecl *oldDecl,
  2394. Sema &S) {
  2395. // C++11 [dcl.attr.depend]p2:
  2396. // The first declaration of a function shall specify the
  2397. // carries_dependency attribute for its declarator-id if any declaration
  2398. // of the function specifies the carries_dependency attribute.
  2399. const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
  2400. if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
  2401. S.Diag(CDA->getLocation(),
  2402. diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
  2403. // Find the first declaration of the parameter.
  2404. // FIXME: Should we build redeclaration chains for function parameters?
  2405. const FunctionDecl *FirstFD =
  2406. cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
  2407. const ParmVarDecl *FirstVD =
  2408. FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
  2409. S.Diag(FirstVD->getLocation(),
  2410. diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
  2411. }
  2412. if (!oldDecl->hasAttrs())
  2413. return;
  2414. bool foundAny = newDecl->hasAttrs();
  2415. // Ensure that any moving of objects within the allocated map is
  2416. // done before we process them.
  2417. if (!foundAny) newDecl->setAttrs(AttrVec());
  2418. for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
  2419. if (!DeclHasAttr(newDecl, I)) {
  2420. InheritableAttr *newAttr =
  2421. cast<InheritableParamAttr>(I->clone(S.Context));
  2422. newAttr->setInherited(true);
  2423. newDecl->addAttr(newAttr);
  2424. foundAny = true;
  2425. }
  2426. }
  2427. if (!foundAny) newDecl->dropAttrs();
  2428. }
  2429. static void mergeParamDeclTypes(ParmVarDecl *NewParam,
  2430. const ParmVarDecl *OldParam,
  2431. Sema &S) {
  2432. if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
  2433. if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
  2434. if (*Oldnullability != *Newnullability) {
  2435. S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
  2436. << DiagNullabilityKind(
  2437. *Newnullability,
  2438. ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2439. != 0))
  2440. << DiagNullabilityKind(
  2441. *Oldnullability,
  2442. ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  2443. != 0));
  2444. S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
  2445. }
  2446. } else {
  2447. QualType NewT = NewParam->getType();
  2448. NewT = S.Context.getAttributedType(
  2449. AttributedType::getNullabilityAttrKind(*Oldnullability),
  2450. NewT, NewT);
  2451. NewParam->setType(NewT);
  2452. }
  2453. }
  2454. }
  2455. namespace {
  2456. /// Used in MergeFunctionDecl to keep track of function parameters in
  2457. /// C.
  2458. struct GNUCompatibleParamWarning {
  2459. ParmVarDecl *OldParm;
  2460. ParmVarDecl *NewParm;
  2461. QualType PromotedType;
  2462. };
  2463. } // end anonymous namespace
  2464. /// getSpecialMember - get the special member enum for a method.
  2465. Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
  2466. if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
  2467. if (Ctor->isDefaultConstructor())
  2468. return Sema::CXXDefaultConstructor;
  2469. if (Ctor->isCopyConstructor())
  2470. return Sema::CXXCopyConstructor;
  2471. if (Ctor->isMoveConstructor())
  2472. return Sema::CXXMoveConstructor;
  2473. } else if (isa<CXXDestructorDecl>(MD)) {
  2474. return Sema::CXXDestructor;
  2475. } else if (MD->isCopyAssignmentOperator()) {
  2476. return Sema::CXXCopyAssignment;
  2477. } else if (MD->isMoveAssignmentOperator()) {
  2478. return Sema::CXXMoveAssignment;
  2479. }
  2480. return Sema::CXXInvalid;
  2481. }
  2482. // Determine whether the previous declaration was a definition, implicit
  2483. // declaration, or a declaration.
  2484. template <typename T>
  2485. static std::pair<diag::kind, SourceLocation>
  2486. getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
  2487. diag::kind PrevDiag;
  2488. SourceLocation OldLocation = Old->getLocation();
  2489. if (Old->isThisDeclarationADefinition())
  2490. PrevDiag = diag::note_previous_definition;
  2491. else if (Old->isImplicit()) {
  2492. PrevDiag = diag::note_previous_implicit_declaration;
  2493. if (OldLocation.isInvalid())
  2494. OldLocation = New->getLocation();
  2495. } else
  2496. PrevDiag = diag::note_previous_declaration;
  2497. return std::make_pair(PrevDiag, OldLocation);
  2498. }
  2499. /// canRedefineFunction - checks if a function can be redefined. Currently,
  2500. /// only extern inline functions can be redefined, and even then only in
  2501. /// GNU89 mode.
  2502. static bool canRedefineFunction(const FunctionDecl *FD,
  2503. const LangOptions& LangOpts) {
  2504. return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
  2505. !LangOpts.CPlusPlus &&
  2506. FD->isInlineSpecified() &&
  2507. FD->getStorageClass() == SC_Extern);
  2508. }
  2509. const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
  2510. const AttributedType *AT = T->getAs<AttributedType>();
  2511. while (AT && !AT->isCallingConv())
  2512. AT = AT->getModifiedType()->getAs<AttributedType>();
  2513. return AT;
  2514. }
  2515. template <typename T>
  2516. static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
  2517. const DeclContext *DC = Old->getDeclContext();
  2518. if (DC->isRecord())
  2519. return false;
  2520. LanguageLinkage OldLinkage = Old->getLanguageLinkage();
  2521. if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
  2522. return true;
  2523. if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
  2524. return true;
  2525. return false;
  2526. }
  2527. template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
  2528. static bool isExternC(VarTemplateDecl *) { return false; }
  2529. /// Check whether a redeclaration of an entity introduced by a
  2530. /// using-declaration is valid, given that we know it's not an overload
  2531. /// (nor a hidden tag declaration).
  2532. template<typename ExpectedDecl>
  2533. static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
  2534. ExpectedDecl *New) {
  2535. // C++11 [basic.scope.declarative]p4:
  2536. // Given a set of declarations in a single declarative region, each of
  2537. // which specifies the same unqualified name,
  2538. // -- they shall all refer to the same entity, or all refer to functions
  2539. // and function templates; or
  2540. // -- exactly one declaration shall declare a class name or enumeration
  2541. // name that is not a typedef name and the other declarations shall all
  2542. // refer to the same variable or enumerator, or all refer to functions
  2543. // and function templates; in this case the class name or enumeration
  2544. // name is hidden (3.3.10).
  2545. // C++11 [namespace.udecl]p14:
  2546. // If a function declaration in namespace scope or block scope has the
  2547. // same name and the same parameter-type-list as a function introduced
  2548. // by a using-declaration, and the declarations do not declare the same
  2549. // function, the program is ill-formed.
  2550. auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
  2551. if (Old &&
  2552. !Old->getDeclContext()->getRedeclContext()->Equals(
  2553. New->getDeclContext()->getRedeclContext()) &&
  2554. !(isExternC(Old) && isExternC(New)))
  2555. Old = nullptr;
  2556. if (!Old) {
  2557. S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
  2558. S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
  2559. S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
  2560. return true;
  2561. }
  2562. return false;
  2563. }
  2564. static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
  2565. const FunctionDecl *B) {
  2566. assert(A->getNumParams() == B->getNumParams());
  2567. auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
  2568. const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
  2569. const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
  2570. if (AttrA == AttrB)
  2571. return true;
  2572. return AttrA && AttrB && AttrA->getType() == AttrB->getType();
  2573. };
  2574. return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
  2575. }
  2576. /// If necessary, adjust the semantic declaration context for a qualified
  2577. /// declaration to name the correct inline namespace within the qualifier.
  2578. static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
  2579. DeclaratorDecl *OldD) {
  2580. // The only case where we need to update the DeclContext is when
  2581. // redeclaration lookup for a qualified name finds a declaration
  2582. // in an inline namespace within the context named by the qualifier:
  2583. //
  2584. // inline namespace N { int f(); }
  2585. // int ::f(); // Sema DC needs adjusting from :: to N::.
  2586. //
  2587. // For unqualified declarations, the semantic context *can* change
  2588. // along the redeclaration chain (for local extern declarations,
  2589. // extern "C" declarations, and friend declarations in particular).
  2590. if (!NewD->getQualifier())
  2591. return;
  2592. // NewD is probably already in the right context.
  2593. auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
  2594. auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
  2595. if (NamedDC->Equals(SemaDC))
  2596. return;
  2597. assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
  2598. NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
  2599. "unexpected context for redeclaration");
  2600. auto *LexDC = NewD->getLexicalDeclContext();
  2601. auto FixSemaDC = [=](NamedDecl *D) {
  2602. if (!D)
  2603. return;
  2604. D->setDeclContext(SemaDC);
  2605. D->setLexicalDeclContext(LexDC);
  2606. };
  2607. FixSemaDC(NewD);
  2608. if (auto *FD = dyn_cast<FunctionDecl>(NewD))
  2609. FixSemaDC(FD->getDescribedFunctionTemplate());
  2610. else if (auto *VD = dyn_cast<VarDecl>(NewD))
  2611. FixSemaDC(VD->getDescribedVarTemplate());
  2612. }
  2613. /// MergeFunctionDecl - We just parsed a function 'New' from
  2614. /// declarator D which has the same name and scope as a previous
  2615. /// declaration 'Old'. Figure out how to resolve this situation,
  2616. /// merging decls or emitting diagnostics as appropriate.
  2617. ///
  2618. /// In C++, New and Old must be declarations that are not
  2619. /// overloaded. Use IsOverload to determine whether New and Old are
  2620. /// overloaded, and to select the Old declaration that New should be
  2621. /// merged with.
  2622. ///
  2623. /// Returns true if there was an error, false otherwise.
  2624. bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
  2625. Scope *S, bool MergeTypeWithOld) {
  2626. // Verify the old decl was also a function.
  2627. FunctionDecl *Old = OldD->getAsFunction();
  2628. if (!Old) {
  2629. if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
  2630. if (New->getFriendObjectKind()) {
  2631. Diag(New->getLocation(), diag::err_using_decl_friend);
  2632. Diag(Shadow->getTargetDecl()->getLocation(),
  2633. diag::note_using_decl_target);
  2634. Diag(Shadow->getUsingDecl()->getLocation(),
  2635. diag::note_using_decl) << 0;
  2636. return true;
  2637. }
  2638. // Check whether the two declarations might declare the same function.
  2639. if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
  2640. return true;
  2641. OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
  2642. } else {
  2643. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  2644. << New->getDeclName();
  2645. notePreviousDefinition(OldD, New->getLocation());
  2646. return true;
  2647. }
  2648. }
  2649. // If the old declaration is invalid, just give up here.
  2650. if (Old->isInvalidDecl())
  2651. return true;
  2652. // Disallow redeclaration of some builtins.
  2653. if (!getASTContext().canBuiltinBeRedeclared(Old)) {
  2654. Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
  2655. Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
  2656. << Old << Old->getType();
  2657. return true;
  2658. }
  2659. diag::kind PrevDiag;
  2660. SourceLocation OldLocation;
  2661. std::tie(PrevDiag, OldLocation) =
  2662. getNoteDiagForInvalidRedeclaration(Old, New);
  2663. // Don't complain about this if we're in GNU89 mode and the old function
  2664. // is an extern inline function.
  2665. // Don't complain about specializations. They are not supposed to have
  2666. // storage classes.
  2667. if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
  2668. New->getStorageClass() == SC_Static &&
  2669. Old->hasExternalFormalLinkage() &&
  2670. !New->getTemplateSpecializationInfo() &&
  2671. !canRedefineFunction(Old, getLangOpts())) {
  2672. if (getLangOpts().MicrosoftExt) {
  2673. Diag(New->getLocation(), diag::ext_static_non_static) << New;
  2674. Diag(OldLocation, PrevDiag);
  2675. } else {
  2676. Diag(New->getLocation(), diag::err_static_non_static) << New;
  2677. Diag(OldLocation, PrevDiag);
  2678. return true;
  2679. }
  2680. }
  2681. if (New->hasAttr<InternalLinkageAttr>() &&
  2682. !Old->hasAttr<InternalLinkageAttr>()) {
  2683. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  2684. << New->getDeclName();
  2685. notePreviousDefinition(Old, New->getLocation());
  2686. New->dropAttr<InternalLinkageAttr>();
  2687. }
  2688. if (CheckRedeclarationModuleOwnership(New, Old))
  2689. return true;
  2690. if (!getLangOpts().CPlusPlus) {
  2691. bool OldOvl = Old->hasAttr<OverloadableAttr>();
  2692. if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
  2693. Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
  2694. << New << OldOvl;
  2695. // Try our best to find a decl that actually has the overloadable
  2696. // attribute for the note. In most cases (e.g. programs with only one
  2697. // broken declaration/definition), this won't matter.
  2698. //
  2699. // FIXME: We could do this if we juggled some extra state in
  2700. // OverloadableAttr, rather than just removing it.
  2701. const Decl *DiagOld = Old;
  2702. if (OldOvl) {
  2703. auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
  2704. const auto *A = D->getAttr<OverloadableAttr>();
  2705. return A && !A->isImplicit();
  2706. });
  2707. // If we've implicitly added *all* of the overloadable attrs to this
  2708. // chain, emitting a "previous redecl" note is pointless.
  2709. DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
  2710. }
  2711. if (DiagOld)
  2712. Diag(DiagOld->getLocation(),
  2713. diag::note_attribute_overloadable_prev_overload)
  2714. << OldOvl;
  2715. if (OldOvl)
  2716. New->addAttr(OverloadableAttr::CreateImplicit(Context));
  2717. else
  2718. New->dropAttr<OverloadableAttr>();
  2719. }
  2720. }
  2721. // If a function is first declared with a calling convention, but is later
  2722. // declared or defined without one, all following decls assume the calling
  2723. // convention of the first.
  2724. //
  2725. // It's OK if a function is first declared without a calling convention,
  2726. // but is later declared or defined with the default calling convention.
  2727. //
  2728. // To test if either decl has an explicit calling convention, we look for
  2729. // AttributedType sugar nodes on the type as written. If they are missing or
  2730. // were canonicalized away, we assume the calling convention was implicit.
  2731. //
  2732. // Note also that we DO NOT return at this point, because we still have
  2733. // other tests to run.
  2734. QualType OldQType = Context.getCanonicalType(Old->getType());
  2735. QualType NewQType = Context.getCanonicalType(New->getType());
  2736. const FunctionType *OldType = cast<FunctionType>(OldQType);
  2737. const FunctionType *NewType = cast<FunctionType>(NewQType);
  2738. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  2739. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  2740. bool RequiresAdjustment = false;
  2741. if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
  2742. FunctionDecl *First = Old->getFirstDecl();
  2743. const FunctionType *FT =
  2744. First->getType().getCanonicalType()->castAs<FunctionType>();
  2745. FunctionType::ExtInfo FI = FT->getExtInfo();
  2746. bool NewCCExplicit = getCallingConvAttributedType(New->getType());
  2747. if (!NewCCExplicit) {
  2748. // Inherit the CC from the previous declaration if it was specified
  2749. // there but not here.
  2750. NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
  2751. RequiresAdjustment = true;
  2752. } else {
  2753. // Calling conventions aren't compatible, so complain.
  2754. bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
  2755. Diag(New->getLocation(), diag::err_cconv_change)
  2756. << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
  2757. << !FirstCCExplicit
  2758. << (!FirstCCExplicit ? "" :
  2759. FunctionType::getNameForCallConv(FI.getCC()));
  2760. // Put the note on the first decl, since it is the one that matters.
  2761. Diag(First->getLocation(), diag::note_previous_declaration);
  2762. return true;
  2763. }
  2764. }
  2765. // FIXME: diagnose the other way around?
  2766. if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
  2767. NewTypeInfo = NewTypeInfo.withNoReturn(true);
  2768. RequiresAdjustment = true;
  2769. }
  2770. // Merge regparm attribute.
  2771. if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
  2772. OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
  2773. if (NewTypeInfo.getHasRegParm()) {
  2774. Diag(New->getLocation(), diag::err_regparm_mismatch)
  2775. << NewType->getRegParmType()
  2776. << OldType->getRegParmType();
  2777. Diag(OldLocation, diag::note_previous_declaration);
  2778. return true;
  2779. }
  2780. NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
  2781. RequiresAdjustment = true;
  2782. }
  2783. // Merge ns_returns_retained attribute.
  2784. if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
  2785. if (NewTypeInfo.getProducesResult()) {
  2786. Diag(New->getLocation(), diag::err_function_attribute_mismatch)
  2787. << "'ns_returns_retained'";
  2788. Diag(OldLocation, diag::note_previous_declaration);
  2789. return true;
  2790. }
  2791. NewTypeInfo = NewTypeInfo.withProducesResult(true);
  2792. RequiresAdjustment = true;
  2793. }
  2794. if (OldTypeInfo.getNoCallerSavedRegs() !=
  2795. NewTypeInfo.getNoCallerSavedRegs()) {
  2796. if (NewTypeInfo.getNoCallerSavedRegs()) {
  2797. AnyX86NoCallerSavedRegistersAttr *Attr =
  2798. New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
  2799. Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
  2800. Diag(OldLocation, diag::note_previous_declaration);
  2801. return true;
  2802. }
  2803. NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
  2804. RequiresAdjustment = true;
  2805. }
  2806. if (RequiresAdjustment) {
  2807. const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
  2808. AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
  2809. New->setType(QualType(AdjustedType, 0));
  2810. NewQType = Context.getCanonicalType(New->getType());
  2811. NewType = cast<FunctionType>(NewQType);
  2812. }
  2813. // If this redeclaration makes the function inline, we may need to add it to
  2814. // UndefinedButUsed.
  2815. if (!Old->isInlined() && New->isInlined() &&
  2816. !New->hasAttr<GNUInlineAttr>() &&
  2817. !getLangOpts().GNUInline &&
  2818. Old->isUsed(false) &&
  2819. !Old->isDefined() && !New->isThisDeclarationADefinition())
  2820. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  2821. SourceLocation()));
  2822. // If this redeclaration makes it newly gnu_inline, we don't want to warn
  2823. // about it.
  2824. if (New->hasAttr<GNUInlineAttr>() &&
  2825. Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
  2826. UndefinedButUsed.erase(Old->getCanonicalDecl());
  2827. }
  2828. // If pass_object_size params don't match up perfectly, this isn't a valid
  2829. // redeclaration.
  2830. if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
  2831. !hasIdenticalPassObjectSizeAttrs(Old, New)) {
  2832. Diag(New->getLocation(), diag::err_different_pass_object_size_params)
  2833. << New->getDeclName();
  2834. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2835. return true;
  2836. }
  2837. if (getLangOpts().CPlusPlus) {
  2838. // C++1z [over.load]p2
  2839. // Certain function declarations cannot be overloaded:
  2840. // -- Function declarations that differ only in the return type,
  2841. // the exception specification, or both cannot be overloaded.
  2842. // Check the exception specifications match. This may recompute the type of
  2843. // both Old and New if it resolved exception specifications, so grab the
  2844. // types again after this. Because this updates the type, we do this before
  2845. // any of the other checks below, which may update the "de facto" NewQType
  2846. // but do not necessarily update the type of New.
  2847. if (CheckEquivalentExceptionSpec(Old, New))
  2848. return true;
  2849. OldQType = Context.getCanonicalType(Old->getType());
  2850. NewQType = Context.getCanonicalType(New->getType());
  2851. // Go back to the type source info to compare the declared return types,
  2852. // per C++1y [dcl.type.auto]p13:
  2853. // Redeclarations or specializations of a function or function template
  2854. // with a declared return type that uses a placeholder type shall also
  2855. // use that placeholder, not a deduced type.
  2856. QualType OldDeclaredReturnType =
  2857. (Old->getTypeSourceInfo()
  2858. ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2859. : OldType)->getReturnType();
  2860. QualType NewDeclaredReturnType =
  2861. (New->getTypeSourceInfo()
  2862. ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
  2863. : NewType)->getReturnType();
  2864. if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
  2865. !((NewQType->isDependentType() || OldQType->isDependentType()) &&
  2866. New->isLocalExternDecl())) {
  2867. QualType ResQT;
  2868. if (NewDeclaredReturnType->isObjCObjectPointerType() &&
  2869. OldDeclaredReturnType->isObjCObjectPointerType())
  2870. ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
  2871. if (ResQT.isNull()) {
  2872. if (New->isCXXClassMember() && New->isOutOfLine())
  2873. Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
  2874. << New << New->getReturnTypeSourceRange();
  2875. else
  2876. Diag(New->getLocation(), diag::err_ovl_diff_return_type)
  2877. << New->getReturnTypeSourceRange();
  2878. Diag(OldLocation, PrevDiag) << Old << Old->getType()
  2879. << Old->getReturnTypeSourceRange();
  2880. return true;
  2881. }
  2882. else
  2883. NewQType = ResQT;
  2884. }
  2885. QualType OldReturnType = OldType->getReturnType();
  2886. QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
  2887. if (OldReturnType != NewReturnType) {
  2888. // If this function has a deduced return type and has already been
  2889. // defined, copy the deduced value from the old declaration.
  2890. AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
  2891. if (OldAT && OldAT->isDeduced()) {
  2892. New->setType(
  2893. SubstAutoType(New->getType(),
  2894. OldAT->isDependentType() ? Context.DependentTy
  2895. : OldAT->getDeducedType()));
  2896. NewQType = Context.getCanonicalType(
  2897. SubstAutoType(NewQType,
  2898. OldAT->isDependentType() ? Context.DependentTy
  2899. : OldAT->getDeducedType()));
  2900. }
  2901. }
  2902. const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
  2903. CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
  2904. if (OldMethod && NewMethod) {
  2905. // Preserve triviality.
  2906. NewMethod->setTrivial(OldMethod->isTrivial());
  2907. // MSVC allows explicit template specialization at class scope:
  2908. // 2 CXXMethodDecls referring to the same function will be injected.
  2909. // We don't want a redeclaration error.
  2910. bool IsClassScopeExplicitSpecialization =
  2911. OldMethod->isFunctionTemplateSpecialization() &&
  2912. NewMethod->isFunctionTemplateSpecialization();
  2913. bool isFriend = NewMethod->getFriendObjectKind();
  2914. if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
  2915. !IsClassScopeExplicitSpecialization) {
  2916. // -- Member function declarations with the same name and the
  2917. // same parameter types cannot be overloaded if any of them
  2918. // is a static member function declaration.
  2919. if (OldMethod->isStatic() != NewMethod->isStatic()) {
  2920. Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
  2921. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2922. return true;
  2923. }
  2924. // C++ [class.mem]p1:
  2925. // [...] A member shall not be declared twice in the
  2926. // member-specification, except that a nested class or member
  2927. // class template can be declared and then later defined.
  2928. if (!inTemplateInstantiation()) {
  2929. unsigned NewDiag;
  2930. if (isa<CXXConstructorDecl>(OldMethod))
  2931. NewDiag = diag::err_constructor_redeclared;
  2932. else if (isa<CXXDestructorDecl>(NewMethod))
  2933. NewDiag = diag::err_destructor_redeclared;
  2934. else if (isa<CXXConversionDecl>(NewMethod))
  2935. NewDiag = diag::err_conv_function_redeclared;
  2936. else
  2937. NewDiag = diag::err_member_redeclared;
  2938. Diag(New->getLocation(), NewDiag);
  2939. } else {
  2940. Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
  2941. << New << New->getType();
  2942. }
  2943. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  2944. return true;
  2945. // Complain if this is an explicit declaration of a special
  2946. // member that was initially declared implicitly.
  2947. //
  2948. // As an exception, it's okay to befriend such methods in order
  2949. // to permit the implicit constructor/destructor/operator calls.
  2950. } else if (OldMethod->isImplicit()) {
  2951. if (isFriend) {
  2952. NewMethod->setImplicit();
  2953. } else {
  2954. Diag(NewMethod->getLocation(),
  2955. diag::err_definition_of_implicitly_declared_member)
  2956. << New << getSpecialMember(OldMethod);
  2957. return true;
  2958. }
  2959. } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
  2960. Diag(NewMethod->getLocation(),
  2961. diag::err_definition_of_explicitly_defaulted_member)
  2962. << getSpecialMember(OldMethod);
  2963. return true;
  2964. }
  2965. }
  2966. // C++11 [dcl.attr.noreturn]p1:
  2967. // The first declaration of a function shall specify the noreturn
  2968. // attribute if any declaration of that function specifies the noreturn
  2969. // attribute.
  2970. const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
  2971. if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
  2972. Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
  2973. Diag(Old->getFirstDecl()->getLocation(),
  2974. diag::note_noreturn_missing_first_decl);
  2975. }
  2976. // C++11 [dcl.attr.depend]p2:
  2977. // The first declaration of a function shall specify the
  2978. // carries_dependency attribute for its declarator-id if any declaration
  2979. // of the function specifies the carries_dependency attribute.
  2980. const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
  2981. if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
  2982. Diag(CDA->getLocation(),
  2983. diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
  2984. Diag(Old->getFirstDecl()->getLocation(),
  2985. diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
  2986. }
  2987. // (C++98 8.3.5p3):
  2988. // All declarations for a function shall agree exactly in both the
  2989. // return type and the parameter-type-list.
  2990. // We also want to respect all the extended bits except noreturn.
  2991. // noreturn should now match unless the old type info didn't have it.
  2992. QualType OldQTypeForComparison = OldQType;
  2993. if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
  2994. auto *OldType = OldQType->castAs<FunctionProtoType>();
  2995. const FunctionType *OldTypeForComparison
  2996. = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
  2997. OldQTypeForComparison = QualType(OldTypeForComparison, 0);
  2998. assert(OldQTypeForComparison.isCanonical());
  2999. }
  3000. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3001. // As a special case, retain the language linkage from previous
  3002. // declarations of a friend function as an extension.
  3003. //
  3004. // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
  3005. // and is useful because there's otherwise no way to specify language
  3006. // linkage within class scope.
  3007. //
  3008. // Check cautiously as the friend object kind isn't yet complete.
  3009. if (New->getFriendObjectKind() != Decl::FOK_None) {
  3010. Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
  3011. Diag(OldLocation, PrevDiag);
  3012. } else {
  3013. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3014. Diag(OldLocation, PrevDiag);
  3015. return true;
  3016. }
  3017. }
  3018. if (OldQTypeForComparison == NewQType)
  3019. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3020. if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
  3021. New->isLocalExternDecl()) {
  3022. // It's OK if we couldn't merge types for a local function declaraton
  3023. // if either the old or new type is dependent. We'll merge the types
  3024. // when we instantiate the function.
  3025. return false;
  3026. }
  3027. // Fall through for conflicting redeclarations and redefinitions.
  3028. }
  3029. // C: Function types need to be compatible, not identical. This handles
  3030. // duplicate function decls like "void f(int); void f(enum X);" properly.
  3031. if (!getLangOpts().CPlusPlus &&
  3032. Context.typesAreCompatible(OldQType, NewQType)) {
  3033. const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
  3034. const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
  3035. const FunctionProtoType *OldProto = nullptr;
  3036. if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
  3037. (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
  3038. // The old declaration provided a function prototype, but the
  3039. // new declaration does not. Merge in the prototype.
  3040. assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
  3041. SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
  3042. NewQType =
  3043. Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
  3044. OldProto->getExtProtoInfo());
  3045. New->setType(NewQType);
  3046. New->setHasInheritedPrototype();
  3047. // Synthesize parameters with the same types.
  3048. SmallVector<ParmVarDecl*, 16> Params;
  3049. for (const auto &ParamType : OldProto->param_types()) {
  3050. ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
  3051. SourceLocation(), nullptr,
  3052. ParamType, /*TInfo=*/nullptr,
  3053. SC_None, nullptr);
  3054. Param->setScopeInfo(0, Params.size());
  3055. Param->setImplicit();
  3056. Params.push_back(Param);
  3057. }
  3058. New->setParams(Params);
  3059. }
  3060. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3061. }
  3062. // GNU C permits a K&R definition to follow a prototype declaration
  3063. // if the declared types of the parameters in the K&R definition
  3064. // match the types in the prototype declaration, even when the
  3065. // promoted types of the parameters from the K&R definition differ
  3066. // from the types in the prototype. GCC then keeps the types from
  3067. // the prototype.
  3068. //
  3069. // If a variadic prototype is followed by a non-variadic K&R definition,
  3070. // the K&R definition becomes variadic. This is sort of an edge case, but
  3071. // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
  3072. // C99 6.9.1p8.
  3073. if (!getLangOpts().CPlusPlus &&
  3074. Old->hasPrototype() && !New->hasPrototype() &&
  3075. New->getType()->getAs<FunctionProtoType>() &&
  3076. Old->getNumParams() == New->getNumParams()) {
  3077. SmallVector<QualType, 16> ArgTypes;
  3078. SmallVector<GNUCompatibleParamWarning, 16> Warnings;
  3079. const FunctionProtoType *OldProto
  3080. = Old->getType()->getAs<FunctionProtoType>();
  3081. const FunctionProtoType *NewProto
  3082. = New->getType()->getAs<FunctionProtoType>();
  3083. // Determine whether this is the GNU C extension.
  3084. QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
  3085. NewProto->getReturnType());
  3086. bool LooseCompatible = !MergedReturn.isNull();
  3087. for (unsigned Idx = 0, End = Old->getNumParams();
  3088. LooseCompatible && Idx != End; ++Idx) {
  3089. ParmVarDecl *OldParm = Old->getParamDecl(Idx);
  3090. ParmVarDecl *NewParm = New->getParamDecl(Idx);
  3091. if (Context.typesAreCompatible(OldParm->getType(),
  3092. NewProto->getParamType(Idx))) {
  3093. ArgTypes.push_back(NewParm->getType());
  3094. } else if (Context.typesAreCompatible(OldParm->getType(),
  3095. NewParm->getType(),
  3096. /*CompareUnqualified=*/true)) {
  3097. GNUCompatibleParamWarning Warn = { OldParm, NewParm,
  3098. NewProto->getParamType(Idx) };
  3099. Warnings.push_back(Warn);
  3100. ArgTypes.push_back(NewParm->getType());
  3101. } else
  3102. LooseCompatible = false;
  3103. }
  3104. if (LooseCompatible) {
  3105. for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
  3106. Diag(Warnings[Warn].NewParm->getLocation(),
  3107. diag::ext_param_promoted_not_compatible_with_prototype)
  3108. << Warnings[Warn].PromotedType
  3109. << Warnings[Warn].OldParm->getType();
  3110. if (Warnings[Warn].OldParm->getLocation().isValid())
  3111. Diag(Warnings[Warn].OldParm->getLocation(),
  3112. diag::note_previous_declaration);
  3113. }
  3114. if (MergeTypeWithOld)
  3115. New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
  3116. OldProto->getExtProtoInfo()));
  3117. return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
  3118. }
  3119. // Fall through to diagnose conflicting types.
  3120. }
  3121. // A function that has already been declared has been redeclared or
  3122. // defined with a different type; show an appropriate diagnostic.
  3123. // If the previous declaration was an implicitly-generated builtin
  3124. // declaration, then at the very least we should use a specialized note.
  3125. unsigned BuiltinID;
  3126. if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
  3127. // If it's actually a library-defined builtin function like 'malloc'
  3128. // or 'printf', just warn about the incompatible redeclaration.
  3129. if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
  3130. Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
  3131. Diag(OldLocation, diag::note_previous_builtin_declaration)
  3132. << Old << Old->getType();
  3133. // If this is a global redeclaration, just forget hereafter
  3134. // about the "builtin-ness" of the function.
  3135. //
  3136. // Doing this for local extern declarations is problematic. If
  3137. // the builtin declaration remains visible, a second invalid
  3138. // local declaration will produce a hard error; if it doesn't
  3139. // remain visible, a single bogus local redeclaration (which is
  3140. // actually only a warning) could break all the downstream code.
  3141. if (!New->getLexicalDeclContext()->isFunctionOrMethod())
  3142. New->getIdentifier()->revertBuiltin();
  3143. return false;
  3144. }
  3145. PrevDiag = diag::note_previous_builtin_declaration;
  3146. }
  3147. Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
  3148. Diag(OldLocation, PrevDiag) << Old << Old->getType();
  3149. return true;
  3150. }
  3151. /// Completes the merge of two function declarations that are
  3152. /// known to be compatible.
  3153. ///
  3154. /// This routine handles the merging of attributes and other
  3155. /// properties of function declarations from the old declaration to
  3156. /// the new declaration, once we know that New is in fact a
  3157. /// redeclaration of Old.
  3158. ///
  3159. /// \returns false
  3160. bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
  3161. Scope *S, bool MergeTypeWithOld) {
  3162. // Merge the attributes
  3163. mergeDeclAttributes(New, Old);
  3164. // Merge "pure" flag.
  3165. if (Old->isPure())
  3166. New->setPure();
  3167. // Merge "used" flag.
  3168. if (Old->getMostRecentDecl()->isUsed(false))
  3169. New->setIsUsed();
  3170. // Merge attributes from the parameters. These can mismatch with K&R
  3171. // declarations.
  3172. if (New->getNumParams() == Old->getNumParams())
  3173. for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
  3174. ParmVarDecl *NewParam = New->getParamDecl(i);
  3175. ParmVarDecl *OldParam = Old->getParamDecl(i);
  3176. mergeParamDeclAttributes(NewParam, OldParam, *this);
  3177. mergeParamDeclTypes(NewParam, OldParam, *this);
  3178. }
  3179. if (getLangOpts().CPlusPlus)
  3180. return MergeCXXFunctionDecl(New, Old, S);
  3181. // Merge the function types so the we get the composite types for the return
  3182. // and argument types. Per C11 6.2.7/4, only update the type if the old decl
  3183. // was visible.
  3184. QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
  3185. if (!Merged.isNull() && MergeTypeWithOld)
  3186. New->setType(Merged);
  3187. return false;
  3188. }
  3189. void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
  3190. ObjCMethodDecl *oldMethod) {
  3191. // Merge the attributes, including deprecated/unavailable
  3192. AvailabilityMergeKind MergeKind =
  3193. isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
  3194. ? AMK_ProtocolImplementation
  3195. : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
  3196. : AMK_Override;
  3197. mergeDeclAttributes(newMethod, oldMethod, MergeKind);
  3198. // Merge attributes from the parameters.
  3199. ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
  3200. oe = oldMethod->param_end();
  3201. for (ObjCMethodDecl::param_iterator
  3202. ni = newMethod->param_begin(), ne = newMethod->param_end();
  3203. ni != ne && oi != oe; ++ni, ++oi)
  3204. mergeParamDeclAttributes(*ni, *oi, *this);
  3205. CheckObjCMethodOverride(newMethod, oldMethod);
  3206. }
  3207. static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
  3208. assert(!S.Context.hasSameType(New->getType(), Old->getType()));
  3209. S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
  3210. ? diag::err_redefinition_different_type
  3211. : diag::err_redeclaration_different_type)
  3212. << New->getDeclName() << New->getType() << Old->getType();
  3213. diag::kind PrevDiag;
  3214. SourceLocation OldLocation;
  3215. std::tie(PrevDiag, OldLocation)
  3216. = getNoteDiagForInvalidRedeclaration(Old, New);
  3217. S.Diag(OldLocation, PrevDiag);
  3218. New->setInvalidDecl();
  3219. }
  3220. /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
  3221. /// scope as a previous declaration 'Old'. Figure out how to merge their types,
  3222. /// emitting diagnostics as appropriate.
  3223. ///
  3224. /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
  3225. /// to here in AddInitializerToDecl. We can't check them before the initializer
  3226. /// is attached.
  3227. void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
  3228. bool MergeTypeWithOld) {
  3229. if (New->isInvalidDecl() || Old->isInvalidDecl())
  3230. return;
  3231. QualType MergedT;
  3232. if (getLangOpts().CPlusPlus) {
  3233. if (New->getType()->isUndeducedType()) {
  3234. // We don't know what the new type is until the initializer is attached.
  3235. return;
  3236. } else if (Context.hasSameType(New->getType(), Old->getType())) {
  3237. // These could still be something that needs exception specs checked.
  3238. return MergeVarDeclExceptionSpecs(New, Old);
  3239. }
  3240. // C++ [basic.link]p10:
  3241. // [...] the types specified by all declarations referring to a given
  3242. // object or function shall be identical, except that declarations for an
  3243. // array object can specify array types that differ by the presence or
  3244. // absence of a major array bound (8.3.4).
  3245. else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
  3246. const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
  3247. const ArrayType *NewArray = Context.getAsArrayType(New->getType());
  3248. // We are merging a variable declaration New into Old. If it has an array
  3249. // bound, and that bound differs from Old's bound, we should diagnose the
  3250. // mismatch.
  3251. if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
  3252. for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
  3253. PrevVD = PrevVD->getPreviousDecl()) {
  3254. const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
  3255. if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
  3256. continue;
  3257. if (!Context.hasSameType(NewArray, PrevVDTy))
  3258. return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
  3259. }
  3260. }
  3261. if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
  3262. if (Context.hasSameType(OldArray->getElementType(),
  3263. NewArray->getElementType()))
  3264. MergedT = New->getType();
  3265. }
  3266. // FIXME: Check visibility. New is hidden but has a complete type. If New
  3267. // has no array bound, it should not inherit one from Old, if Old is not
  3268. // visible.
  3269. else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
  3270. if (Context.hasSameType(OldArray->getElementType(),
  3271. NewArray->getElementType()))
  3272. MergedT = Old->getType();
  3273. }
  3274. }
  3275. else if (New->getType()->isObjCObjectPointerType() &&
  3276. Old->getType()->isObjCObjectPointerType()) {
  3277. MergedT = Context.mergeObjCGCQualifiers(New->getType(),
  3278. Old->getType());
  3279. }
  3280. } else {
  3281. // C 6.2.7p2:
  3282. // All declarations that refer to the same object or function shall have
  3283. // compatible type.
  3284. MergedT = Context.mergeTypes(New->getType(), Old->getType());
  3285. }
  3286. if (MergedT.isNull()) {
  3287. // It's OK if we couldn't merge types if either type is dependent, for a
  3288. // block-scope variable. In other cases (static data members of class
  3289. // templates, variable templates, ...), we require the types to be
  3290. // equivalent.
  3291. // FIXME: The C++ standard doesn't say anything about this.
  3292. if ((New->getType()->isDependentType() ||
  3293. Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
  3294. // If the old type was dependent, we can't merge with it, so the new type
  3295. // becomes dependent for now. We'll reproduce the original type when we
  3296. // instantiate the TypeSourceInfo for the variable.
  3297. if (!New->getType()->isDependentType() && MergeTypeWithOld)
  3298. New->setType(Context.DependentTy);
  3299. return;
  3300. }
  3301. return diagnoseVarDeclTypeMismatch(*this, New, Old);
  3302. }
  3303. // Don't actually update the type on the new declaration if the old
  3304. // declaration was an extern declaration in a different scope.
  3305. if (MergeTypeWithOld)
  3306. New->setType(MergedT);
  3307. }
  3308. static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
  3309. LookupResult &Previous) {
  3310. // C11 6.2.7p4:
  3311. // For an identifier with internal or external linkage declared
  3312. // in a scope in which a prior declaration of that identifier is
  3313. // visible, if the prior declaration specifies internal or
  3314. // external linkage, the type of the identifier at the later
  3315. // declaration becomes the composite type.
  3316. //
  3317. // If the variable isn't visible, we do not merge with its type.
  3318. if (Previous.isShadowed())
  3319. return false;
  3320. if (S.getLangOpts().CPlusPlus) {
  3321. // C++11 [dcl.array]p3:
  3322. // If there is a preceding declaration of the entity in the same
  3323. // scope in which the bound was specified, an omitted array bound
  3324. // is taken to be the same as in that earlier declaration.
  3325. return NewVD->isPreviousDeclInSameBlockScope() ||
  3326. (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
  3327. !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
  3328. } else {
  3329. // If the old declaration was function-local, don't merge with its
  3330. // type unless we're in the same function.
  3331. return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
  3332. OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
  3333. }
  3334. }
  3335. /// MergeVarDecl - We just parsed a variable 'New' which has the same name
  3336. /// and scope as a previous declaration 'Old'. Figure out how to resolve this
  3337. /// situation, merging decls or emitting diagnostics as appropriate.
  3338. ///
  3339. /// Tentative definition rules (C99 6.9.2p2) are checked by
  3340. /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
  3341. /// definitions here, since the initializer hasn't been attached.
  3342. ///
  3343. void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
  3344. // If the new decl is already invalid, don't do any other checking.
  3345. if (New->isInvalidDecl())
  3346. return;
  3347. if (!shouldLinkPossiblyHiddenDecl(Previous, New))
  3348. return;
  3349. VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
  3350. // Verify the old decl was also a variable or variable template.
  3351. VarDecl *Old = nullptr;
  3352. VarTemplateDecl *OldTemplate = nullptr;
  3353. if (Previous.isSingleResult()) {
  3354. if (NewTemplate) {
  3355. OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
  3356. Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
  3357. if (auto *Shadow =
  3358. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3359. if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
  3360. return New->setInvalidDecl();
  3361. } else {
  3362. Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
  3363. if (auto *Shadow =
  3364. dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
  3365. if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
  3366. return New->setInvalidDecl();
  3367. }
  3368. }
  3369. if (!Old) {
  3370. Diag(New->getLocation(), diag::err_redefinition_different_kind)
  3371. << New->getDeclName();
  3372. notePreviousDefinition(Previous.getRepresentativeDecl(),
  3373. New->getLocation());
  3374. return New->setInvalidDecl();
  3375. }
  3376. // Ensure the template parameters are compatible.
  3377. if (NewTemplate &&
  3378. !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
  3379. OldTemplate->getTemplateParameters(),
  3380. /*Complain=*/true, TPL_TemplateMatch))
  3381. return New->setInvalidDecl();
  3382. // C++ [class.mem]p1:
  3383. // A member shall not be declared twice in the member-specification [...]
  3384. //
  3385. // Here, we need only consider static data members.
  3386. if (Old->isStaticDataMember() && !New->isOutOfLine()) {
  3387. Diag(New->getLocation(), diag::err_duplicate_member)
  3388. << New->getIdentifier();
  3389. Diag(Old->getLocation(), diag::note_previous_declaration);
  3390. New->setInvalidDecl();
  3391. }
  3392. mergeDeclAttributes(New, Old);
  3393. // Warn if an already-declared variable is made a weak_import in a subsequent
  3394. // declaration
  3395. if (New->hasAttr<WeakImportAttr>() &&
  3396. Old->getStorageClass() == SC_None &&
  3397. !Old->hasAttr<WeakImportAttr>()) {
  3398. Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
  3399. notePreviousDefinition(Old, New->getLocation());
  3400. // Remove weak_import attribute on new declaration.
  3401. New->dropAttr<WeakImportAttr>();
  3402. }
  3403. if (New->hasAttr<InternalLinkageAttr>() &&
  3404. !Old->hasAttr<InternalLinkageAttr>()) {
  3405. Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
  3406. << New->getDeclName();
  3407. notePreviousDefinition(Old, New->getLocation());
  3408. New->dropAttr<InternalLinkageAttr>();
  3409. }
  3410. // Merge the types.
  3411. VarDecl *MostRecent = Old->getMostRecentDecl();
  3412. if (MostRecent != Old) {
  3413. MergeVarDeclTypes(New, MostRecent,
  3414. mergeTypeWithPrevious(*this, New, MostRecent, Previous));
  3415. if (New->isInvalidDecl())
  3416. return;
  3417. }
  3418. MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
  3419. if (New->isInvalidDecl())
  3420. return;
  3421. diag::kind PrevDiag;
  3422. SourceLocation OldLocation;
  3423. std::tie(PrevDiag, OldLocation) =
  3424. getNoteDiagForInvalidRedeclaration(Old, New);
  3425. // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
  3426. if (New->getStorageClass() == SC_Static &&
  3427. !New->isStaticDataMember() &&
  3428. Old->hasExternalFormalLinkage()) {
  3429. if (getLangOpts().MicrosoftExt) {
  3430. Diag(New->getLocation(), diag::ext_static_non_static)
  3431. << New->getDeclName();
  3432. Diag(OldLocation, PrevDiag);
  3433. } else {
  3434. Diag(New->getLocation(), diag::err_static_non_static)
  3435. << New->getDeclName();
  3436. Diag(OldLocation, PrevDiag);
  3437. return New->setInvalidDecl();
  3438. }
  3439. }
  3440. // C99 6.2.2p4:
  3441. // For an identifier declared with the storage-class specifier
  3442. // extern in a scope in which a prior declaration of that
  3443. // identifier is visible,23) if the prior declaration specifies
  3444. // internal or external linkage, the linkage of the identifier at
  3445. // the later declaration is the same as the linkage specified at
  3446. // the prior declaration. If no prior declaration is visible, or
  3447. // if the prior declaration specifies no linkage, then the
  3448. // identifier has external linkage.
  3449. if (New->hasExternalStorage() && Old->hasLinkage())
  3450. /* Okay */;
  3451. else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
  3452. !New->isStaticDataMember() &&
  3453. Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
  3454. Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
  3455. Diag(OldLocation, PrevDiag);
  3456. return New->setInvalidDecl();
  3457. }
  3458. // Check if extern is followed by non-extern and vice-versa.
  3459. if (New->hasExternalStorage() &&
  3460. !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
  3461. Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
  3462. Diag(OldLocation, PrevDiag);
  3463. return New->setInvalidDecl();
  3464. }
  3465. if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
  3466. !New->hasExternalStorage()) {
  3467. Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
  3468. Diag(OldLocation, PrevDiag);
  3469. return New->setInvalidDecl();
  3470. }
  3471. if (CheckRedeclarationModuleOwnership(New, Old))
  3472. return;
  3473. // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
  3474. // FIXME: The test for external storage here seems wrong? We still
  3475. // need to check for mismatches.
  3476. if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
  3477. // Don't complain about out-of-line definitions of static members.
  3478. !(Old->getLexicalDeclContext()->isRecord() &&
  3479. !New->getLexicalDeclContext()->isRecord())) {
  3480. Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
  3481. Diag(OldLocation, PrevDiag);
  3482. return New->setInvalidDecl();
  3483. }
  3484. if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
  3485. if (VarDecl *Def = Old->getDefinition()) {
  3486. // C++1z [dcl.fcn.spec]p4:
  3487. // If the definition of a variable appears in a translation unit before
  3488. // its first declaration as inline, the program is ill-formed.
  3489. Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
  3490. Diag(Def->getLocation(), diag::note_previous_definition);
  3491. }
  3492. }
  3493. // If this redeclaration makes the variable inline, we may need to add it to
  3494. // UndefinedButUsed.
  3495. if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
  3496. !Old->getDefinition() && !New->isThisDeclarationADefinition())
  3497. UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
  3498. SourceLocation()));
  3499. if (New->getTLSKind() != Old->getTLSKind()) {
  3500. if (!Old->getTLSKind()) {
  3501. Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
  3502. Diag(OldLocation, PrevDiag);
  3503. } else if (!New->getTLSKind()) {
  3504. Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
  3505. Diag(OldLocation, PrevDiag);
  3506. } else {
  3507. // Do not allow redeclaration to change the variable between requiring
  3508. // static and dynamic initialization.
  3509. // FIXME: GCC allows this, but uses the TLS keyword on the first
  3510. // declaration to determine the kind. Do we need to be compatible here?
  3511. Diag(New->getLocation(), diag::err_thread_thread_different_kind)
  3512. << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
  3513. Diag(OldLocation, PrevDiag);
  3514. }
  3515. }
  3516. // C++ doesn't have tentative definitions, so go right ahead and check here.
  3517. if (getLangOpts().CPlusPlus &&
  3518. New->isThisDeclarationADefinition() == VarDecl::Definition) {
  3519. if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
  3520. Old->getCanonicalDecl()->isConstexpr()) {
  3521. // This definition won't be a definition any more once it's been merged.
  3522. Diag(New->getLocation(),
  3523. diag::warn_deprecated_redundant_constexpr_static_def);
  3524. } else if (VarDecl *Def = Old->getDefinition()) {
  3525. if (checkVarDeclRedefinition(Def, New))
  3526. return;
  3527. }
  3528. }
  3529. if (haveIncompatibleLanguageLinkages(Old, New)) {
  3530. Diag(New->getLocation(), diag::err_different_language_linkage) << New;
  3531. Diag(OldLocation, PrevDiag);
  3532. New->setInvalidDecl();
  3533. return;
  3534. }
  3535. // Merge "used" flag.
  3536. if (Old->getMostRecentDecl()->isUsed(false))
  3537. New->setIsUsed();
  3538. // Keep a chain of previous declarations.
  3539. New->setPreviousDecl(Old);
  3540. if (NewTemplate)
  3541. NewTemplate->setPreviousDecl(OldTemplate);
  3542. adjustDeclContextForDeclaratorDecl(New, Old);
  3543. // Inherit access appropriately.
  3544. New->setAccess(Old->getAccess());
  3545. if (NewTemplate)
  3546. NewTemplate->setAccess(New->getAccess());
  3547. if (Old->isInline())
  3548. New->setImplicitlyInline();
  3549. }
  3550. void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
  3551. SourceManager &SrcMgr = getSourceManager();
  3552. auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
  3553. auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
  3554. auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
  3555. auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
  3556. auto &HSI = PP.getHeaderSearchInfo();
  3557. StringRef HdrFilename =
  3558. SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
  3559. auto noteFromModuleOrInclude = [&](Module *Mod,
  3560. SourceLocation IncLoc) -> bool {
  3561. // Redefinition errors with modules are common with non modular mapped
  3562. // headers, example: a non-modular header H in module A that also gets
  3563. // included directly in a TU. Pointing twice to the same header/definition
  3564. // is confusing, try to get better diagnostics when modules is on.
  3565. if (IncLoc.isValid()) {
  3566. if (Mod) {
  3567. Diag(IncLoc, diag::note_redefinition_modules_same_file)
  3568. << HdrFilename.str() << Mod->getFullModuleName();
  3569. if (!Mod->DefinitionLoc.isInvalid())
  3570. Diag(Mod->DefinitionLoc, diag::note_defined_here)
  3571. << Mod->getFullModuleName();
  3572. } else {
  3573. Diag(IncLoc, diag::note_redefinition_include_same_file)
  3574. << HdrFilename.str();
  3575. }
  3576. return true;
  3577. }
  3578. return false;
  3579. };
  3580. // Is it the same file and same offset? Provide more information on why
  3581. // this leads to a redefinition error.
  3582. bool EmittedDiag = false;
  3583. if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
  3584. SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
  3585. SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
  3586. EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
  3587. EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
  3588. // If the header has no guards, emit a note suggesting one.
  3589. if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
  3590. Diag(Old->getLocation(), diag::note_use_ifdef_guards);
  3591. if (EmittedDiag)
  3592. return;
  3593. }
  3594. // Redefinition coming from different files or couldn't do better above.
  3595. if (Old->getLocation().isValid())
  3596. Diag(Old->getLocation(), diag::note_previous_definition);
  3597. }
  3598. /// We've just determined that \p Old and \p New both appear to be definitions
  3599. /// of the same variable. Either diagnose or fix the problem.
  3600. bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
  3601. if (!hasVisibleDefinition(Old) &&
  3602. (New->getFormalLinkage() == InternalLinkage ||
  3603. New->isInline() ||
  3604. New->getDescribedVarTemplate() ||
  3605. New->getNumTemplateParameterLists() ||
  3606. New->getDeclContext()->isDependentContext())) {
  3607. // The previous definition is hidden, and multiple definitions are
  3608. // permitted (in separate TUs). Demote this to a declaration.
  3609. New->demoteThisDefinitionToDeclaration();
  3610. // Make the canonical definition visible.
  3611. if (auto *OldTD = Old->getDescribedVarTemplate())
  3612. makeMergedDefinitionVisible(OldTD);
  3613. makeMergedDefinitionVisible(Old);
  3614. return false;
  3615. } else {
  3616. Diag(New->getLocation(), diag::err_redefinition) << New;
  3617. notePreviousDefinition(Old, New->getLocation());
  3618. New->setInvalidDecl();
  3619. return true;
  3620. }
  3621. }
  3622. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3623. /// no declarator (e.g. "struct foo;") is parsed.
  3624. Decl *
  3625. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3626. RecordDecl *&AnonRecord) {
  3627. return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
  3628. AnonRecord);
  3629. }
  3630. // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
  3631. // disambiguate entities defined in different scopes.
  3632. // While the VS2015 ABI fixes potential miscompiles, it is also breaks
  3633. // compatibility.
  3634. // We will pick our mangling number depending on which version of MSVC is being
  3635. // targeted.
  3636. static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
  3637. return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
  3638. ? S->getMSCurManglingNumber()
  3639. : S->getMSLastManglingNumber();
  3640. }
  3641. void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
  3642. if (!Context.getLangOpts().CPlusPlus)
  3643. return;
  3644. if (isa<CXXRecordDecl>(Tag->getParent())) {
  3645. // If this tag is the direct child of a class, number it if
  3646. // it is anonymous.
  3647. if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
  3648. return;
  3649. MangleNumberingContext &MCtx =
  3650. Context.getManglingNumberContext(Tag->getParent());
  3651. Context.setManglingNumber(
  3652. Tag, MCtx.getManglingNumber(
  3653. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3654. return;
  3655. }
  3656. // If this tag isn't a direct child of a class, number it if it is local.
  3657. Decl *ManglingContextDecl;
  3658. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  3659. Tag->getDeclContext(), ManglingContextDecl)) {
  3660. Context.setManglingNumber(
  3661. Tag, MCtx->getManglingNumber(
  3662. Tag, getMSManglingNumber(getLangOpts(), TagScope)));
  3663. }
  3664. }
  3665. void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
  3666. TypedefNameDecl *NewTD) {
  3667. if (TagFromDeclSpec->isInvalidDecl())
  3668. return;
  3669. // Do nothing if the tag already has a name for linkage purposes.
  3670. if (TagFromDeclSpec->hasNameForLinkage())
  3671. return;
  3672. // A well-formed anonymous tag must always be a TUK_Definition.
  3673. assert(TagFromDeclSpec->isThisDeclarationADefinition());
  3674. // The type must match the tag exactly; no qualifiers allowed.
  3675. if (!Context.hasSameType(NewTD->getUnderlyingType(),
  3676. Context.getTagDeclType(TagFromDeclSpec))) {
  3677. if (getLangOpts().CPlusPlus)
  3678. Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
  3679. return;
  3680. }
  3681. // If we've already computed linkage for the anonymous tag, then
  3682. // adding a typedef name for the anonymous decl can change that
  3683. // linkage, which might be a serious problem. Diagnose this as
  3684. // unsupported and ignore the typedef name. TODO: we should
  3685. // pursue this as a language defect and establish a formal rule
  3686. // for how to handle it.
  3687. if (TagFromDeclSpec->hasLinkageBeenComputed()) {
  3688. Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
  3689. SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
  3690. tagLoc = getLocForEndOfToken(tagLoc);
  3691. llvm::SmallString<40> textToInsert;
  3692. textToInsert += ' ';
  3693. textToInsert += NewTD->getIdentifier()->getName();
  3694. Diag(tagLoc, diag::note_typedef_changes_linkage)
  3695. << FixItHint::CreateInsertion(tagLoc, textToInsert);
  3696. return;
  3697. }
  3698. // Otherwise, set this is the anon-decl typedef for the tag.
  3699. TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
  3700. }
  3701. static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
  3702. switch (T) {
  3703. case DeclSpec::TST_class:
  3704. return 0;
  3705. case DeclSpec::TST_struct:
  3706. return 1;
  3707. case DeclSpec::TST_interface:
  3708. return 2;
  3709. case DeclSpec::TST_union:
  3710. return 3;
  3711. case DeclSpec::TST_enum:
  3712. return 4;
  3713. default:
  3714. llvm_unreachable("unexpected type specifier");
  3715. }
  3716. }
  3717. /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
  3718. /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
  3719. /// parameters to cope with template friend declarations.
  3720. Decl *
  3721. Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
  3722. MultiTemplateParamsArg TemplateParams,
  3723. bool IsExplicitInstantiation,
  3724. RecordDecl *&AnonRecord) {
  3725. Decl *TagD = nullptr;
  3726. TagDecl *Tag = nullptr;
  3727. if (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3728. DS.getTypeSpecType() == DeclSpec::TST_struct ||
  3729. DS.getTypeSpecType() == DeclSpec::TST_interface ||
  3730. DS.getTypeSpecType() == DeclSpec::TST_union ||
  3731. DS.getTypeSpecType() == DeclSpec::TST_enum) {
  3732. TagD = DS.getRepAsDecl();
  3733. if (!TagD) // We probably had an error
  3734. return nullptr;
  3735. // Note that the above type specs guarantee that the
  3736. // type rep is a Decl, whereas in many of the others
  3737. // it's a Type.
  3738. if (isa<TagDecl>(TagD))
  3739. Tag = cast<TagDecl>(TagD);
  3740. else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
  3741. Tag = CTD->getTemplatedDecl();
  3742. }
  3743. if (Tag) {
  3744. handleTagNumbering(Tag, S);
  3745. Tag->setFreeStanding();
  3746. if (Tag->isInvalidDecl())
  3747. return Tag;
  3748. }
  3749. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  3750. // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
  3751. // or incomplete types shall not be restrict-qualified."
  3752. if (TypeQuals & DeclSpec::TQ_restrict)
  3753. Diag(DS.getRestrictSpecLoc(),
  3754. diag::err_typecheck_invalid_restrict_not_pointer_noarg)
  3755. << DS.getSourceRange();
  3756. }
  3757. if (DS.isInlineSpecified())
  3758. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  3759. << getLangOpts().CPlusPlus17;
  3760. if (DS.isConstexprSpecified()) {
  3761. // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
  3762. // and definitions of functions and variables.
  3763. if (Tag)
  3764. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
  3765. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
  3766. else
  3767. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
  3768. // Don't emit warnings after this error.
  3769. return TagD;
  3770. }
  3771. DiagnoseFunctionSpecifiers(DS);
  3772. if (DS.isFriendSpecified()) {
  3773. // If we're dealing with a decl but not a TagDecl, assume that
  3774. // whatever routines created it handled the friendship aspect.
  3775. if (TagD && !Tag)
  3776. return nullptr;
  3777. return ActOnFriendTypeDecl(S, DS, TemplateParams);
  3778. }
  3779. const CXXScopeSpec &SS = DS.getTypeSpecScope();
  3780. bool IsExplicitSpecialization =
  3781. !TemplateParams.empty() && TemplateParams.back()->size() == 0;
  3782. if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
  3783. !IsExplicitInstantiation && !IsExplicitSpecialization &&
  3784. !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
  3785. // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
  3786. // nested-name-specifier unless it is an explicit instantiation
  3787. // or an explicit specialization.
  3788. //
  3789. // FIXME: We allow class template partial specializations here too, per the
  3790. // obvious intent of DR1819.
  3791. //
  3792. // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
  3793. Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
  3794. << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
  3795. return nullptr;
  3796. }
  3797. // Track whether this decl-specifier declares anything.
  3798. bool DeclaresAnything = true;
  3799. // Handle anonymous struct definitions.
  3800. if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
  3801. if (!Record->getDeclName() && Record->isCompleteDefinition() &&
  3802. DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
  3803. if (getLangOpts().CPlusPlus ||
  3804. Record->getDeclContext()->isRecord()) {
  3805. // If CurContext is a DeclContext that can contain statements,
  3806. // RecursiveASTVisitor won't visit the decls that
  3807. // BuildAnonymousStructOrUnion() will put into CurContext.
  3808. // Also store them here so that they can be part of the
  3809. // DeclStmt that gets created in this case.
  3810. // FIXME: Also return the IndirectFieldDecls created by
  3811. // BuildAnonymousStructOr union, for the same reason?
  3812. if (CurContext->isFunctionOrMethod())
  3813. AnonRecord = Record;
  3814. return BuildAnonymousStructOrUnion(S, DS, AS, Record,
  3815. Context.getPrintingPolicy());
  3816. }
  3817. DeclaresAnything = false;
  3818. }
  3819. }
  3820. // C11 6.7.2.1p2:
  3821. // A struct-declaration that does not declare an anonymous structure or
  3822. // anonymous union shall contain a struct-declarator-list.
  3823. //
  3824. // This rule also existed in C89 and C99; the grammar for struct-declaration
  3825. // did not permit a struct-declaration without a struct-declarator-list.
  3826. if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
  3827. DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
  3828. // Check for Microsoft C extension: anonymous struct/union member.
  3829. // Handle 2 kinds of anonymous struct/union:
  3830. // struct STRUCT;
  3831. // union UNION;
  3832. // and
  3833. // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
  3834. // UNION_TYPE; <- where UNION_TYPE is a typedef union.
  3835. if ((Tag && Tag->getDeclName()) ||
  3836. DS.getTypeSpecType() == DeclSpec::TST_typename) {
  3837. RecordDecl *Record = nullptr;
  3838. if (Tag)
  3839. Record = dyn_cast<RecordDecl>(Tag);
  3840. else if (const RecordType *RT =
  3841. DS.getRepAsType().get()->getAsStructureType())
  3842. Record = RT->getDecl();
  3843. else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
  3844. Record = UT->getDecl();
  3845. if (Record && getLangOpts().MicrosoftExt) {
  3846. Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
  3847. << Record->isUnion() << DS.getSourceRange();
  3848. return BuildMicrosoftCAnonymousStruct(S, DS, Record);
  3849. }
  3850. DeclaresAnything = false;
  3851. }
  3852. }
  3853. // Skip all the checks below if we have a type error.
  3854. if (DS.getTypeSpecType() == DeclSpec::TST_error ||
  3855. (TagD && TagD->isInvalidDecl()))
  3856. return TagD;
  3857. if (getLangOpts().CPlusPlus &&
  3858. DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
  3859. if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
  3860. if (Enum->enumerator_begin() == Enum->enumerator_end() &&
  3861. !Enum->getIdentifier() && !Enum->isInvalidDecl())
  3862. DeclaresAnything = false;
  3863. if (!DS.isMissingDeclaratorOk()) {
  3864. // Customize diagnostic for a typedef missing a name.
  3865. if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
  3866. Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
  3867. << DS.getSourceRange();
  3868. else
  3869. DeclaresAnything = false;
  3870. }
  3871. if (DS.isModulePrivateSpecified() &&
  3872. Tag && Tag->getDeclContext()->isFunctionOrMethod())
  3873. Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
  3874. << Tag->getTagKind()
  3875. << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
  3876. ActOnDocumentableDecl(TagD);
  3877. // C 6.7/2:
  3878. // A declaration [...] shall declare at least a declarator [...], a tag,
  3879. // or the members of an enumeration.
  3880. // C++ [dcl.dcl]p3:
  3881. // [If there are no declarators], and except for the declaration of an
  3882. // unnamed bit-field, the decl-specifier-seq shall introduce one or more
  3883. // names into the program, or shall redeclare a name introduced by a
  3884. // previous declaration.
  3885. if (!DeclaresAnything) {
  3886. // In C, we allow this as a (popular) extension / bug. Don't bother
  3887. // producing further diagnostics for redundant qualifiers after this.
  3888. Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
  3889. return TagD;
  3890. }
  3891. // C++ [dcl.stc]p1:
  3892. // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
  3893. // init-declarator-list of the declaration shall not be empty.
  3894. // C++ [dcl.fct.spec]p1:
  3895. // If a cv-qualifier appears in a decl-specifier-seq, the
  3896. // init-declarator-list of the declaration shall not be empty.
  3897. //
  3898. // Spurious qualifiers here appear to be valid in C.
  3899. unsigned DiagID = diag::warn_standalone_specifier;
  3900. if (getLangOpts().CPlusPlus)
  3901. DiagID = diag::ext_standalone_specifier;
  3902. // Note that a linkage-specification sets a storage class, but
  3903. // 'extern "C" struct foo;' is actually valid and not theoretically
  3904. // useless.
  3905. if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
  3906. if (SCS == DeclSpec::SCS_mutable)
  3907. // Since mutable is not a viable storage class specifier in C, there is
  3908. // no reason to treat it as an extension. Instead, diagnose as an error.
  3909. Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
  3910. else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
  3911. Diag(DS.getStorageClassSpecLoc(), DiagID)
  3912. << DeclSpec::getSpecifierName(SCS);
  3913. }
  3914. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  3915. Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
  3916. << DeclSpec::getSpecifierName(TSCS);
  3917. if (DS.getTypeQualifiers()) {
  3918. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  3919. Diag(DS.getConstSpecLoc(), DiagID) << "const";
  3920. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  3921. Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
  3922. // Restrict is covered above.
  3923. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  3924. Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
  3925. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  3926. Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
  3927. }
  3928. // Warn about ignored type attributes, for example:
  3929. // __attribute__((aligned)) struct A;
  3930. // Attributes should be placed after tag to apply to type declaration.
  3931. if (!DS.getAttributes().empty()) {
  3932. DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
  3933. if (TypeSpecType == DeclSpec::TST_class ||
  3934. TypeSpecType == DeclSpec::TST_struct ||
  3935. TypeSpecType == DeclSpec::TST_interface ||
  3936. TypeSpecType == DeclSpec::TST_union ||
  3937. TypeSpecType == DeclSpec::TST_enum) {
  3938. for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
  3939. attrs = attrs->getNext())
  3940. Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
  3941. << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
  3942. }
  3943. }
  3944. return TagD;
  3945. }
  3946. /// We are trying to inject an anonymous member into the given scope;
  3947. /// check if there's an existing declaration that can't be overloaded.
  3948. ///
  3949. /// \return true if this is a forbidden redeclaration
  3950. static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
  3951. Scope *S,
  3952. DeclContext *Owner,
  3953. DeclarationName Name,
  3954. SourceLocation NameLoc,
  3955. bool IsUnion) {
  3956. LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
  3957. Sema::ForVisibleRedeclaration);
  3958. if (!SemaRef.LookupName(R, S)) return false;
  3959. // Pick a representative declaration.
  3960. NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
  3961. assert(PrevDecl && "Expected a non-null Decl");
  3962. if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
  3963. return false;
  3964. SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
  3965. << IsUnion << Name;
  3966. SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  3967. return true;
  3968. }
  3969. /// InjectAnonymousStructOrUnionMembers - Inject the members of the
  3970. /// anonymous struct or union AnonRecord into the owning context Owner
  3971. /// and scope S. This routine will be invoked just after we realize
  3972. /// that an unnamed union or struct is actually an anonymous union or
  3973. /// struct, e.g.,
  3974. ///
  3975. /// @code
  3976. /// union {
  3977. /// int i;
  3978. /// float f;
  3979. /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
  3980. /// // f into the surrounding scope.x
  3981. /// @endcode
  3982. ///
  3983. /// This routine is recursive, injecting the names of nested anonymous
  3984. /// structs/unions into the owning context and scope as well.
  3985. static bool
  3986. InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
  3987. RecordDecl *AnonRecord, AccessSpecifier AS,
  3988. SmallVectorImpl<NamedDecl *> &Chaining) {
  3989. bool Invalid = false;
  3990. // Look every FieldDecl and IndirectFieldDecl with a name.
  3991. for (auto *D : AnonRecord->decls()) {
  3992. if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
  3993. cast<NamedDecl>(D)->getDeclName()) {
  3994. ValueDecl *VD = cast<ValueDecl>(D);
  3995. if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
  3996. VD->getLocation(),
  3997. AnonRecord->isUnion())) {
  3998. // C++ [class.union]p2:
  3999. // The names of the members of an anonymous union shall be
  4000. // distinct from the names of any other entity in the
  4001. // scope in which the anonymous union is declared.
  4002. Invalid = true;
  4003. } else {
  4004. // C++ [class.union]p2:
  4005. // For the purpose of name lookup, after the anonymous union
  4006. // definition, the members of the anonymous union are
  4007. // considered to have been defined in the scope in which the
  4008. // anonymous union is declared.
  4009. unsigned OldChainingSize = Chaining.size();
  4010. if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
  4011. Chaining.append(IF->chain_begin(), IF->chain_end());
  4012. else
  4013. Chaining.push_back(VD);
  4014. assert(Chaining.size() >= 2);
  4015. NamedDecl **NamedChain =
  4016. new (SemaRef.Context)NamedDecl*[Chaining.size()];
  4017. for (unsigned i = 0; i < Chaining.size(); i++)
  4018. NamedChain[i] = Chaining[i];
  4019. IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
  4020. SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
  4021. VD->getType(), {NamedChain, Chaining.size()});
  4022. for (const auto *Attr : VD->attrs())
  4023. IndirectField->addAttr(Attr->clone(SemaRef.Context));
  4024. IndirectField->setAccess(AS);
  4025. IndirectField->setImplicit();
  4026. SemaRef.PushOnScopeChains(IndirectField, S);
  4027. // That includes picking up the appropriate access specifier.
  4028. if (AS != AS_none) IndirectField->setAccess(AS);
  4029. Chaining.resize(OldChainingSize);
  4030. }
  4031. }
  4032. }
  4033. return Invalid;
  4034. }
  4035. /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
  4036. /// a VarDecl::StorageClass. Any error reporting is up to the caller:
  4037. /// illegal input values are mapped to SC_None.
  4038. static StorageClass
  4039. StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
  4040. DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
  4041. assert(StorageClassSpec != DeclSpec::SCS_typedef &&
  4042. "Parser allowed 'typedef' as storage class VarDecl.");
  4043. switch (StorageClassSpec) {
  4044. case DeclSpec::SCS_unspecified: return SC_None;
  4045. case DeclSpec::SCS_extern:
  4046. if (DS.isExternInLinkageSpec())
  4047. return SC_None;
  4048. return SC_Extern;
  4049. case DeclSpec::SCS_static: return SC_Static;
  4050. case DeclSpec::SCS_auto: return SC_Auto;
  4051. case DeclSpec::SCS_register: return SC_Register;
  4052. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  4053. // Illegal SCSs map to None: error reporting is up to the caller.
  4054. case DeclSpec::SCS_mutable: // Fall through.
  4055. case DeclSpec::SCS_typedef: return SC_None;
  4056. }
  4057. llvm_unreachable("unknown storage class specifier");
  4058. }
  4059. static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
  4060. assert(Record->hasInClassInitializer());
  4061. for (const auto *I : Record->decls()) {
  4062. const auto *FD = dyn_cast<FieldDecl>(I);
  4063. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  4064. FD = IFD->getAnonField();
  4065. if (FD && FD->hasInClassInitializer())
  4066. return FD->getLocation();
  4067. }
  4068. llvm_unreachable("couldn't find in-class initializer");
  4069. }
  4070. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4071. SourceLocation DefaultInitLoc) {
  4072. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4073. return;
  4074. S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
  4075. S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
  4076. }
  4077. static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
  4078. CXXRecordDecl *AnonUnion) {
  4079. if (!Parent->isUnion() || !Parent->hasInClassInitializer())
  4080. return;
  4081. checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
  4082. }
  4083. /// BuildAnonymousStructOrUnion - Handle the declaration of an
  4084. /// anonymous structure or union. Anonymous unions are a C++ feature
  4085. /// (C++ [class.union]) and a C11 feature; anonymous structures
  4086. /// are a C11 feature and GNU C++ extension.
  4087. Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
  4088. AccessSpecifier AS,
  4089. RecordDecl *Record,
  4090. const PrintingPolicy &Policy) {
  4091. DeclContext *Owner = Record->getDeclContext();
  4092. // Diagnose whether this anonymous struct/union is an extension.
  4093. if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
  4094. Diag(Record->getLocation(), diag::ext_anonymous_union);
  4095. else if (!Record->isUnion() && getLangOpts().CPlusPlus)
  4096. Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
  4097. else if (!Record->isUnion() && !getLangOpts().C11)
  4098. Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
  4099. // C and C++ require different kinds of checks for anonymous
  4100. // structs/unions.
  4101. bool Invalid = false;
  4102. if (getLangOpts().CPlusPlus) {
  4103. const char *PrevSpec = nullptr;
  4104. unsigned DiagID;
  4105. if (Record->isUnion()) {
  4106. // C++ [class.union]p6:
  4107. // Anonymous unions declared in a named namespace or in the
  4108. // global namespace shall be declared static.
  4109. if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
  4110. (isa<TranslationUnitDecl>(Owner) ||
  4111. (isa<NamespaceDecl>(Owner) &&
  4112. cast<NamespaceDecl>(Owner)->getDeclName()))) {
  4113. Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
  4114. << FixItHint::CreateInsertion(Record->getLocation(), "static ");
  4115. // Recover by adding 'static'.
  4116. DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
  4117. PrevSpec, DiagID, Policy);
  4118. }
  4119. // C++ [class.union]p6:
  4120. // A storage class is not allowed in a declaration of an
  4121. // anonymous union in a class scope.
  4122. else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
  4123. isa<RecordDecl>(Owner)) {
  4124. Diag(DS.getStorageClassSpecLoc(),
  4125. diag::err_anonymous_union_with_storage_spec)
  4126. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  4127. // Recover by removing the storage specifier.
  4128. DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
  4129. SourceLocation(),
  4130. PrevSpec, DiagID, Context.getPrintingPolicy());
  4131. }
  4132. }
  4133. // Ignore const/volatile/restrict qualifiers.
  4134. if (DS.getTypeQualifiers()) {
  4135. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  4136. Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
  4137. << Record->isUnion() << "const"
  4138. << FixItHint::CreateRemoval(DS.getConstSpecLoc());
  4139. if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
  4140. Diag(DS.getVolatileSpecLoc(),
  4141. diag::ext_anonymous_struct_union_qualified)
  4142. << Record->isUnion() << "volatile"
  4143. << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
  4144. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  4145. Diag(DS.getRestrictSpecLoc(),
  4146. diag::ext_anonymous_struct_union_qualified)
  4147. << Record->isUnion() << "restrict"
  4148. << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
  4149. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  4150. Diag(DS.getAtomicSpecLoc(),
  4151. diag::ext_anonymous_struct_union_qualified)
  4152. << Record->isUnion() << "_Atomic"
  4153. << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
  4154. if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
  4155. Diag(DS.getUnalignedSpecLoc(),
  4156. diag::ext_anonymous_struct_union_qualified)
  4157. << Record->isUnion() << "__unaligned"
  4158. << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
  4159. DS.ClearTypeQualifiers();
  4160. }
  4161. // C++ [class.union]p2:
  4162. // The member-specification of an anonymous union shall only
  4163. // define non-static data members. [Note: nested types and
  4164. // functions cannot be declared within an anonymous union. ]
  4165. for (auto *Mem : Record->decls()) {
  4166. if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
  4167. // C++ [class.union]p3:
  4168. // An anonymous union shall not have private or protected
  4169. // members (clause 11).
  4170. assert(FD->getAccess() != AS_none);
  4171. if (FD->getAccess() != AS_public) {
  4172. Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
  4173. << Record->isUnion() << (FD->getAccess() == AS_protected);
  4174. Invalid = true;
  4175. }
  4176. // C++ [class.union]p1
  4177. // An object of a class with a non-trivial constructor, a non-trivial
  4178. // copy constructor, a non-trivial destructor, or a non-trivial copy
  4179. // assignment operator cannot be a member of a union, nor can an
  4180. // array of such objects.
  4181. if (CheckNontrivialField(FD))
  4182. Invalid = true;
  4183. } else if (Mem->isImplicit()) {
  4184. // Any implicit members are fine.
  4185. } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
  4186. // This is a type that showed up in an
  4187. // elaborated-type-specifier inside the anonymous struct or
  4188. // union, but which actually declares a type outside of the
  4189. // anonymous struct or union. It's okay.
  4190. } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
  4191. if (!MemRecord->isAnonymousStructOrUnion() &&
  4192. MemRecord->getDeclName()) {
  4193. // Visual C++ allows type definition in anonymous struct or union.
  4194. if (getLangOpts().MicrosoftExt)
  4195. Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
  4196. << Record->isUnion();
  4197. else {
  4198. // This is a nested type declaration.
  4199. Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
  4200. << Record->isUnion();
  4201. Invalid = true;
  4202. }
  4203. } else {
  4204. // This is an anonymous type definition within another anonymous type.
  4205. // This is a popular extension, provided by Plan9, MSVC and GCC, but
  4206. // not part of standard C++.
  4207. Diag(MemRecord->getLocation(),
  4208. diag::ext_anonymous_record_with_anonymous_type)
  4209. << Record->isUnion();
  4210. }
  4211. } else if (isa<AccessSpecDecl>(Mem)) {
  4212. // Any access specifier is fine.
  4213. } else if (isa<StaticAssertDecl>(Mem)) {
  4214. // In C++1z, static_assert declarations are also fine.
  4215. } else {
  4216. // We have something that isn't a non-static data
  4217. // member. Complain about it.
  4218. unsigned DK = diag::err_anonymous_record_bad_member;
  4219. if (isa<TypeDecl>(Mem))
  4220. DK = diag::err_anonymous_record_with_type;
  4221. else if (isa<FunctionDecl>(Mem))
  4222. DK = diag::err_anonymous_record_with_function;
  4223. else if (isa<VarDecl>(Mem))
  4224. DK = diag::err_anonymous_record_with_static;
  4225. // Visual C++ allows type definition in anonymous struct or union.
  4226. if (getLangOpts().MicrosoftExt &&
  4227. DK == diag::err_anonymous_record_with_type)
  4228. Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
  4229. << Record->isUnion();
  4230. else {
  4231. Diag(Mem->getLocation(), DK) << Record->isUnion();
  4232. Invalid = true;
  4233. }
  4234. }
  4235. }
  4236. // C++11 [class.union]p8 (DR1460):
  4237. // At most one variant member of a union may have a
  4238. // brace-or-equal-initializer.
  4239. if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
  4240. Owner->isRecord())
  4241. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
  4242. cast<CXXRecordDecl>(Record));
  4243. }
  4244. if (!Record->isUnion() && !Owner->isRecord()) {
  4245. Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
  4246. << getLangOpts().CPlusPlus;
  4247. Invalid = true;
  4248. }
  4249. // Mock up a declarator.
  4250. Declarator Dc(DS, DeclaratorContext::MemberContext);
  4251. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4252. assert(TInfo && "couldn't build declarator info for anonymous struct/union");
  4253. // Create a declaration for this anonymous struct/union.
  4254. NamedDecl *Anon = nullptr;
  4255. if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
  4256. Anon = FieldDecl::Create(Context, OwningClass,
  4257. DS.getLocStart(),
  4258. Record->getLocation(),
  4259. /*IdentifierInfo=*/nullptr,
  4260. Context.getTypeDeclType(Record),
  4261. TInfo,
  4262. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4263. /*InitStyle=*/ICIS_NoInit);
  4264. Anon->setAccess(AS);
  4265. if (getLangOpts().CPlusPlus)
  4266. FieldCollector->Add(cast<FieldDecl>(Anon));
  4267. } else {
  4268. DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
  4269. StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
  4270. if (SCSpec == DeclSpec::SCS_mutable) {
  4271. // mutable can only appear on non-static class members, so it's always
  4272. // an error here
  4273. Diag(Record->getLocation(), diag::err_mutable_nonmember);
  4274. Invalid = true;
  4275. SC = SC_None;
  4276. }
  4277. Anon = VarDecl::Create(Context, Owner,
  4278. DS.getLocStart(),
  4279. Record->getLocation(), /*IdentifierInfo=*/nullptr,
  4280. Context.getTypeDeclType(Record),
  4281. TInfo, SC);
  4282. // Default-initialize the implicit variable. This initialization will be
  4283. // trivial in almost all cases, except if a union member has an in-class
  4284. // initializer:
  4285. // union { int n = 0; };
  4286. ActOnUninitializedDecl(Anon);
  4287. }
  4288. Anon->setImplicit();
  4289. // Mark this as an anonymous struct/union type.
  4290. Record->setAnonymousStructOrUnion(true);
  4291. // Add the anonymous struct/union object to the current
  4292. // context. We'll be referencing this object when we refer to one of
  4293. // its members.
  4294. Owner->addDecl(Anon);
  4295. // Inject the members of the anonymous struct/union into the owning
  4296. // context and into the identifier resolver chain for name lookup
  4297. // purposes.
  4298. SmallVector<NamedDecl*, 2> Chain;
  4299. Chain.push_back(Anon);
  4300. if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
  4301. Invalid = true;
  4302. if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
  4303. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  4304. Decl *ManglingContextDecl;
  4305. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  4306. NewVD->getDeclContext(), ManglingContextDecl)) {
  4307. Context.setManglingNumber(
  4308. NewVD, MCtx->getManglingNumber(
  4309. NewVD, getMSManglingNumber(getLangOpts(), S)));
  4310. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  4311. }
  4312. }
  4313. }
  4314. if (Invalid)
  4315. Anon->setInvalidDecl();
  4316. return Anon;
  4317. }
  4318. /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
  4319. /// Microsoft C anonymous structure.
  4320. /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
  4321. /// Example:
  4322. ///
  4323. /// struct A { int a; };
  4324. /// struct B { struct A; int b; };
  4325. ///
  4326. /// void foo() {
  4327. /// B var;
  4328. /// var.a = 3;
  4329. /// }
  4330. ///
  4331. Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
  4332. RecordDecl *Record) {
  4333. assert(Record && "expected a record!");
  4334. // Mock up a declarator.
  4335. Declarator Dc(DS, DeclaratorContext::TypeNameContext);
  4336. TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
  4337. assert(TInfo && "couldn't build declarator info for anonymous struct");
  4338. auto *ParentDecl = cast<RecordDecl>(CurContext);
  4339. QualType RecTy = Context.getTypeDeclType(Record);
  4340. // Create a declaration for this anonymous struct.
  4341. NamedDecl *Anon = FieldDecl::Create(Context,
  4342. ParentDecl,
  4343. DS.getLocStart(),
  4344. DS.getLocStart(),
  4345. /*IdentifierInfo=*/nullptr,
  4346. RecTy,
  4347. TInfo,
  4348. /*BitWidth=*/nullptr, /*Mutable=*/false,
  4349. /*InitStyle=*/ICIS_NoInit);
  4350. Anon->setImplicit();
  4351. // Add the anonymous struct object to the current context.
  4352. CurContext->addDecl(Anon);
  4353. // Inject the members of the anonymous struct into the current
  4354. // context and into the identifier resolver chain for name lookup
  4355. // purposes.
  4356. SmallVector<NamedDecl*, 2> Chain;
  4357. Chain.push_back(Anon);
  4358. RecordDecl *RecordDef = Record->getDefinition();
  4359. if (RequireCompleteType(Anon->getLocation(), RecTy,
  4360. diag::err_field_incomplete) ||
  4361. InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
  4362. AS_none, Chain)) {
  4363. Anon->setInvalidDecl();
  4364. ParentDecl->setInvalidDecl();
  4365. }
  4366. return Anon;
  4367. }
  4368. /// GetNameForDeclarator - Determine the full declaration name for the
  4369. /// given Declarator.
  4370. DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
  4371. return GetNameFromUnqualifiedId(D.getName());
  4372. }
  4373. /// Retrieves the declaration name from a parsed unqualified-id.
  4374. DeclarationNameInfo
  4375. Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
  4376. DeclarationNameInfo NameInfo;
  4377. NameInfo.setLoc(Name.StartLocation);
  4378. switch (Name.getKind()) {
  4379. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  4380. case UnqualifiedIdKind::IK_Identifier:
  4381. NameInfo.setName(Name.Identifier);
  4382. NameInfo.setLoc(Name.StartLocation);
  4383. return NameInfo;
  4384. case UnqualifiedIdKind::IK_DeductionGuideName: {
  4385. // C++ [temp.deduct.guide]p3:
  4386. // The simple-template-id shall name a class template specialization.
  4387. // The template-name shall be the same identifier as the template-name
  4388. // of the simple-template-id.
  4389. // These together intend to imply that the template-name shall name a
  4390. // class template.
  4391. // FIXME: template<typename T> struct X {};
  4392. // template<typename T> using Y = X<T>;
  4393. // Y(int) -> Y<int>;
  4394. // satisfies these rules but does not name a class template.
  4395. TemplateName TN = Name.TemplateName.get().get();
  4396. auto *Template = TN.getAsTemplateDecl();
  4397. if (!Template || !isa<ClassTemplateDecl>(Template)) {
  4398. Diag(Name.StartLocation,
  4399. diag::err_deduction_guide_name_not_class_template)
  4400. << (int)getTemplateNameKindForDiagnostics(TN) << TN;
  4401. if (Template)
  4402. Diag(Template->getLocation(), diag::note_template_decl_here);
  4403. return DeclarationNameInfo();
  4404. }
  4405. NameInfo.setName(
  4406. Context.DeclarationNames.getCXXDeductionGuideName(Template));
  4407. NameInfo.setLoc(Name.StartLocation);
  4408. return NameInfo;
  4409. }
  4410. case UnqualifiedIdKind::IK_OperatorFunctionId:
  4411. NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
  4412. Name.OperatorFunctionId.Operator));
  4413. NameInfo.setLoc(Name.StartLocation);
  4414. NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
  4415. = Name.OperatorFunctionId.SymbolLocations[0];
  4416. NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
  4417. = Name.EndLocation.getRawEncoding();
  4418. return NameInfo;
  4419. case UnqualifiedIdKind::IK_LiteralOperatorId:
  4420. NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
  4421. Name.Identifier));
  4422. NameInfo.setLoc(Name.StartLocation);
  4423. NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
  4424. return NameInfo;
  4425. case UnqualifiedIdKind::IK_ConversionFunctionId: {
  4426. TypeSourceInfo *TInfo;
  4427. QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
  4428. if (Ty.isNull())
  4429. return DeclarationNameInfo();
  4430. NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
  4431. Context.getCanonicalType(Ty)));
  4432. NameInfo.setLoc(Name.StartLocation);
  4433. NameInfo.setNamedTypeInfo(TInfo);
  4434. return NameInfo;
  4435. }
  4436. case UnqualifiedIdKind::IK_ConstructorName: {
  4437. TypeSourceInfo *TInfo;
  4438. QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
  4439. if (Ty.isNull())
  4440. return DeclarationNameInfo();
  4441. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4442. Context.getCanonicalType(Ty)));
  4443. NameInfo.setLoc(Name.StartLocation);
  4444. NameInfo.setNamedTypeInfo(TInfo);
  4445. return NameInfo;
  4446. }
  4447. case UnqualifiedIdKind::IK_ConstructorTemplateId: {
  4448. // In well-formed code, we can only have a constructor
  4449. // template-id that refers to the current context, so go there
  4450. // to find the actual type being constructed.
  4451. CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
  4452. if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
  4453. return DeclarationNameInfo();
  4454. // Determine the type of the class being constructed.
  4455. QualType CurClassType = Context.getTypeDeclType(CurClass);
  4456. // FIXME: Check two things: that the template-id names the same type as
  4457. // CurClassType, and that the template-id does not occur when the name
  4458. // was qualified.
  4459. NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
  4460. Context.getCanonicalType(CurClassType)));
  4461. NameInfo.setLoc(Name.StartLocation);
  4462. // FIXME: should we retrieve TypeSourceInfo?
  4463. NameInfo.setNamedTypeInfo(nullptr);
  4464. return NameInfo;
  4465. }
  4466. case UnqualifiedIdKind::IK_DestructorName: {
  4467. TypeSourceInfo *TInfo;
  4468. QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
  4469. if (Ty.isNull())
  4470. return DeclarationNameInfo();
  4471. NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
  4472. Context.getCanonicalType(Ty)));
  4473. NameInfo.setLoc(Name.StartLocation);
  4474. NameInfo.setNamedTypeInfo(TInfo);
  4475. return NameInfo;
  4476. }
  4477. case UnqualifiedIdKind::IK_TemplateId: {
  4478. TemplateName TName = Name.TemplateId->Template.get();
  4479. SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
  4480. return Context.getNameForTemplate(TName, TNameLoc);
  4481. }
  4482. } // switch (Name.getKind())
  4483. llvm_unreachable("Unknown name kind");
  4484. }
  4485. static QualType getCoreType(QualType Ty) {
  4486. do {
  4487. if (Ty->isPointerType() || Ty->isReferenceType())
  4488. Ty = Ty->getPointeeType();
  4489. else if (Ty->isArrayType())
  4490. Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
  4491. else
  4492. return Ty.withoutLocalFastQualifiers();
  4493. } while (true);
  4494. }
  4495. /// hasSimilarParameters - Determine whether the C++ functions Declaration
  4496. /// and Definition have "nearly" matching parameters. This heuristic is
  4497. /// used to improve diagnostics in the case where an out-of-line function
  4498. /// definition doesn't match any declaration within the class or namespace.
  4499. /// Also sets Params to the list of indices to the parameters that differ
  4500. /// between the declaration and the definition. If hasSimilarParameters
  4501. /// returns true and Params is empty, then all of the parameters match.
  4502. static bool hasSimilarParameters(ASTContext &Context,
  4503. FunctionDecl *Declaration,
  4504. FunctionDecl *Definition,
  4505. SmallVectorImpl<unsigned> &Params) {
  4506. Params.clear();
  4507. if (Declaration->param_size() != Definition->param_size())
  4508. return false;
  4509. for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
  4510. QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
  4511. QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
  4512. // The parameter types are identical
  4513. if (Context.hasSameType(DefParamTy, DeclParamTy))
  4514. continue;
  4515. QualType DeclParamBaseTy = getCoreType(DeclParamTy);
  4516. QualType DefParamBaseTy = getCoreType(DefParamTy);
  4517. const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
  4518. const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
  4519. if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
  4520. (DeclTyName && DeclTyName == DefTyName))
  4521. Params.push_back(Idx);
  4522. else // The two parameters aren't even close
  4523. return false;
  4524. }
  4525. return true;
  4526. }
  4527. /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
  4528. /// declarator needs to be rebuilt in the current instantiation.
  4529. /// Any bits of declarator which appear before the name are valid for
  4530. /// consideration here. That's specifically the type in the decl spec
  4531. /// and the base type in any member-pointer chunks.
  4532. static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
  4533. DeclarationName Name) {
  4534. // The types we specifically need to rebuild are:
  4535. // - typenames, typeofs, and decltypes
  4536. // - types which will become injected class names
  4537. // Of course, we also need to rebuild any type referencing such a
  4538. // type. It's safest to just say "dependent", but we call out a
  4539. // few cases here.
  4540. DeclSpec &DS = D.getMutableDeclSpec();
  4541. switch (DS.getTypeSpecType()) {
  4542. case DeclSpec::TST_typename:
  4543. case DeclSpec::TST_typeofType:
  4544. case DeclSpec::TST_underlyingType:
  4545. case DeclSpec::TST_atomic: {
  4546. // Grab the type from the parser.
  4547. TypeSourceInfo *TSI = nullptr;
  4548. QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
  4549. if (T.isNull() || !T->isDependentType()) break;
  4550. // Make sure there's a type source info. This isn't really much
  4551. // of a waste; most dependent types should have type source info
  4552. // attached already.
  4553. if (!TSI)
  4554. TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
  4555. // Rebuild the type in the current instantiation.
  4556. TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
  4557. if (!TSI) return true;
  4558. // Store the new type back in the decl spec.
  4559. ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
  4560. DS.UpdateTypeRep(LocType);
  4561. break;
  4562. }
  4563. case DeclSpec::TST_decltype:
  4564. case DeclSpec::TST_typeofExpr: {
  4565. Expr *E = DS.getRepAsExpr();
  4566. ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
  4567. if (Result.isInvalid()) return true;
  4568. DS.UpdateExprRep(Result.get());
  4569. break;
  4570. }
  4571. default:
  4572. // Nothing to do for these decl specs.
  4573. break;
  4574. }
  4575. // It doesn't matter what order we do this in.
  4576. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  4577. DeclaratorChunk &Chunk = D.getTypeObject(I);
  4578. // The only type information in the declarator which can come
  4579. // before the declaration name is the base type of a member
  4580. // pointer.
  4581. if (Chunk.Kind != DeclaratorChunk::MemberPointer)
  4582. continue;
  4583. // Rebuild the scope specifier in-place.
  4584. CXXScopeSpec &SS = Chunk.Mem.Scope();
  4585. if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
  4586. return true;
  4587. }
  4588. return false;
  4589. }
  4590. Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
  4591. D.setFunctionDefinitionKind(FDK_Declaration);
  4592. Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
  4593. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
  4594. Dcl && Dcl->getDeclContext()->isFileContext())
  4595. Dcl->setTopLevelDeclInObjCContainer();
  4596. if (getLangOpts().OpenCL)
  4597. setCurrentOpenCLExtensionForDecl(Dcl);
  4598. return Dcl;
  4599. }
  4600. /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
  4601. /// If T is the name of a class, then each of the following shall have a
  4602. /// name different from T:
  4603. /// - every static data member of class T;
  4604. /// - every member function of class T
  4605. /// - every member of class T that is itself a type;
  4606. /// \returns true if the declaration name violates these rules.
  4607. bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
  4608. DeclarationNameInfo NameInfo) {
  4609. DeclarationName Name = NameInfo.getName();
  4610. CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
  4611. while (Record && Record->isAnonymousStructOrUnion())
  4612. Record = dyn_cast<CXXRecordDecl>(Record->getParent());
  4613. if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
  4614. Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
  4615. return true;
  4616. }
  4617. return false;
  4618. }
  4619. /// Diagnose a declaration whose declarator-id has the given
  4620. /// nested-name-specifier.
  4621. ///
  4622. /// \param SS The nested-name-specifier of the declarator-id.
  4623. ///
  4624. /// \param DC The declaration context to which the nested-name-specifier
  4625. /// resolves.
  4626. ///
  4627. /// \param Name The name of the entity being declared.
  4628. ///
  4629. /// \param Loc The location of the name of the entity being declared.
  4630. ///
  4631. /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
  4632. /// we're declaring an explicit / partial specialization / instantiation.
  4633. ///
  4634. /// \returns true if we cannot safely recover from this error, false otherwise.
  4635. bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
  4636. DeclarationName Name,
  4637. SourceLocation Loc, bool IsTemplateId) {
  4638. DeclContext *Cur = CurContext;
  4639. while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
  4640. Cur = Cur->getParent();
  4641. // If the user provided a superfluous scope specifier that refers back to the
  4642. // class in which the entity is already declared, diagnose and ignore it.
  4643. //
  4644. // class X {
  4645. // void X::f();
  4646. // };
  4647. //
  4648. // Note, it was once ill-formed to give redundant qualification in all
  4649. // contexts, but that rule was removed by DR482.
  4650. if (Cur->Equals(DC)) {
  4651. if (Cur->isRecord()) {
  4652. Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
  4653. : diag::err_member_extra_qualification)
  4654. << Name << FixItHint::CreateRemoval(SS.getRange());
  4655. SS.clear();
  4656. } else {
  4657. Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
  4658. }
  4659. return false;
  4660. }
  4661. // Check whether the qualifying scope encloses the scope of the original
  4662. // declaration. For a template-id, we perform the checks in
  4663. // CheckTemplateSpecializationScope.
  4664. if (!Cur->Encloses(DC) && !IsTemplateId) {
  4665. if (Cur->isRecord())
  4666. Diag(Loc, diag::err_member_qualification)
  4667. << Name << SS.getRange();
  4668. else if (isa<TranslationUnitDecl>(DC))
  4669. Diag(Loc, diag::err_invalid_declarator_global_scope)
  4670. << Name << SS.getRange();
  4671. else if (isa<FunctionDecl>(Cur))
  4672. Diag(Loc, diag::err_invalid_declarator_in_function)
  4673. << Name << SS.getRange();
  4674. else if (isa<BlockDecl>(Cur))
  4675. Diag(Loc, diag::err_invalid_declarator_in_block)
  4676. << Name << SS.getRange();
  4677. else
  4678. Diag(Loc, diag::err_invalid_declarator_scope)
  4679. << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
  4680. return true;
  4681. }
  4682. if (Cur->isRecord()) {
  4683. // Cannot qualify members within a class.
  4684. Diag(Loc, diag::err_member_qualification)
  4685. << Name << SS.getRange();
  4686. SS.clear();
  4687. // C++ constructors and destructors with incorrect scopes can break
  4688. // our AST invariants by having the wrong underlying types. If
  4689. // that's the case, then drop this declaration entirely.
  4690. if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
  4691. Name.getNameKind() == DeclarationName::CXXDestructorName) &&
  4692. !Context.hasSameType(Name.getCXXNameType(),
  4693. Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
  4694. return true;
  4695. return false;
  4696. }
  4697. // C++11 [dcl.meaning]p1:
  4698. // [...] "The nested-name-specifier of the qualified declarator-id shall
  4699. // not begin with a decltype-specifer"
  4700. NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
  4701. while (SpecLoc.getPrefix())
  4702. SpecLoc = SpecLoc.getPrefix();
  4703. if (dyn_cast_or_null<DecltypeType>(
  4704. SpecLoc.getNestedNameSpecifier()->getAsType()))
  4705. Diag(Loc, diag::err_decltype_in_declarator)
  4706. << SpecLoc.getTypeLoc().getSourceRange();
  4707. return false;
  4708. }
  4709. NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
  4710. MultiTemplateParamsArg TemplateParamLists) {
  4711. // TODO: consider using NameInfo for diagnostic.
  4712. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  4713. DeclarationName Name = NameInfo.getName();
  4714. // All of these full declarators require an identifier. If it doesn't have
  4715. // one, the ParsedFreeStandingDeclSpec action should be used.
  4716. if (D.isDecompositionDeclarator()) {
  4717. return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
  4718. } else if (!Name) {
  4719. if (!D.isInvalidType()) // Reject this if we think it is valid.
  4720. Diag(D.getDeclSpec().getLocStart(),
  4721. diag::err_declarator_need_ident)
  4722. << D.getDeclSpec().getSourceRange() << D.getSourceRange();
  4723. return nullptr;
  4724. } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
  4725. return nullptr;
  4726. // The scope passed in may not be a decl scope. Zip up the scope tree until
  4727. // we find one that is.
  4728. while ((S->getFlags() & Scope::DeclScope) == 0 ||
  4729. (S->getFlags() & Scope::TemplateParamScope) != 0)
  4730. S = S->getParent();
  4731. DeclContext *DC = CurContext;
  4732. if (D.getCXXScopeSpec().isInvalid())
  4733. D.setInvalidType();
  4734. else if (D.getCXXScopeSpec().isSet()) {
  4735. if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
  4736. UPPC_DeclarationQualifier))
  4737. return nullptr;
  4738. bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
  4739. DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
  4740. if (!DC || isa<EnumDecl>(DC)) {
  4741. // If we could not compute the declaration context, it's because the
  4742. // declaration context is dependent but does not refer to a class,
  4743. // class template, or class template partial specialization. Complain
  4744. // and return early, to avoid the coming semantic disaster.
  4745. Diag(D.getIdentifierLoc(),
  4746. diag::err_template_qualified_declarator_no_match)
  4747. << D.getCXXScopeSpec().getScopeRep()
  4748. << D.getCXXScopeSpec().getRange();
  4749. return nullptr;
  4750. }
  4751. bool IsDependentContext = DC->isDependentContext();
  4752. if (!IsDependentContext &&
  4753. RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
  4754. return nullptr;
  4755. // If a class is incomplete, do not parse entities inside it.
  4756. if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
  4757. Diag(D.getIdentifierLoc(),
  4758. diag::err_member_def_undefined_record)
  4759. << Name << DC << D.getCXXScopeSpec().getRange();
  4760. return nullptr;
  4761. }
  4762. if (!D.getDeclSpec().isFriendSpecified()) {
  4763. if (diagnoseQualifiedDeclaration(
  4764. D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
  4765. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
  4766. if (DC->isRecord())
  4767. return nullptr;
  4768. D.setInvalidType();
  4769. }
  4770. }
  4771. // Check whether we need to rebuild the type of the given
  4772. // declaration in the current instantiation.
  4773. if (EnteringContext && IsDependentContext &&
  4774. TemplateParamLists.size() != 0) {
  4775. ContextRAII SavedContext(*this, DC);
  4776. if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
  4777. D.setInvalidType();
  4778. }
  4779. }
  4780. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  4781. QualType R = TInfo->getType();
  4782. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  4783. UPPC_DeclarationType))
  4784. D.setInvalidType();
  4785. LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
  4786. forRedeclarationInCurContext());
  4787. // See if this is a redefinition of a variable in the same scope.
  4788. if (!D.getCXXScopeSpec().isSet()) {
  4789. bool IsLinkageLookup = false;
  4790. bool CreateBuiltins = false;
  4791. // If the declaration we're planning to build will be a function
  4792. // or object with linkage, then look for another declaration with
  4793. // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
  4794. //
  4795. // If the declaration we're planning to build will be declared with
  4796. // external linkage in the translation unit, create any builtin with
  4797. // the same name.
  4798. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  4799. /* Do nothing*/;
  4800. else if (CurContext->isFunctionOrMethod() &&
  4801. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
  4802. R->isFunctionType())) {
  4803. IsLinkageLookup = true;
  4804. CreateBuiltins =
  4805. CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
  4806. } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
  4807. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
  4808. CreateBuiltins = true;
  4809. if (IsLinkageLookup) {
  4810. Previous.clear(LookupRedeclarationWithLinkage);
  4811. Previous.setRedeclarationKind(ForExternalRedeclaration);
  4812. }
  4813. LookupName(Previous, S, CreateBuiltins);
  4814. } else { // Something like "int foo::x;"
  4815. LookupQualifiedName(Previous, DC);
  4816. // C++ [dcl.meaning]p1:
  4817. // When the declarator-id is qualified, the declaration shall refer to a
  4818. // previously declared member of the class or namespace to which the
  4819. // qualifier refers (or, in the case of a namespace, of an element of the
  4820. // inline namespace set of that namespace (7.3.1)) or to a specialization
  4821. // thereof; [...]
  4822. //
  4823. // Note that we already checked the context above, and that we do not have
  4824. // enough information to make sure that Previous contains the declaration
  4825. // we want to match. For example, given:
  4826. //
  4827. // class X {
  4828. // void f();
  4829. // void f(float);
  4830. // };
  4831. //
  4832. // void X::f(int) { } // ill-formed
  4833. //
  4834. // In this case, Previous will point to the overload set
  4835. // containing the two f's declared in X, but neither of them
  4836. // matches.
  4837. // C++ [dcl.meaning]p1:
  4838. // [...] the member shall not merely have been introduced by a
  4839. // using-declaration in the scope of the class or namespace nominated by
  4840. // the nested-name-specifier of the declarator-id.
  4841. RemoveUsingDecls(Previous);
  4842. }
  4843. if (Previous.isSingleResult() &&
  4844. Previous.getFoundDecl()->isTemplateParameter()) {
  4845. // Maybe we will complain about the shadowed template parameter.
  4846. if (!D.isInvalidType())
  4847. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
  4848. Previous.getFoundDecl());
  4849. // Just pretend that we didn't see the previous declaration.
  4850. Previous.clear();
  4851. }
  4852. if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
  4853. // Forget that the previous declaration is the injected-class-name.
  4854. Previous.clear();
  4855. // In C++, the previous declaration we find might be a tag type
  4856. // (class or enum). In this case, the new declaration will hide the
  4857. // tag type. Note that this applies to functions, function templates, and
  4858. // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
  4859. if (Previous.isSingleTagDecl() &&
  4860. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  4861. (TemplateParamLists.size() == 0 || R->isFunctionType()))
  4862. Previous.clear();
  4863. // Check that there are no default arguments other than in the parameters
  4864. // of a function declaration (C++ only).
  4865. if (getLangOpts().CPlusPlus)
  4866. CheckExtraCXXDefaultArguments(D);
  4867. NamedDecl *New;
  4868. bool AddToScope = true;
  4869. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
  4870. if (TemplateParamLists.size()) {
  4871. Diag(D.getIdentifierLoc(), diag::err_template_typedef);
  4872. return nullptr;
  4873. }
  4874. New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
  4875. } else if (R->isFunctionType()) {
  4876. New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
  4877. TemplateParamLists,
  4878. AddToScope);
  4879. } else {
  4880. New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
  4881. AddToScope);
  4882. }
  4883. if (!New)
  4884. return nullptr;
  4885. // If this has an identifier and is not a function template specialization,
  4886. // add it to the scope stack.
  4887. if (New->getDeclName() && AddToScope) {
  4888. // Only make a locally-scoped extern declaration visible if it is the first
  4889. // declaration of this entity. Qualified lookup for such an entity should
  4890. // only find this declaration if there is no visible declaration of it.
  4891. bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
  4892. PushOnScopeChains(New, S, AddToContext);
  4893. if (!AddToContext)
  4894. CurContext->addHiddenDecl(New);
  4895. }
  4896. if (isInOpenMPDeclareTargetContext())
  4897. checkDeclIsAllowedInOpenMPTarget(nullptr, New);
  4898. return New;
  4899. }
  4900. /// Helper method to turn variable array types into constant array
  4901. /// types in certain situations which would otherwise be errors (for
  4902. /// GCC compatibility).
  4903. static QualType TryToFixInvalidVariablyModifiedType(QualType T,
  4904. ASTContext &Context,
  4905. bool &SizeIsNegative,
  4906. llvm::APSInt &Oversized) {
  4907. // This method tries to turn a variable array into a constant
  4908. // array even when the size isn't an ICE. This is necessary
  4909. // for compatibility with code that depends on gcc's buggy
  4910. // constant expression folding, like struct {char x[(int)(char*)2];}
  4911. SizeIsNegative = false;
  4912. Oversized = 0;
  4913. if (T->isDependentType())
  4914. return QualType();
  4915. QualifierCollector Qs;
  4916. const Type *Ty = Qs.strip(T);
  4917. if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
  4918. QualType Pointee = PTy->getPointeeType();
  4919. QualType FixedType =
  4920. TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
  4921. Oversized);
  4922. if (FixedType.isNull()) return FixedType;
  4923. FixedType = Context.getPointerType(FixedType);
  4924. return Qs.apply(Context, FixedType);
  4925. }
  4926. if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
  4927. QualType Inner = PTy->getInnerType();
  4928. QualType FixedType =
  4929. TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
  4930. Oversized);
  4931. if (FixedType.isNull()) return FixedType;
  4932. FixedType = Context.getParenType(FixedType);
  4933. return Qs.apply(Context, FixedType);
  4934. }
  4935. const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
  4936. if (!VLATy)
  4937. return QualType();
  4938. // FIXME: We should probably handle this case
  4939. if (VLATy->getElementType()->isVariablyModifiedType())
  4940. return QualType();
  4941. llvm::APSInt Res;
  4942. if (!VLATy->getSizeExpr() ||
  4943. !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
  4944. return QualType();
  4945. // Check whether the array size is negative.
  4946. if (Res.isSigned() && Res.isNegative()) {
  4947. SizeIsNegative = true;
  4948. return QualType();
  4949. }
  4950. // Check whether the array is too large to be addressed.
  4951. unsigned ActiveSizeBits
  4952. = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
  4953. Res);
  4954. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  4955. Oversized = Res;
  4956. return QualType();
  4957. }
  4958. return Context.getConstantArrayType(VLATy->getElementType(),
  4959. Res, ArrayType::Normal, 0);
  4960. }
  4961. static void
  4962. FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
  4963. SrcTL = SrcTL.getUnqualifiedLoc();
  4964. DstTL = DstTL.getUnqualifiedLoc();
  4965. if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
  4966. PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
  4967. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
  4968. DstPTL.getPointeeLoc());
  4969. DstPTL.setStarLoc(SrcPTL.getStarLoc());
  4970. return;
  4971. }
  4972. if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
  4973. ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
  4974. FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
  4975. DstPTL.getInnerLoc());
  4976. DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
  4977. DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
  4978. return;
  4979. }
  4980. ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
  4981. ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
  4982. TypeLoc SrcElemTL = SrcATL.getElementLoc();
  4983. TypeLoc DstElemTL = DstATL.getElementLoc();
  4984. DstElemTL.initializeFullCopy(SrcElemTL);
  4985. DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
  4986. DstATL.setSizeExpr(SrcATL.getSizeExpr());
  4987. DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
  4988. }
  4989. /// Helper method to turn variable array types into constant array
  4990. /// types in certain situations which would otherwise be errors (for
  4991. /// GCC compatibility).
  4992. static TypeSourceInfo*
  4993. TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
  4994. ASTContext &Context,
  4995. bool &SizeIsNegative,
  4996. llvm::APSInt &Oversized) {
  4997. QualType FixedTy
  4998. = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
  4999. SizeIsNegative, Oversized);
  5000. if (FixedTy.isNull())
  5001. return nullptr;
  5002. TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
  5003. FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
  5004. FixedTInfo->getTypeLoc());
  5005. return FixedTInfo;
  5006. }
  5007. /// Register the given locally-scoped extern "C" declaration so
  5008. /// that it can be found later for redeclarations. We include any extern "C"
  5009. /// declaration that is not visible in the translation unit here, not just
  5010. /// function-scope declarations.
  5011. void
  5012. Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
  5013. if (!getLangOpts().CPlusPlus &&
  5014. ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
  5015. // Don't need to track declarations in the TU in C.
  5016. return;
  5017. // Note that we have a locally-scoped external with this name.
  5018. Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
  5019. }
  5020. NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
  5021. // FIXME: We can have multiple results via __attribute__((overloadable)).
  5022. auto Result = Context.getExternCContextDecl()->lookup(Name);
  5023. return Result.empty() ? nullptr : *Result.begin();
  5024. }
  5025. /// Diagnose function specifiers on a declaration of an identifier that
  5026. /// does not identify a function.
  5027. void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
  5028. // FIXME: We should probably indicate the identifier in question to avoid
  5029. // confusion for constructs like "virtual int a(), b;"
  5030. if (DS.isVirtualSpecified())
  5031. Diag(DS.getVirtualSpecLoc(),
  5032. diag::err_virtual_non_function);
  5033. if (DS.isExplicitSpecified())
  5034. Diag(DS.getExplicitSpecLoc(),
  5035. diag::err_explicit_non_function);
  5036. if (DS.isNoreturnSpecified())
  5037. Diag(DS.getNoreturnSpecLoc(),
  5038. diag::err_noreturn_non_function);
  5039. }
  5040. NamedDecl*
  5041. Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
  5042. TypeSourceInfo *TInfo, LookupResult &Previous) {
  5043. // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
  5044. if (D.getCXXScopeSpec().isSet()) {
  5045. Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
  5046. << D.getCXXScopeSpec().getRange();
  5047. D.setInvalidType();
  5048. // Pretend we didn't see the scope specifier.
  5049. DC = CurContext;
  5050. Previous.clear();
  5051. }
  5052. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  5053. if (D.getDeclSpec().isInlineSpecified())
  5054. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5055. << getLangOpts().CPlusPlus17;
  5056. if (D.getDeclSpec().isConstexprSpecified())
  5057. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
  5058. << 1;
  5059. if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
  5060. if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
  5061. Diag(D.getName().StartLocation,
  5062. diag::err_deduction_guide_invalid_specifier)
  5063. << "typedef";
  5064. else
  5065. Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
  5066. << D.getName().getSourceRange();
  5067. return nullptr;
  5068. }
  5069. TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
  5070. if (!NewTD) return nullptr;
  5071. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5072. ProcessDeclAttributes(S, NewTD, D);
  5073. CheckTypedefForVariablyModifiedType(S, NewTD);
  5074. bool Redeclaration = D.isRedeclaration();
  5075. NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
  5076. D.setRedeclaration(Redeclaration);
  5077. return ND;
  5078. }
  5079. void
  5080. Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
  5081. // C99 6.7.7p2: If a typedef name specifies a variably modified type
  5082. // then it shall have block scope.
  5083. // Note that variably modified types must be fixed before merging the decl so
  5084. // that redeclarations will match.
  5085. TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
  5086. QualType T = TInfo->getType();
  5087. if (T->isVariablyModifiedType()) {
  5088. setFunctionHasBranchProtectedScope();
  5089. if (S->getFnParent() == nullptr) {
  5090. bool SizeIsNegative;
  5091. llvm::APSInt Oversized;
  5092. TypeSourceInfo *FixedTInfo =
  5093. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  5094. SizeIsNegative,
  5095. Oversized);
  5096. if (FixedTInfo) {
  5097. Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
  5098. NewTD->setTypeSourceInfo(FixedTInfo);
  5099. } else {
  5100. if (SizeIsNegative)
  5101. Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
  5102. else if (T->isVariableArrayType())
  5103. Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
  5104. else if (Oversized.getBoolValue())
  5105. Diag(NewTD->getLocation(), diag::err_array_too_large)
  5106. << Oversized.toString(10);
  5107. else
  5108. Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
  5109. NewTD->setInvalidDecl();
  5110. }
  5111. }
  5112. }
  5113. }
  5114. /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
  5115. /// declares a typedef-name, either using the 'typedef' type specifier or via
  5116. /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
  5117. NamedDecl*
  5118. Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
  5119. LookupResult &Previous, bool &Redeclaration) {
  5120. // Find the shadowed declaration before filtering for scope.
  5121. NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
  5122. // Merge the decl with the existing one if appropriate. If the decl is
  5123. // in an outer scope, it isn't the same thing.
  5124. FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
  5125. /*AllowInlineNamespace*/false);
  5126. filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
  5127. if (!Previous.empty()) {
  5128. Redeclaration = true;
  5129. MergeTypedefNameDecl(S, NewTD, Previous);
  5130. }
  5131. if (ShadowedDecl && !Redeclaration)
  5132. CheckShadow(NewTD, ShadowedDecl, Previous);
  5133. // If this is the C FILE type, notify the AST context.
  5134. if (IdentifierInfo *II = NewTD->getIdentifier())
  5135. if (!NewTD->isInvalidDecl() &&
  5136. NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  5137. if (II->isStr("FILE"))
  5138. Context.setFILEDecl(NewTD);
  5139. else if (II->isStr("jmp_buf"))
  5140. Context.setjmp_bufDecl(NewTD);
  5141. else if (II->isStr("sigjmp_buf"))
  5142. Context.setsigjmp_bufDecl(NewTD);
  5143. else if (II->isStr("ucontext_t"))
  5144. Context.setucontext_tDecl(NewTD);
  5145. }
  5146. return NewTD;
  5147. }
  5148. /// Determines whether the given declaration is an out-of-scope
  5149. /// previous declaration.
  5150. ///
  5151. /// This routine should be invoked when name lookup has found a
  5152. /// previous declaration (PrevDecl) that is not in the scope where a
  5153. /// new declaration by the same name is being introduced. If the new
  5154. /// declaration occurs in a local scope, previous declarations with
  5155. /// linkage may still be considered previous declarations (C99
  5156. /// 6.2.2p4-5, C++ [basic.link]p6).
  5157. ///
  5158. /// \param PrevDecl the previous declaration found by name
  5159. /// lookup
  5160. ///
  5161. /// \param DC the context in which the new declaration is being
  5162. /// declared.
  5163. ///
  5164. /// \returns true if PrevDecl is an out-of-scope previous declaration
  5165. /// for a new delcaration with the same name.
  5166. static bool
  5167. isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
  5168. ASTContext &Context) {
  5169. if (!PrevDecl)
  5170. return false;
  5171. if (!PrevDecl->hasLinkage())
  5172. return false;
  5173. if (Context.getLangOpts().CPlusPlus) {
  5174. // C++ [basic.link]p6:
  5175. // If there is a visible declaration of an entity with linkage
  5176. // having the same name and type, ignoring entities declared
  5177. // outside the innermost enclosing namespace scope, the block
  5178. // scope declaration declares that same entity and receives the
  5179. // linkage of the previous declaration.
  5180. DeclContext *OuterContext = DC->getRedeclContext();
  5181. if (!OuterContext->isFunctionOrMethod())
  5182. // This rule only applies to block-scope declarations.
  5183. return false;
  5184. DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
  5185. if (PrevOuterContext->isRecord())
  5186. // We found a member function: ignore it.
  5187. return false;
  5188. // Find the innermost enclosing namespace for the new and
  5189. // previous declarations.
  5190. OuterContext = OuterContext->getEnclosingNamespaceContext();
  5191. PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
  5192. // The previous declaration is in a different namespace, so it
  5193. // isn't the same function.
  5194. if (!OuterContext->Equals(PrevOuterContext))
  5195. return false;
  5196. }
  5197. return true;
  5198. }
  5199. static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
  5200. CXXScopeSpec &SS = D.getCXXScopeSpec();
  5201. if (!SS.isSet()) return;
  5202. DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
  5203. }
  5204. bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
  5205. QualType type = decl->getType();
  5206. Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
  5207. if (lifetime == Qualifiers::OCL_Autoreleasing) {
  5208. // Various kinds of declaration aren't allowed to be __autoreleasing.
  5209. unsigned kind = -1U;
  5210. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5211. if (var->hasAttr<BlocksAttr>())
  5212. kind = 0; // __block
  5213. else if (!var->hasLocalStorage())
  5214. kind = 1; // global
  5215. } else if (isa<ObjCIvarDecl>(decl)) {
  5216. kind = 3; // ivar
  5217. } else if (isa<FieldDecl>(decl)) {
  5218. kind = 2; // field
  5219. }
  5220. if (kind != -1U) {
  5221. Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
  5222. << kind;
  5223. }
  5224. } else if (lifetime == Qualifiers::OCL_None) {
  5225. // Try to infer lifetime.
  5226. if (!type->isObjCLifetimeType())
  5227. return false;
  5228. lifetime = type->getObjCARCImplicitLifetime();
  5229. type = Context.getLifetimeQualifiedType(type, lifetime);
  5230. decl->setType(type);
  5231. }
  5232. if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
  5233. // Thread-local variables cannot have lifetime.
  5234. if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
  5235. var->getTLSKind()) {
  5236. Diag(var->getLocation(), diag::err_arc_thread_ownership)
  5237. << var->getType();
  5238. return true;
  5239. }
  5240. }
  5241. return false;
  5242. }
  5243. static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
  5244. // Ensure that an auto decl is deduced otherwise the checks below might cache
  5245. // the wrong linkage.
  5246. assert(S.ParsingInitForAutoVars.count(&ND) == 0);
  5247. // 'weak' only applies to declarations with external linkage.
  5248. if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
  5249. if (!ND.isExternallyVisible()) {
  5250. S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
  5251. ND.dropAttr<WeakAttr>();
  5252. }
  5253. }
  5254. if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
  5255. if (ND.isExternallyVisible()) {
  5256. S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
  5257. ND.dropAttr<WeakRefAttr>();
  5258. ND.dropAttr<AliasAttr>();
  5259. }
  5260. }
  5261. if (auto *VD = dyn_cast<VarDecl>(&ND)) {
  5262. if (VD->hasInit()) {
  5263. if (const auto *Attr = VD->getAttr<AliasAttr>()) {
  5264. assert(VD->isThisDeclarationADefinition() &&
  5265. !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
  5266. S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
  5267. VD->dropAttr<AliasAttr>();
  5268. }
  5269. }
  5270. }
  5271. // 'selectany' only applies to externally visible variable declarations.
  5272. // It does not apply to functions.
  5273. if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
  5274. if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
  5275. S.Diag(Attr->getLocation(),
  5276. diag::err_attribute_selectany_non_extern_data);
  5277. ND.dropAttr<SelectAnyAttr>();
  5278. }
  5279. }
  5280. if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
  5281. // dll attributes require external linkage. Static locals may have external
  5282. // linkage but still cannot be explicitly imported or exported.
  5283. auto *VD = dyn_cast<VarDecl>(&ND);
  5284. if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
  5285. S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
  5286. << &ND << Attr;
  5287. ND.setInvalidDecl();
  5288. }
  5289. }
  5290. // Virtual functions cannot be marked as 'notail'.
  5291. if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
  5292. if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
  5293. if (MD->isVirtual()) {
  5294. S.Diag(ND.getLocation(),
  5295. diag::err_invalid_attribute_on_virtual_function)
  5296. << Attr;
  5297. ND.dropAttr<NotTailCalledAttr>();
  5298. }
  5299. }
  5300. static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
  5301. NamedDecl *NewDecl,
  5302. bool IsSpecialization,
  5303. bool IsDefinition) {
  5304. if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
  5305. return;
  5306. bool IsTemplate = false;
  5307. if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
  5308. OldDecl = OldTD->getTemplatedDecl();
  5309. IsTemplate = true;
  5310. if (!IsSpecialization)
  5311. IsDefinition = false;
  5312. }
  5313. if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
  5314. NewDecl = NewTD->getTemplatedDecl();
  5315. IsTemplate = true;
  5316. }
  5317. if (!OldDecl || !NewDecl)
  5318. return;
  5319. const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
  5320. const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
  5321. const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
  5322. const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
  5323. // dllimport and dllexport are inheritable attributes so we have to exclude
  5324. // inherited attribute instances.
  5325. bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
  5326. (NewExportAttr && !NewExportAttr->isInherited());
  5327. // A redeclaration is not allowed to add a dllimport or dllexport attribute,
  5328. // the only exception being explicit specializations.
  5329. // Implicitly generated declarations are also excluded for now because there
  5330. // is no other way to switch these to use dllimport or dllexport.
  5331. bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
  5332. if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
  5333. // Allow with a warning for free functions and global variables.
  5334. bool JustWarn = false;
  5335. if (!OldDecl->isCXXClassMember()) {
  5336. auto *VD = dyn_cast<VarDecl>(OldDecl);
  5337. if (VD && !VD->getDescribedVarTemplate())
  5338. JustWarn = true;
  5339. auto *FD = dyn_cast<FunctionDecl>(OldDecl);
  5340. if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
  5341. JustWarn = true;
  5342. }
  5343. // We cannot change a declaration that's been used because IR has already
  5344. // been emitted. Dllimported functions will still work though (modulo
  5345. // address equality) as they can use the thunk.
  5346. if (OldDecl->isUsed())
  5347. if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
  5348. JustWarn = false;
  5349. unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
  5350. : diag::err_attribute_dll_redeclaration;
  5351. S.Diag(NewDecl->getLocation(), DiagID)
  5352. << NewDecl
  5353. << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
  5354. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5355. if (!JustWarn) {
  5356. NewDecl->setInvalidDecl();
  5357. return;
  5358. }
  5359. }
  5360. // A redeclaration is not allowed to drop a dllimport attribute, the only
  5361. // exceptions being inline function definitions (except for function
  5362. // templates), local extern declarations, qualified friend declarations or
  5363. // special MSVC extension: in the last case, the declaration is treated as if
  5364. // it were marked dllexport.
  5365. bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
  5366. bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
  5367. if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
  5368. // Ignore static data because out-of-line definitions are diagnosed
  5369. // separately.
  5370. IsStaticDataMember = VD->isStaticDataMember();
  5371. IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
  5372. VarDecl::DeclarationOnly;
  5373. } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
  5374. IsInline = FD->isInlined();
  5375. IsQualifiedFriend = FD->getQualifier() &&
  5376. FD->getFriendObjectKind() == Decl::FOK_Declared;
  5377. }
  5378. if (OldImportAttr && !HasNewAttr &&
  5379. (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
  5380. !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
  5381. if (IsMicrosoft && IsDefinition) {
  5382. S.Diag(NewDecl->getLocation(),
  5383. diag::warn_redeclaration_without_import_attribute)
  5384. << NewDecl;
  5385. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5386. NewDecl->dropAttr<DLLImportAttr>();
  5387. NewDecl->addAttr(::new (S.Context) DLLExportAttr(
  5388. NewImportAttr->getRange(), S.Context,
  5389. NewImportAttr->getSpellingListIndex()));
  5390. } else {
  5391. S.Diag(NewDecl->getLocation(),
  5392. diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
  5393. << NewDecl << OldImportAttr;
  5394. S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
  5395. S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
  5396. OldDecl->dropAttr<DLLImportAttr>();
  5397. NewDecl->dropAttr<DLLImportAttr>();
  5398. }
  5399. } else if (IsInline && OldImportAttr && !IsMicrosoft) {
  5400. // In MinGW, seeing a function declared inline drops the dllimport
  5401. // attribute.
  5402. OldDecl->dropAttr<DLLImportAttr>();
  5403. NewDecl->dropAttr<DLLImportAttr>();
  5404. S.Diag(NewDecl->getLocation(),
  5405. diag::warn_dllimport_dropped_from_inline_function)
  5406. << NewDecl << OldImportAttr;
  5407. }
  5408. // A specialization of a class template member function is processed here
  5409. // since it's a redeclaration. If the parent class is dllexport, the
  5410. // specialization inherits that attribute. This doesn't happen automatically
  5411. // since the parent class isn't instantiated until later.
  5412. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
  5413. if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
  5414. !NewImportAttr && !NewExportAttr) {
  5415. if (const DLLExportAttr *ParentExportAttr =
  5416. MD->getParent()->getAttr<DLLExportAttr>()) {
  5417. DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
  5418. NewAttr->setInherited(true);
  5419. NewDecl->addAttr(NewAttr);
  5420. }
  5421. }
  5422. }
  5423. }
  5424. /// Given that we are within the definition of the given function,
  5425. /// will that definition behave like C99's 'inline', where the
  5426. /// definition is discarded except for optimization purposes?
  5427. static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
  5428. // Try to avoid calling GetGVALinkageForFunction.
  5429. // All cases of this require the 'inline' keyword.
  5430. if (!FD->isInlined()) return false;
  5431. // This is only possible in C++ with the gnu_inline attribute.
  5432. if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
  5433. return false;
  5434. // Okay, go ahead and call the relatively-more-expensive function.
  5435. return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
  5436. }
  5437. /// Determine whether a variable is extern "C" prior to attaching
  5438. /// an initializer. We can't just call isExternC() here, because that
  5439. /// will also compute and cache whether the declaration is externally
  5440. /// visible, which might change when we attach the initializer.
  5441. ///
  5442. /// This can only be used if the declaration is known to not be a
  5443. /// redeclaration of an internal linkage declaration.
  5444. ///
  5445. /// For instance:
  5446. ///
  5447. /// auto x = []{};
  5448. ///
  5449. /// Attaching the initializer here makes this declaration not externally
  5450. /// visible, because its type has internal linkage.
  5451. ///
  5452. /// FIXME: This is a hack.
  5453. template<typename T>
  5454. static bool isIncompleteDeclExternC(Sema &S, const T *D) {
  5455. if (S.getLangOpts().CPlusPlus) {
  5456. // In C++, the overloadable attribute negates the effects of extern "C".
  5457. if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
  5458. return false;
  5459. // So do CUDA's host/device attributes.
  5460. if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
  5461. D->template hasAttr<CUDAHostAttr>()))
  5462. return false;
  5463. }
  5464. return D->isExternC();
  5465. }
  5466. static bool shouldConsiderLinkage(const VarDecl *VD) {
  5467. const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
  5468. if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
  5469. return VD->hasExternalStorage();
  5470. if (DC->isFileContext())
  5471. return true;
  5472. if (DC->isRecord())
  5473. return false;
  5474. llvm_unreachable("Unexpected context");
  5475. }
  5476. static bool shouldConsiderLinkage(const FunctionDecl *FD) {
  5477. const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
  5478. if (DC->isFileContext() || DC->isFunctionOrMethod() ||
  5479. isa<OMPDeclareReductionDecl>(DC))
  5480. return true;
  5481. if (DC->isRecord())
  5482. return false;
  5483. llvm_unreachable("Unexpected context");
  5484. }
  5485. static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
  5486. AttributeList::Kind Kind) {
  5487. for (const AttributeList *L = AttrList; L; L = L->getNext())
  5488. if (L->getKind() == Kind)
  5489. return true;
  5490. return false;
  5491. }
  5492. static bool hasParsedAttr(Scope *S, const Declarator &PD,
  5493. AttributeList::Kind Kind) {
  5494. // Check decl attributes on the DeclSpec.
  5495. if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), 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 (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
  5501. return true;
  5502. }
  5503. // Finally, check attributes on the decl itself.
  5504. return hasParsedAttr(S, PD.getAttributes(), 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.getLocStart(), 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, AttributeList::AT_DLLImport) &&
  5642. !hasParsedAttr(S, D, AttributeList::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.getLocStart(),
  5684. D.getIdentifierLoc(), II,
  5685. R, TInfo, SC);
  5686. if (R->getContainedDeducedType())
  5687. ParsingInitForAutoVars.insert(NewVD);
  5688. if (D.isInvalidType())
  5689. NewVD->setInvalidDecl();
  5690. } else {
  5691. bool Invalid = false;
  5692. if (DC->isRecord() && !CurContext->isRecord()) {
  5693. // This is an out-of-line definition of a static data member.
  5694. switch (SC) {
  5695. case SC_None:
  5696. break;
  5697. case SC_Static:
  5698. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5699. diag::err_static_out_of_line)
  5700. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5701. break;
  5702. case SC_Auto:
  5703. case SC_Register:
  5704. case SC_Extern:
  5705. // [dcl.stc] p2: The auto or register specifiers shall be applied only
  5706. // to names of variables declared in a block or to function parameters.
  5707. // [dcl.stc] p6: The extern specifier cannot be used in the declaration
  5708. // of class members
  5709. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5710. diag::err_storage_class_for_static_member)
  5711. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  5712. break;
  5713. case SC_PrivateExtern:
  5714. llvm_unreachable("C storage class in c++!");
  5715. }
  5716. }
  5717. if (SC == SC_Static && CurContext->isRecord()) {
  5718. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
  5719. if (RD->isLocalClass())
  5720. Diag(D.getIdentifierLoc(),
  5721. diag::err_static_data_member_not_allowed_in_local_class)
  5722. << Name << RD->getDeclName();
  5723. // C++98 [class.union]p1: If a union contains a static data member,
  5724. // the program is ill-formed. C++11 drops this restriction.
  5725. if (RD->isUnion())
  5726. Diag(D.getIdentifierLoc(),
  5727. getLangOpts().CPlusPlus11
  5728. ? diag::warn_cxx98_compat_static_data_member_in_union
  5729. : diag::ext_static_data_member_in_union) << Name;
  5730. // We conservatively disallow static data members in anonymous structs.
  5731. else if (!RD->getDeclName())
  5732. Diag(D.getIdentifierLoc(),
  5733. diag::err_static_data_member_not_allowed_in_anon_struct)
  5734. << Name << RD->isUnion();
  5735. }
  5736. }
  5737. // Match up the template parameter lists with the scope specifier, then
  5738. // determine whether we have a template or a template specialization.
  5739. TemplateParams = MatchTemplateParametersToScopeSpecifier(
  5740. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  5741. D.getCXXScopeSpec(),
  5742. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  5743. ? D.getName().TemplateId
  5744. : nullptr,
  5745. TemplateParamLists,
  5746. /*never a friend*/ false, IsMemberSpecialization, Invalid);
  5747. if (TemplateParams) {
  5748. if (!TemplateParams->size() &&
  5749. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  5750. // There is an extraneous 'template<>' for this variable. Complain
  5751. // about it, but allow the declaration of the variable.
  5752. Diag(TemplateParams->getTemplateLoc(),
  5753. diag::err_template_variable_noparams)
  5754. << II
  5755. << SourceRange(TemplateParams->getTemplateLoc(),
  5756. TemplateParams->getRAngleLoc());
  5757. TemplateParams = nullptr;
  5758. } else {
  5759. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  5760. // This is an explicit specialization or a partial specialization.
  5761. // FIXME: Check that we can declare a specialization here.
  5762. IsVariableTemplateSpecialization = true;
  5763. IsPartialSpecialization = TemplateParams->size() > 0;
  5764. } else { // if (TemplateParams->size() > 0)
  5765. // This is a template declaration.
  5766. IsVariableTemplate = true;
  5767. // Check that we can declare a template here.
  5768. if (CheckTemplateDeclScope(S, TemplateParams))
  5769. return nullptr;
  5770. // Only C++1y supports variable templates (N3651).
  5771. Diag(D.getIdentifierLoc(),
  5772. getLangOpts().CPlusPlus14
  5773. ? diag::warn_cxx11_compat_variable_template
  5774. : diag::ext_variable_template);
  5775. }
  5776. }
  5777. } else {
  5778. assert((Invalid ||
  5779. D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
  5780. "should have a 'template<>' for this decl");
  5781. }
  5782. if (IsVariableTemplateSpecialization) {
  5783. SourceLocation TemplateKWLoc =
  5784. TemplateParamLists.size() > 0
  5785. ? TemplateParamLists[0]->getTemplateLoc()
  5786. : SourceLocation();
  5787. DeclResult Res = ActOnVarTemplateSpecialization(
  5788. S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
  5789. IsPartialSpecialization);
  5790. if (Res.isInvalid())
  5791. return nullptr;
  5792. NewVD = cast<VarDecl>(Res.get());
  5793. AddToScope = false;
  5794. } else if (D.isDecompositionDeclarator()) {
  5795. NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
  5796. D.getIdentifierLoc(), R, TInfo, SC,
  5797. Bindings);
  5798. } else
  5799. NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
  5800. D.getIdentifierLoc(), II, R, TInfo, SC);
  5801. // If this is supposed to be a variable template, create it as such.
  5802. if (IsVariableTemplate) {
  5803. NewTemplate =
  5804. VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
  5805. TemplateParams, NewVD);
  5806. NewVD->setDescribedVarTemplate(NewTemplate);
  5807. }
  5808. // If this decl has an auto type in need of deduction, make a note of the
  5809. // Decl so we can diagnose uses of it in its own initializer.
  5810. if (R->getContainedDeducedType())
  5811. ParsingInitForAutoVars.insert(NewVD);
  5812. if (D.isInvalidType() || Invalid) {
  5813. NewVD->setInvalidDecl();
  5814. if (NewTemplate)
  5815. NewTemplate->setInvalidDecl();
  5816. }
  5817. SetNestedNameSpecifier(NewVD, D);
  5818. // If we have any template parameter lists that don't directly belong to
  5819. // the variable (matching the scope specifier), store them.
  5820. unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
  5821. if (TemplateParamLists.size() > VDTemplateParamLists)
  5822. NewVD->setTemplateParameterListsInfo(
  5823. Context, TemplateParamLists.drop_back(VDTemplateParamLists));
  5824. if (D.getDeclSpec().isConstexprSpecified()) {
  5825. NewVD->setConstexpr(true);
  5826. // C++1z [dcl.spec.constexpr]p1:
  5827. // A static data member declared with the constexpr specifier is
  5828. // implicitly an inline variable.
  5829. if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
  5830. NewVD->setImplicitlyInline();
  5831. }
  5832. }
  5833. if (D.getDeclSpec().isInlineSpecified()) {
  5834. if (!getLangOpts().CPlusPlus) {
  5835. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  5836. << 0;
  5837. } else if (CurContext->isFunctionOrMethod()) {
  5838. // 'inline' is not allowed on block scope variable declaration.
  5839. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5840. diag::err_inline_declaration_block_scope) << Name
  5841. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  5842. } else {
  5843. Diag(D.getDeclSpec().getInlineSpecLoc(),
  5844. getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
  5845. : diag::ext_inline_variable);
  5846. NewVD->setInlineSpecified();
  5847. }
  5848. }
  5849. // Set the lexical context. If the declarator has a C++ scope specifier, the
  5850. // lexical context will be different from the semantic context.
  5851. NewVD->setLexicalDeclContext(CurContext);
  5852. if (NewTemplate)
  5853. NewTemplate->setLexicalDeclContext(CurContext);
  5854. if (IsLocalExternDecl) {
  5855. if (D.isDecompositionDeclarator())
  5856. for (auto *B : Bindings)
  5857. B->setLocalExternDecl();
  5858. else
  5859. NewVD->setLocalExternDecl();
  5860. }
  5861. bool EmitTLSUnsupportedError = false;
  5862. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
  5863. // C++11 [dcl.stc]p4:
  5864. // When thread_local is applied to a variable of block scope the
  5865. // storage-class-specifier static is implied if it does not appear
  5866. // explicitly.
  5867. // Core issue: 'static' is not implied if the variable is declared
  5868. // 'extern'.
  5869. if (NewVD->hasLocalStorage() &&
  5870. (SCSpec != DeclSpec::SCS_unspecified ||
  5871. TSCS != DeclSpec::TSCS_thread_local ||
  5872. !DC->isFunctionOrMethod()))
  5873. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5874. diag::err_thread_non_global)
  5875. << DeclSpec::getSpecifierName(TSCS);
  5876. else if (!Context.getTargetInfo().isTLSSupported()) {
  5877. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5878. // Postpone error emission until we've collected attributes required to
  5879. // figure out whether it's a host or device variable and whether the
  5880. // error should be ignored.
  5881. EmitTLSUnsupportedError = true;
  5882. // We still need to mark the variable as TLS so it shows up in AST with
  5883. // proper storage class for other tools to use even if we're not going
  5884. // to emit any code for it.
  5885. NewVD->setTSCSpec(TSCS);
  5886. } else
  5887. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5888. diag::err_thread_unsupported);
  5889. } else
  5890. NewVD->setTSCSpec(TSCS);
  5891. }
  5892. // C99 6.7.4p3
  5893. // An inline definition of a function with external linkage shall
  5894. // not contain a definition of a modifiable object with static or
  5895. // thread storage duration...
  5896. // We only apply this when the function is required to be defined
  5897. // elsewhere, i.e. when the function is not 'extern inline'. Note
  5898. // that a local variable with thread storage duration still has to
  5899. // be marked 'static'. Also note that it's possible to get these
  5900. // semantics in C++ using __attribute__((gnu_inline)).
  5901. if (SC == SC_Static && S->getFnParent() != nullptr &&
  5902. !NewVD->getType().isConstQualified()) {
  5903. FunctionDecl *CurFD = getCurFunctionDecl();
  5904. if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
  5905. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  5906. diag::warn_static_local_in_extern_inline);
  5907. MaybeSuggestAddingStaticToDecl(CurFD);
  5908. }
  5909. }
  5910. if (D.getDeclSpec().isModulePrivateSpecified()) {
  5911. if (IsVariableTemplateSpecialization)
  5912. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5913. << (IsPartialSpecialization ? 1 : 0)
  5914. << FixItHint::CreateRemoval(
  5915. D.getDeclSpec().getModulePrivateSpecLoc());
  5916. else if (IsMemberSpecialization)
  5917. Diag(NewVD->getLocation(), diag::err_module_private_specialization)
  5918. << 2
  5919. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5920. else if (NewVD->hasLocalStorage())
  5921. Diag(NewVD->getLocation(), diag::err_module_private_local)
  5922. << 0 << NewVD->getDeclName()
  5923. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  5924. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  5925. else {
  5926. NewVD->setModulePrivate();
  5927. if (NewTemplate)
  5928. NewTemplate->setModulePrivate();
  5929. for (auto *B : Bindings)
  5930. B->setModulePrivate();
  5931. }
  5932. }
  5933. // Handle attributes prior to checking for duplicates in MergeVarDecl
  5934. ProcessDeclAttributes(S, NewVD, D);
  5935. if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
  5936. if (EmitTLSUnsupportedError &&
  5937. ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
  5938. (getLangOpts().OpenMPIsDevice &&
  5939. NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
  5940. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  5941. diag::err_thread_unsupported);
  5942. // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
  5943. // storage [duration]."
  5944. if (SC == SC_None && S->getFnParent() != nullptr &&
  5945. (NewVD->hasAttr<CUDASharedAttr>() ||
  5946. NewVD->hasAttr<CUDAConstantAttr>())) {
  5947. NewVD->setStorageClass(SC_Static);
  5948. }
  5949. }
  5950. // Ensure that dllimport globals without explicit storage class are treated as
  5951. // extern. The storage class is set above using parsed attributes. Now we can
  5952. // check the VarDecl itself.
  5953. assert(!NewVD->hasAttr<DLLImportAttr>() ||
  5954. NewVD->getAttr<DLLImportAttr>()->isInherited() ||
  5955. NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
  5956. // In auto-retain/release, infer strong retension for variables of
  5957. // retainable type.
  5958. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
  5959. NewVD->setInvalidDecl();
  5960. // Handle GNU asm-label extension (encoded as an attribute).
  5961. if (Expr *E = (Expr*)D.getAsmLabel()) {
  5962. // The parser guarantees this is a string.
  5963. StringLiteral *SE = cast<StringLiteral>(E);
  5964. StringRef Label = SE->getString();
  5965. if (S->getFnParent() != nullptr) {
  5966. switch (SC) {
  5967. case SC_None:
  5968. case SC_Auto:
  5969. Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
  5970. break;
  5971. case SC_Register:
  5972. // Local Named register
  5973. if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
  5974. DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
  5975. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5976. break;
  5977. case SC_Static:
  5978. case SC_Extern:
  5979. case SC_PrivateExtern:
  5980. break;
  5981. }
  5982. } else if (SC == SC_Register) {
  5983. // Global Named register
  5984. if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
  5985. const auto &TI = Context.getTargetInfo();
  5986. bool HasSizeMismatch;
  5987. if (!TI.isValidGCCRegisterName(Label))
  5988. Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
  5989. else if (!TI.validateGlobalRegisterVariable(Label,
  5990. Context.getTypeSize(R),
  5991. HasSizeMismatch))
  5992. Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
  5993. else if (HasSizeMismatch)
  5994. Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
  5995. }
  5996. if (!R->isIntegralType(Context) && !R->isPointerType()) {
  5997. Diag(D.getLocStart(), diag::err_asm_bad_register_type);
  5998. NewVD->setInvalidDecl(true);
  5999. }
  6000. }
  6001. NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
  6002. Context, Label, 0));
  6003. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  6004. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  6005. ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
  6006. if (I != ExtnameUndeclaredIdentifiers.end()) {
  6007. if (isDeclExternC(NewVD)) {
  6008. NewVD->addAttr(I->second);
  6009. ExtnameUndeclaredIdentifiers.erase(I);
  6010. } else
  6011. Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
  6012. << /*Variable*/1 << NewVD;
  6013. }
  6014. }
  6015. // Find the shadowed declaration before filtering for scope.
  6016. NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
  6017. ? getShadowedDeclaration(NewVD, Previous)
  6018. : nullptr;
  6019. // Don't consider existing declarations that are in a different
  6020. // scope and are out-of-semantic-context declarations (if the new
  6021. // declaration has linkage).
  6022. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
  6023. D.getCXXScopeSpec().isNotEmpty() ||
  6024. IsMemberSpecialization ||
  6025. IsVariableTemplateSpecialization);
  6026. // Check whether the previous declaration is in the same block scope. This
  6027. // affects whether we merge types with it, per C++11 [dcl.array]p3.
  6028. if (getLangOpts().CPlusPlus &&
  6029. NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
  6030. NewVD->setPreviousDeclInSameBlockScope(
  6031. Previous.isSingleResult() && !Previous.isShadowed() &&
  6032. isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
  6033. if (!getLangOpts().CPlusPlus) {
  6034. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6035. } else {
  6036. // If this is an explicit specialization of a static data member, check it.
  6037. if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
  6038. CheckMemberSpecialization(NewVD, Previous))
  6039. NewVD->setInvalidDecl();
  6040. // Merge the decl with the existing one if appropriate.
  6041. if (!Previous.empty()) {
  6042. if (Previous.isSingleResult() &&
  6043. isa<FieldDecl>(Previous.getFoundDecl()) &&
  6044. D.getCXXScopeSpec().isSet()) {
  6045. // The user tried to define a non-static data member
  6046. // out-of-line (C++ [dcl.meaning]p1).
  6047. Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
  6048. << D.getCXXScopeSpec().getRange();
  6049. Previous.clear();
  6050. NewVD->setInvalidDecl();
  6051. }
  6052. } else if (D.getCXXScopeSpec().isSet()) {
  6053. // No previous declaration in the qualifying scope.
  6054. Diag(D.getIdentifierLoc(), diag::err_no_member)
  6055. << Name << computeDeclContext(D.getCXXScopeSpec(), true)
  6056. << D.getCXXScopeSpec().getRange();
  6057. NewVD->setInvalidDecl();
  6058. }
  6059. if (!IsVariableTemplateSpecialization)
  6060. D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
  6061. if (NewTemplate) {
  6062. VarTemplateDecl *PrevVarTemplate =
  6063. NewVD->getPreviousDecl()
  6064. ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
  6065. : nullptr;
  6066. // Check the template parameter list of this declaration, possibly
  6067. // merging in the template parameter list from the previous variable
  6068. // template declaration.
  6069. if (CheckTemplateParameterList(
  6070. TemplateParams,
  6071. PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
  6072. : nullptr,
  6073. (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
  6074. DC->isDependentContext())
  6075. ? TPC_ClassTemplateMember
  6076. : TPC_VarTemplate))
  6077. NewVD->setInvalidDecl();
  6078. // If we are providing an explicit specialization of a static variable
  6079. // template, make a note of that.
  6080. if (PrevVarTemplate &&
  6081. PrevVarTemplate->getInstantiatedFromMemberTemplate())
  6082. PrevVarTemplate->setMemberSpecialization();
  6083. }
  6084. }
  6085. // Diagnose shadowed variables iff this isn't a redeclaration.
  6086. if (ShadowedDecl && !D.isRedeclaration())
  6087. CheckShadow(NewVD, ShadowedDecl, Previous);
  6088. ProcessPragmaWeak(S, NewVD);
  6089. // If this is the first declaration of an extern C variable, update
  6090. // the map of such variables.
  6091. if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
  6092. isIncompleteDeclExternC(*this, NewVD))
  6093. RegisterLocallyScopedExternCDecl(NewVD, S);
  6094. if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
  6095. Decl *ManglingContextDecl;
  6096. if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
  6097. NewVD->getDeclContext(), ManglingContextDecl)) {
  6098. Context.setManglingNumber(
  6099. NewVD, MCtx->getManglingNumber(
  6100. NewVD, getMSManglingNumber(getLangOpts(), S)));
  6101. Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
  6102. }
  6103. }
  6104. // Special handling of variable named 'main'.
  6105. if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
  6106. NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  6107. !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
  6108. // C++ [basic.start.main]p3
  6109. // A program that declares a variable main at global scope is ill-formed.
  6110. if (getLangOpts().CPlusPlus)
  6111. Diag(D.getLocStart(), diag::err_main_global_variable);
  6112. // In C, and external-linkage variable named main results in undefined
  6113. // behavior.
  6114. else if (NewVD->hasExternalFormalLinkage())
  6115. Diag(D.getLocStart(), diag::warn_main_redefined);
  6116. }
  6117. if (D.isRedeclaration() && !Previous.empty()) {
  6118. NamedDecl *Prev = Previous.getRepresentativeDecl();
  6119. checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
  6120. D.isFunctionDefinition());
  6121. }
  6122. if (NewTemplate) {
  6123. if (NewVD->isInvalidDecl())
  6124. NewTemplate->setInvalidDecl();
  6125. ActOnDocumentableDecl(NewTemplate);
  6126. return NewTemplate;
  6127. }
  6128. if (IsMemberSpecialization && !NewVD->isInvalidDecl())
  6129. CompleteMemberSpecialization(NewVD, Previous);
  6130. return NewVD;
  6131. }
  6132. /// Enum describing the %select options in diag::warn_decl_shadow.
  6133. enum ShadowedDeclKind {
  6134. SDK_Local,
  6135. SDK_Global,
  6136. SDK_StaticMember,
  6137. SDK_Field,
  6138. SDK_Typedef,
  6139. SDK_Using
  6140. };
  6141. /// Determine what kind of declaration we're shadowing.
  6142. static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
  6143. const DeclContext *OldDC) {
  6144. if (isa<TypeAliasDecl>(ShadowedDecl))
  6145. return SDK_Using;
  6146. else if (isa<TypedefDecl>(ShadowedDecl))
  6147. return SDK_Typedef;
  6148. else if (isa<RecordDecl>(OldDC))
  6149. return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
  6150. return OldDC->isFileContext() ? SDK_Global : SDK_Local;
  6151. }
  6152. /// Return the location of the capture if the given lambda captures the given
  6153. /// variable \p VD, or an invalid source location otherwise.
  6154. static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
  6155. const VarDecl *VD) {
  6156. for (const Capture &Capture : LSI->Captures) {
  6157. if (Capture.isVariableCapture() && Capture.getVariable() == VD)
  6158. return Capture.getLocation();
  6159. }
  6160. return SourceLocation();
  6161. }
  6162. static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
  6163. const LookupResult &R) {
  6164. // Only diagnose if we're shadowing an unambiguous field or variable.
  6165. if (R.getResultKind() != LookupResult::Found)
  6166. return false;
  6167. // Return false if warning is ignored.
  6168. return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
  6169. }
  6170. /// Return the declaration shadowed by the given variable \p D, or null
  6171. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6172. NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
  6173. const LookupResult &R) {
  6174. if (!shouldWarnIfShadowedDecl(Diags, R))
  6175. return nullptr;
  6176. // Don't diagnose declarations at file scope.
  6177. if (D->hasGlobalStorage())
  6178. return nullptr;
  6179. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6180. return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
  6181. ? ShadowedDecl
  6182. : nullptr;
  6183. }
  6184. /// Return the declaration shadowed by the given typedef \p D, or null
  6185. /// if it doesn't shadow any declaration or shadowing warnings are disabled.
  6186. NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
  6187. const LookupResult &R) {
  6188. // Don't warn if typedef declaration is part of a class
  6189. if (D->getDeclContext()->isRecord())
  6190. return nullptr;
  6191. if (!shouldWarnIfShadowedDecl(Diags, R))
  6192. return nullptr;
  6193. NamedDecl *ShadowedDecl = R.getFoundDecl();
  6194. return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
  6195. }
  6196. /// Diagnose variable or built-in function shadowing. Implements
  6197. /// -Wshadow.
  6198. ///
  6199. /// This method is called whenever a VarDecl is added to a "useful"
  6200. /// scope.
  6201. ///
  6202. /// \param ShadowedDecl the declaration that is shadowed by the given variable
  6203. /// \param R the lookup of the name
  6204. ///
  6205. void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
  6206. const LookupResult &R) {
  6207. DeclContext *NewDC = D->getDeclContext();
  6208. if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
  6209. // Fields are not shadowed by variables in C++ static methods.
  6210. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
  6211. if (MD->isStatic())
  6212. return;
  6213. // Fields shadowed by constructor parameters are a special case. Usually
  6214. // the constructor initializes the field with the parameter.
  6215. if (isa<CXXConstructorDecl>(NewDC))
  6216. if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
  6217. // Remember that this was shadowed so we can either warn about its
  6218. // modification or its existence depending on warning settings.
  6219. ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
  6220. return;
  6221. }
  6222. }
  6223. if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
  6224. if (shadowedVar->isExternC()) {
  6225. // For shadowing external vars, make sure that we point to the global
  6226. // declaration, not a locally scoped extern declaration.
  6227. for (auto I : shadowedVar->redecls())
  6228. if (I->isFileVarDecl()) {
  6229. ShadowedDecl = I;
  6230. break;
  6231. }
  6232. }
  6233. DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
  6234. unsigned WarningDiag = diag::warn_decl_shadow;
  6235. SourceLocation CaptureLoc;
  6236. if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
  6237. isa<CXXMethodDecl>(NewDC)) {
  6238. if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
  6239. if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
  6240. if (RD->getLambdaCaptureDefault() == LCD_None) {
  6241. // Try to avoid warnings for lambdas with an explicit capture list.
  6242. const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
  6243. // Warn only when the lambda captures the shadowed decl explicitly.
  6244. CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
  6245. if (CaptureLoc.isInvalid())
  6246. WarningDiag = diag::warn_decl_shadow_uncaptured_local;
  6247. } else {
  6248. // Remember that this was shadowed so we can avoid the warning if the
  6249. // shadowed decl isn't captured and the warning settings allow it.
  6250. cast<LambdaScopeInfo>(getCurFunction())
  6251. ->ShadowingDecls.push_back(
  6252. {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
  6253. return;
  6254. }
  6255. }
  6256. if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
  6257. // A variable can't shadow a local variable in an enclosing scope, if
  6258. // they are separated by a non-capturing declaration context.
  6259. for (DeclContext *ParentDC = NewDC;
  6260. ParentDC && !ParentDC->Equals(OldDC);
  6261. ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
  6262. // Only block literals, captured statements, and lambda expressions
  6263. // can capture; other scopes don't.
  6264. if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
  6265. !isLambdaCallOperator(ParentDC)) {
  6266. return;
  6267. }
  6268. }
  6269. }
  6270. }
  6271. }
  6272. // Only warn about certain kinds of shadowing for class members.
  6273. if (NewDC && NewDC->isRecord()) {
  6274. // In particular, don't warn about shadowing non-class members.
  6275. if (!OldDC->isRecord())
  6276. return;
  6277. // TODO: should we warn about static data members shadowing
  6278. // static data members from base classes?
  6279. // TODO: don't diagnose for inaccessible shadowed members.
  6280. // This is hard to do perfectly because we might friend the
  6281. // shadowing context, but that's just a false negative.
  6282. }
  6283. DeclarationName Name = R.getLookupName();
  6284. // Emit warning and note.
  6285. if (getSourceManager().isInSystemMacro(R.getNameLoc()))
  6286. return;
  6287. ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
  6288. Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
  6289. if (!CaptureLoc.isInvalid())
  6290. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6291. << Name << /*explicitly*/ 1;
  6292. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6293. }
  6294. /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
  6295. /// when these variables are captured by the lambda.
  6296. void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
  6297. for (const auto &Shadow : LSI->ShadowingDecls) {
  6298. const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
  6299. // Try to avoid the warning when the shadowed decl isn't captured.
  6300. SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
  6301. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6302. Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
  6303. ? diag::warn_decl_shadow_uncaptured_local
  6304. : diag::warn_decl_shadow)
  6305. << Shadow.VD->getDeclName()
  6306. << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
  6307. if (!CaptureLoc.isInvalid())
  6308. Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
  6309. << Shadow.VD->getDeclName() << /*explicitly*/ 0;
  6310. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6311. }
  6312. }
  6313. /// Check -Wshadow without the advantage of a previous lookup.
  6314. void Sema::CheckShadow(Scope *S, VarDecl *D) {
  6315. if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
  6316. return;
  6317. LookupResult R(*this, D->getDeclName(), D->getLocation(),
  6318. Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
  6319. LookupName(R, S);
  6320. if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
  6321. CheckShadow(D, ShadowedDecl, R);
  6322. }
  6323. /// Check if 'E', which is an expression that is about to be modified, refers
  6324. /// to a constructor parameter that shadows a field.
  6325. void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
  6326. // Quickly ignore expressions that can't be shadowing ctor parameters.
  6327. if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
  6328. return;
  6329. E = E->IgnoreParenImpCasts();
  6330. auto *DRE = dyn_cast<DeclRefExpr>(E);
  6331. if (!DRE)
  6332. return;
  6333. const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
  6334. auto I = ShadowingDecls.find(D);
  6335. if (I == ShadowingDecls.end())
  6336. return;
  6337. const NamedDecl *ShadowedDecl = I->second;
  6338. const DeclContext *OldDC = ShadowedDecl->getDeclContext();
  6339. Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
  6340. Diag(D->getLocation(), diag::note_var_declared_here) << D;
  6341. Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
  6342. // Avoid issuing multiple warnings about the same decl.
  6343. ShadowingDecls.erase(I);
  6344. }
  6345. /// Check for conflict between this global or extern "C" declaration and
  6346. /// previous global or extern "C" declarations. This is only used in C++.
  6347. template<typename T>
  6348. static bool checkGlobalOrExternCConflict(
  6349. Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
  6350. assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
  6351. NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
  6352. if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
  6353. // The common case: this global doesn't conflict with any extern "C"
  6354. // declaration.
  6355. return false;
  6356. }
  6357. if (Prev) {
  6358. if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
  6359. // Both the old and new declarations have C language linkage. This is a
  6360. // redeclaration.
  6361. Previous.clear();
  6362. Previous.addDecl(Prev);
  6363. return true;
  6364. }
  6365. // This is a global, non-extern "C" declaration, and there is a previous
  6366. // non-global extern "C" declaration. Diagnose if this is a variable
  6367. // declaration.
  6368. if (!isa<VarDecl>(ND))
  6369. return false;
  6370. } else {
  6371. // The declaration is extern "C". Check for any declaration in the
  6372. // translation unit which might conflict.
  6373. if (IsGlobal) {
  6374. // We have already performed the lookup into the translation unit.
  6375. IsGlobal = false;
  6376. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6377. I != E; ++I) {
  6378. if (isa<VarDecl>(*I)) {
  6379. Prev = *I;
  6380. break;
  6381. }
  6382. }
  6383. } else {
  6384. DeclContext::lookup_result R =
  6385. S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
  6386. for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
  6387. I != E; ++I) {
  6388. if (isa<VarDecl>(*I)) {
  6389. Prev = *I;
  6390. break;
  6391. }
  6392. // FIXME: If we have any other entity with this name in global scope,
  6393. // the declaration is ill-formed, but that is a defect: it breaks the
  6394. // 'stat' hack, for instance. Only variables can have mangled name
  6395. // clashes with extern "C" declarations, so only they deserve a
  6396. // diagnostic.
  6397. }
  6398. }
  6399. if (!Prev)
  6400. return false;
  6401. }
  6402. // Use the first declaration's location to ensure we point at something which
  6403. // is lexically inside an extern "C" linkage-spec.
  6404. assert(Prev && "should have found a previous declaration to diagnose");
  6405. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
  6406. Prev = FD->getFirstDecl();
  6407. else
  6408. Prev = cast<VarDecl>(Prev)->getFirstDecl();
  6409. S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
  6410. << IsGlobal << ND;
  6411. S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
  6412. << IsGlobal;
  6413. return false;
  6414. }
  6415. /// Apply special rules for handling extern "C" declarations. Returns \c true
  6416. /// if we have found that this is a redeclaration of some prior entity.
  6417. ///
  6418. /// Per C++ [dcl.link]p6:
  6419. /// Two declarations [for a function or variable] with C language linkage
  6420. /// with the same name that appear in different scopes refer to the same
  6421. /// [entity]. An entity with C language linkage shall not be declared with
  6422. /// the same name as an entity in global scope.
  6423. template<typename T>
  6424. static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
  6425. LookupResult &Previous) {
  6426. if (!S.getLangOpts().CPlusPlus) {
  6427. // In C, when declaring a global variable, look for a corresponding 'extern'
  6428. // variable declared in function scope. We don't need this in C++, because
  6429. // we find local extern decls in the surrounding file-scope DeclContext.
  6430. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  6431. if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
  6432. Previous.clear();
  6433. Previous.addDecl(Prev);
  6434. return true;
  6435. }
  6436. }
  6437. return false;
  6438. }
  6439. // A declaration in the translation unit can conflict with an extern "C"
  6440. // declaration.
  6441. if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
  6442. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
  6443. // An extern "C" declaration can conflict with a declaration in the
  6444. // translation unit or can be a redeclaration of an extern "C" declaration
  6445. // in another scope.
  6446. if (isIncompleteDeclExternC(S,ND))
  6447. return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
  6448. // Neither global nor extern "C": nothing to do.
  6449. return false;
  6450. }
  6451. void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
  6452. // If the decl is already known invalid, don't check it.
  6453. if (NewVD->isInvalidDecl())
  6454. return;
  6455. TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
  6456. QualType T = TInfo->getType();
  6457. // Defer checking an 'auto' type until its initializer is attached.
  6458. if (T->isUndeducedType())
  6459. return;
  6460. if (NewVD->hasAttrs())
  6461. CheckAlignasUnderalignment(NewVD);
  6462. if (T->isObjCObjectType()) {
  6463. Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
  6464. << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
  6465. T = Context.getObjCObjectPointerType(T);
  6466. NewVD->setType(T);
  6467. }
  6468. // Emit an error if an address space was applied to decl with local storage.
  6469. // This includes arrays of objects with address space qualifiers, but not
  6470. // automatic variables that point to other address spaces.
  6471. // ISO/IEC TR 18037 S5.1.2
  6472. if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
  6473. T.getAddressSpace() != LangAS::Default) {
  6474. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
  6475. NewVD->setInvalidDecl();
  6476. return;
  6477. }
  6478. // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
  6479. // scope.
  6480. if (getLangOpts().OpenCLVersion == 120 &&
  6481. !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
  6482. NewVD->isStaticLocal()) {
  6483. Diag(NewVD->getLocation(), diag::err_static_function_scope);
  6484. NewVD->setInvalidDecl();
  6485. return;
  6486. }
  6487. if (getLangOpts().OpenCL) {
  6488. // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
  6489. if (NewVD->hasAttr<BlocksAttr>()) {
  6490. Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
  6491. return;
  6492. }
  6493. if (T->isBlockPointerType()) {
  6494. // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
  6495. // can't use 'extern' storage class.
  6496. if (!T.isConstQualified()) {
  6497. Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
  6498. << 0 /*const*/;
  6499. NewVD->setInvalidDecl();
  6500. return;
  6501. }
  6502. if (NewVD->hasExternalStorage()) {
  6503. Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
  6504. NewVD->setInvalidDecl();
  6505. return;
  6506. }
  6507. }
  6508. // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
  6509. // __constant address space.
  6510. // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
  6511. // variables inside a function can also be declared in the global
  6512. // address space.
  6513. if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
  6514. NewVD->hasExternalStorage()) {
  6515. if (!T->isSamplerT() &&
  6516. !(T.getAddressSpace() == LangAS::opencl_constant ||
  6517. (T.getAddressSpace() == LangAS::opencl_global &&
  6518. getLangOpts().OpenCLVersion == 200))) {
  6519. int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
  6520. if (getLangOpts().OpenCLVersion == 200)
  6521. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6522. << Scope << "global or constant";
  6523. else
  6524. Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
  6525. << Scope << "constant";
  6526. NewVD->setInvalidDecl();
  6527. return;
  6528. }
  6529. } else {
  6530. if (T.getAddressSpace() == LangAS::opencl_global) {
  6531. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6532. << 1 /*is any function*/ << "global";
  6533. NewVD->setInvalidDecl();
  6534. return;
  6535. }
  6536. if (T.getAddressSpace() == LangAS::opencl_constant ||
  6537. T.getAddressSpace() == LangAS::opencl_local) {
  6538. FunctionDecl *FD = getCurFunctionDecl();
  6539. // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
  6540. // in functions.
  6541. if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
  6542. if (T.getAddressSpace() == LangAS::opencl_constant)
  6543. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6544. << 0 /*non-kernel only*/ << "constant";
  6545. else
  6546. Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
  6547. << 0 /*non-kernel only*/ << "local";
  6548. NewVD->setInvalidDecl();
  6549. return;
  6550. }
  6551. // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
  6552. // in the outermost scope of a kernel function.
  6553. if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
  6554. if (!getCurScope()->isFunctionScope()) {
  6555. if (T.getAddressSpace() == LangAS::opencl_constant)
  6556. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6557. << "constant";
  6558. else
  6559. Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
  6560. << "local";
  6561. NewVD->setInvalidDecl();
  6562. return;
  6563. }
  6564. }
  6565. } else if (T.getAddressSpace() != LangAS::opencl_private) {
  6566. // Do not allow other address spaces on automatic variable.
  6567. Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
  6568. NewVD->setInvalidDecl();
  6569. return;
  6570. }
  6571. }
  6572. }
  6573. if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
  6574. && !NewVD->hasAttr<BlocksAttr>()) {
  6575. if (getLangOpts().getGC() != LangOptions::NonGC)
  6576. Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
  6577. else {
  6578. assert(!getLangOpts().ObjCAutoRefCount);
  6579. Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
  6580. }
  6581. }
  6582. bool isVM = T->isVariablyModifiedType();
  6583. if (isVM || NewVD->hasAttr<CleanupAttr>() ||
  6584. NewVD->hasAttr<BlocksAttr>())
  6585. setFunctionHasBranchProtectedScope();
  6586. if ((isVM && NewVD->hasLinkage()) ||
  6587. (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
  6588. bool SizeIsNegative;
  6589. llvm::APSInt Oversized;
  6590. TypeSourceInfo *FixedTInfo =
  6591. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  6592. SizeIsNegative, Oversized);
  6593. if (!FixedTInfo && T->isVariableArrayType()) {
  6594. const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
  6595. // FIXME: This won't give the correct result for
  6596. // int a[10][n];
  6597. SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
  6598. if (NewVD->isFileVarDecl())
  6599. Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
  6600. << SizeRange;
  6601. else if (NewVD->isStaticLocal())
  6602. Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
  6603. << SizeRange;
  6604. else
  6605. Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
  6606. << SizeRange;
  6607. NewVD->setInvalidDecl();
  6608. return;
  6609. }
  6610. if (!FixedTInfo) {
  6611. if (NewVD->isFileVarDecl())
  6612. Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
  6613. else
  6614. Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
  6615. NewVD->setInvalidDecl();
  6616. return;
  6617. }
  6618. Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
  6619. NewVD->setType(FixedTInfo->getType());
  6620. NewVD->setTypeSourceInfo(FixedTInfo);
  6621. }
  6622. if (T->isVoidType()) {
  6623. // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
  6624. // of objects and functions.
  6625. if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
  6626. Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
  6627. << T;
  6628. NewVD->setInvalidDecl();
  6629. return;
  6630. }
  6631. }
  6632. if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
  6633. Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
  6634. NewVD->setInvalidDecl();
  6635. return;
  6636. }
  6637. if (isVM && NewVD->hasAttr<BlocksAttr>()) {
  6638. Diag(NewVD->getLocation(), diag::err_block_on_vm);
  6639. NewVD->setInvalidDecl();
  6640. return;
  6641. }
  6642. if (NewVD->isConstexpr() && !T->isDependentType() &&
  6643. RequireLiteralType(NewVD->getLocation(), T,
  6644. diag::err_constexpr_var_non_literal)) {
  6645. NewVD->setInvalidDecl();
  6646. return;
  6647. }
  6648. }
  6649. /// Perform semantic checking on a newly-created variable
  6650. /// declaration.
  6651. ///
  6652. /// This routine performs all of the type-checking required for a
  6653. /// variable declaration once it has been built. It is used both to
  6654. /// check variables after they have been parsed and their declarators
  6655. /// have been translated into a declaration, and to check variables
  6656. /// that have been instantiated from a template.
  6657. ///
  6658. /// Sets NewVD->isInvalidDecl() if an error was encountered.
  6659. ///
  6660. /// Returns true if the variable declaration is a redeclaration.
  6661. bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
  6662. CheckVariableDeclarationType(NewVD);
  6663. // If the decl is already known invalid, don't check it.
  6664. if (NewVD->isInvalidDecl())
  6665. return false;
  6666. // If we did not find anything by this name, look for a non-visible
  6667. // extern "C" declaration with the same name.
  6668. if (Previous.empty() &&
  6669. checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
  6670. Previous.setShadowed();
  6671. if (!Previous.empty()) {
  6672. MergeVarDecl(NewVD, Previous);
  6673. return true;
  6674. }
  6675. return false;
  6676. }
  6677. namespace {
  6678. struct FindOverriddenMethod {
  6679. Sema *S;
  6680. CXXMethodDecl *Method;
  6681. /// Member lookup function that determines whether a given C++
  6682. /// method overrides a method in a base class, to be used with
  6683. /// CXXRecordDecl::lookupInBases().
  6684. bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
  6685. RecordDecl *BaseRecord =
  6686. Specifier->getType()->getAs<RecordType>()->getDecl();
  6687. DeclarationName Name = Method->getDeclName();
  6688. // FIXME: Do we care about other names here too?
  6689. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  6690. // We really want to find the base class destructor here.
  6691. QualType T = S->Context.getTypeDeclType(BaseRecord);
  6692. CanQualType CT = S->Context.getCanonicalType(T);
  6693. Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
  6694. }
  6695. for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
  6696. Path.Decls = Path.Decls.slice(1)) {
  6697. NamedDecl *D = Path.Decls.front();
  6698. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
  6699. if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
  6700. return true;
  6701. }
  6702. }
  6703. return false;
  6704. }
  6705. };
  6706. enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
  6707. } // end anonymous namespace
  6708. /// Report an error regarding overriding, along with any relevant
  6709. /// overridden methods.
  6710. ///
  6711. /// \param DiagID the primary error to report.
  6712. /// \param MD the overriding method.
  6713. /// \param OEK which overrides to include as notes.
  6714. static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
  6715. OverrideErrorKind OEK = OEK_All) {
  6716. S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
  6717. for (const CXXMethodDecl *O : MD->overridden_methods()) {
  6718. // This check (& the OEK parameter) could be replaced by a predicate, but
  6719. // without lambdas that would be overkill. This is still nicer than writing
  6720. // out the diag loop 3 times.
  6721. if ((OEK == OEK_All) ||
  6722. (OEK == OEK_NonDeleted && !O->isDeleted()) ||
  6723. (OEK == OEK_Deleted && O->isDeleted()))
  6724. S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
  6725. }
  6726. }
  6727. /// AddOverriddenMethods - See if a method overrides any in the base classes,
  6728. /// and if so, check that it's a valid override and remember it.
  6729. bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
  6730. // Look for methods in base classes that this method might override.
  6731. CXXBasePaths Paths;
  6732. FindOverriddenMethod FOM;
  6733. FOM.Method = MD;
  6734. FOM.S = this;
  6735. bool hasDeletedOverridenMethods = false;
  6736. bool hasNonDeletedOverridenMethods = false;
  6737. bool AddedAny = false;
  6738. if (DC->lookupInBases(FOM, Paths)) {
  6739. for (auto *I : Paths.found_decls()) {
  6740. if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
  6741. MD->addOverriddenMethod(OldMD->getCanonicalDecl());
  6742. if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
  6743. !CheckOverridingFunctionAttributes(MD, OldMD) &&
  6744. !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
  6745. !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
  6746. hasDeletedOverridenMethods |= OldMD->isDeleted();
  6747. hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
  6748. AddedAny = true;
  6749. }
  6750. }
  6751. }
  6752. }
  6753. if (hasDeletedOverridenMethods && !MD->isDeleted()) {
  6754. ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
  6755. }
  6756. if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
  6757. ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
  6758. }
  6759. return AddedAny;
  6760. }
  6761. namespace {
  6762. // Struct for holding all of the extra arguments needed by
  6763. // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
  6764. struct ActOnFDArgs {
  6765. Scope *S;
  6766. Declarator &D;
  6767. MultiTemplateParamsArg TemplateParamLists;
  6768. bool AddToScope;
  6769. };
  6770. } // end anonymous namespace
  6771. namespace {
  6772. // Callback to only accept typo corrections that have a non-zero edit distance.
  6773. // Also only accept corrections that have the same parent decl.
  6774. class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
  6775. public:
  6776. DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
  6777. CXXRecordDecl *Parent)
  6778. : Context(Context), OriginalFD(TypoFD),
  6779. ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
  6780. bool ValidateCandidate(const TypoCorrection &candidate) override {
  6781. if (candidate.getEditDistance() == 0)
  6782. return false;
  6783. SmallVector<unsigned, 1> MismatchedParams;
  6784. for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
  6785. CDeclEnd = candidate.end();
  6786. CDecl != CDeclEnd; ++CDecl) {
  6787. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6788. if (FD && !FD->hasBody() &&
  6789. hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
  6790. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  6791. CXXRecordDecl *Parent = MD->getParent();
  6792. if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
  6793. return true;
  6794. } else if (!ExpectedParent) {
  6795. return true;
  6796. }
  6797. }
  6798. }
  6799. return false;
  6800. }
  6801. private:
  6802. ASTContext &Context;
  6803. FunctionDecl *OriginalFD;
  6804. CXXRecordDecl *ExpectedParent;
  6805. };
  6806. } // end anonymous namespace
  6807. void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
  6808. TypoCorrectedFunctionDefinitions.insert(F);
  6809. }
  6810. /// Generate diagnostics for an invalid function redeclaration.
  6811. ///
  6812. /// This routine handles generating the diagnostic messages for an invalid
  6813. /// function redeclaration, including finding possible similar declarations
  6814. /// or performing typo correction if there are no previous declarations with
  6815. /// the same name.
  6816. ///
  6817. /// Returns a NamedDecl iff typo correction was performed and substituting in
  6818. /// the new declaration name does not cause new errors.
  6819. static NamedDecl *DiagnoseInvalidRedeclaration(
  6820. Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
  6821. ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
  6822. DeclarationName Name = NewFD->getDeclName();
  6823. DeclContext *NewDC = NewFD->getDeclContext();
  6824. SmallVector<unsigned, 1> MismatchedParams;
  6825. SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
  6826. TypoCorrection Correction;
  6827. bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
  6828. unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
  6829. : diag::err_member_decl_does_not_match;
  6830. LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
  6831. IsLocalFriend ? Sema::LookupLocalFriendName
  6832. : Sema::LookupOrdinaryName,
  6833. Sema::ForVisibleRedeclaration);
  6834. NewFD->setInvalidDecl();
  6835. if (IsLocalFriend)
  6836. SemaRef.LookupName(Prev, S);
  6837. else
  6838. SemaRef.LookupQualifiedName(Prev, NewDC);
  6839. assert(!Prev.isAmbiguous() &&
  6840. "Cannot have an ambiguity in previous-declaration lookup");
  6841. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  6842. if (!Prev.empty()) {
  6843. for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
  6844. Func != FuncEnd; ++Func) {
  6845. FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
  6846. if (FD &&
  6847. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6848. // Add 1 to the index so that 0 can mean the mismatch didn't
  6849. // involve a parameter
  6850. unsigned ParamNum =
  6851. MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
  6852. NearMatches.push_back(std::make_pair(FD, ParamNum));
  6853. }
  6854. }
  6855. // If the qualified name lookup yielded nothing, try typo correction
  6856. } else if ((Correction = SemaRef.CorrectTypo(
  6857. Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
  6858. &ExtraArgs.D.getCXXScopeSpec(),
  6859. llvm::make_unique<DifferentNameValidatorCCC>(
  6860. SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
  6861. Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
  6862. // Set up everything for the call to ActOnFunctionDeclarator
  6863. ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
  6864. ExtraArgs.D.getIdentifierLoc());
  6865. Previous.clear();
  6866. Previous.setLookupName(Correction.getCorrection());
  6867. for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
  6868. CDeclEnd = Correction.end();
  6869. CDecl != CDeclEnd; ++CDecl) {
  6870. FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
  6871. if (FD && !FD->hasBody() &&
  6872. hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
  6873. Previous.addDecl(FD);
  6874. }
  6875. }
  6876. bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
  6877. NamedDecl *Result;
  6878. // Retry building the function declaration with the new previous
  6879. // declarations, and with errors suppressed.
  6880. {
  6881. // Trap errors.
  6882. Sema::SFINAETrap Trap(SemaRef);
  6883. // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
  6884. // pieces need to verify the typo-corrected C++ declaration and hopefully
  6885. // eliminate the need for the parameter pack ExtraArgs.
  6886. Result = SemaRef.ActOnFunctionDeclarator(
  6887. ExtraArgs.S, ExtraArgs.D,
  6888. Correction.getCorrectionDecl()->getDeclContext(),
  6889. NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
  6890. ExtraArgs.AddToScope);
  6891. if (Trap.hasErrorOccurred())
  6892. Result = nullptr;
  6893. }
  6894. if (Result) {
  6895. // Determine which correction we picked.
  6896. Decl *Canonical = Result->getCanonicalDecl();
  6897. for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
  6898. I != E; ++I)
  6899. if ((*I)->getCanonicalDecl() == Canonical)
  6900. Correction.setCorrectionDecl(*I);
  6901. // Let Sema know about the correction.
  6902. SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
  6903. SemaRef.diagnoseTypo(
  6904. Correction,
  6905. SemaRef.PDiag(IsLocalFriend
  6906. ? diag::err_no_matching_local_friend_suggest
  6907. : diag::err_member_decl_does_not_match_suggest)
  6908. << Name << NewDC << IsDefinition);
  6909. return Result;
  6910. }
  6911. // Pretend the typo correction never occurred
  6912. ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
  6913. ExtraArgs.D.getIdentifierLoc());
  6914. ExtraArgs.D.setRedeclaration(wasRedeclaration);
  6915. Previous.clear();
  6916. Previous.setLookupName(Name);
  6917. }
  6918. SemaRef.Diag(NewFD->getLocation(), DiagMsg)
  6919. << Name << NewDC << IsDefinition << NewFD->getLocation();
  6920. bool NewFDisConst = false;
  6921. if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
  6922. NewFDisConst = NewMD->isConst();
  6923. for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
  6924. NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
  6925. NearMatch != NearMatchEnd; ++NearMatch) {
  6926. FunctionDecl *FD = NearMatch->first;
  6927. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
  6928. bool FDisConst = MD && MD->isConst();
  6929. bool IsMember = MD || !IsLocalFriend;
  6930. // FIXME: These notes are poorly worded for the local friend case.
  6931. if (unsigned Idx = NearMatch->second) {
  6932. ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
  6933. SourceLocation Loc = FDParam->getTypeSpecStartLoc();
  6934. if (Loc.isInvalid()) Loc = FD->getLocation();
  6935. SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
  6936. : diag::note_local_decl_close_param_match)
  6937. << Idx << FDParam->getType()
  6938. << NewFD->getParamDecl(Idx - 1)->getType();
  6939. } else if (FDisConst != NewFDisConst) {
  6940. SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
  6941. << NewFDisConst << FD->getSourceRange().getEnd();
  6942. } else
  6943. SemaRef.Diag(FD->getLocation(),
  6944. IsMember ? diag::note_member_def_close_match
  6945. : diag::note_local_decl_close_match);
  6946. }
  6947. return nullptr;
  6948. }
  6949. static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
  6950. switch (D.getDeclSpec().getStorageClassSpec()) {
  6951. default: llvm_unreachable("Unknown storage class!");
  6952. case DeclSpec::SCS_auto:
  6953. case DeclSpec::SCS_register:
  6954. case DeclSpec::SCS_mutable:
  6955. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6956. diag::err_typecheck_sclass_func);
  6957. D.getMutableDeclSpec().ClearStorageClassSpecs();
  6958. D.setInvalidType();
  6959. break;
  6960. case DeclSpec::SCS_unspecified: break;
  6961. case DeclSpec::SCS_extern:
  6962. if (D.getDeclSpec().isExternInLinkageSpec())
  6963. return SC_None;
  6964. return SC_Extern;
  6965. case DeclSpec::SCS_static: {
  6966. if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
  6967. // C99 6.7.1p5:
  6968. // The declaration of an identifier for a function that has
  6969. // block scope shall have no explicit storage-class specifier
  6970. // other than extern
  6971. // See also (C++ [dcl.stc]p4).
  6972. SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  6973. diag::err_static_block_func);
  6974. break;
  6975. } else
  6976. return SC_Static;
  6977. }
  6978. case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
  6979. }
  6980. // No explicit storage class has already been returned
  6981. return SC_None;
  6982. }
  6983. static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
  6984. DeclContext *DC, QualType &R,
  6985. TypeSourceInfo *TInfo,
  6986. StorageClass SC,
  6987. bool &IsVirtualOkay) {
  6988. DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
  6989. DeclarationName Name = NameInfo.getName();
  6990. FunctionDecl *NewFD = nullptr;
  6991. bool isInline = D.getDeclSpec().isInlineSpecified();
  6992. if (!SemaRef.getLangOpts().CPlusPlus) {
  6993. // Determine whether the function was written with a
  6994. // prototype. This true when:
  6995. // - there is a prototype in the declarator, or
  6996. // - the type R of the function is some kind of typedef or other non-
  6997. // attributed reference to a type name (which eventually refers to a
  6998. // function type).
  6999. bool HasPrototype =
  7000. (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
  7001. (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
  7002. NewFD = FunctionDecl::Create(SemaRef.Context, DC,
  7003. D.getLocStart(), NameInfo, R,
  7004. TInfo, SC, isInline,
  7005. HasPrototype, false);
  7006. if (D.isInvalidType())
  7007. NewFD->setInvalidDecl();
  7008. return NewFD;
  7009. }
  7010. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7011. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7012. // Check that the return type is not an abstract class type.
  7013. // For record types, this is done by the AbstractClassUsageDiagnoser once
  7014. // the class has been completely parsed.
  7015. if (!DC->isRecord() &&
  7016. SemaRef.RequireNonAbstractType(
  7017. D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
  7018. diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
  7019. D.setInvalidType();
  7020. if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
  7021. // This is a C++ constructor declaration.
  7022. assert(DC->isRecord() &&
  7023. "Constructors can only be declared in a member context");
  7024. R = SemaRef.CheckConstructorDeclarator(D, R, SC);
  7025. return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7026. D.getLocStart(), NameInfo,
  7027. R, TInfo, isExplicit, isInline,
  7028. /*isImplicitlyDeclared=*/false,
  7029. isConstexpr);
  7030. } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7031. // This is a C++ destructor declaration.
  7032. if (DC->isRecord()) {
  7033. R = SemaRef.CheckDestructorDeclarator(D, R, SC);
  7034. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  7035. CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
  7036. SemaRef.Context, Record,
  7037. D.getLocStart(),
  7038. NameInfo, R, TInfo, isInline,
  7039. /*isImplicitlyDeclared=*/false);
  7040. // If the class is complete, then we now create the implicit exception
  7041. // specification. If the class is incomplete or dependent, we can't do
  7042. // it yet.
  7043. if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
  7044. Record->getDefinition() && !Record->isBeingDefined() &&
  7045. R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
  7046. SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
  7047. }
  7048. IsVirtualOkay = true;
  7049. return NewDD;
  7050. } else {
  7051. SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
  7052. D.setInvalidType();
  7053. // Create a FunctionDecl to satisfy the function definition parsing
  7054. // code path.
  7055. return FunctionDecl::Create(SemaRef.Context, DC,
  7056. D.getLocStart(),
  7057. D.getIdentifierLoc(), Name, R, TInfo,
  7058. SC, isInline,
  7059. /*hasPrototype=*/true, isConstexpr);
  7060. }
  7061. } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  7062. if (!DC->isRecord()) {
  7063. SemaRef.Diag(D.getIdentifierLoc(),
  7064. diag::err_conv_function_not_member);
  7065. return nullptr;
  7066. }
  7067. SemaRef.CheckConversionDeclarator(D, R, SC);
  7068. IsVirtualOkay = true;
  7069. return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
  7070. D.getLocStart(), NameInfo,
  7071. R, TInfo, isInline, isExplicit,
  7072. isConstexpr, SourceLocation());
  7073. } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
  7074. SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
  7075. return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
  7076. isExplicit, NameInfo, R, TInfo,
  7077. D.getLocEnd());
  7078. } else if (DC->isRecord()) {
  7079. // If the name of the function is the same as the name of the record,
  7080. // then this must be an invalid constructor that has a return type.
  7081. // (The parser checks for a return type and makes the declarator a
  7082. // constructor if it has no return type).
  7083. if (Name.getAsIdentifierInfo() &&
  7084. Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
  7085. SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
  7086. << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
  7087. << SourceRange(D.getIdentifierLoc());
  7088. return nullptr;
  7089. }
  7090. // This is a C++ method declaration.
  7091. CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
  7092. cast<CXXRecordDecl>(DC),
  7093. D.getLocStart(), NameInfo, R,
  7094. TInfo, SC, isInline,
  7095. isConstexpr, SourceLocation());
  7096. IsVirtualOkay = !Ret->isStatic();
  7097. return Ret;
  7098. } else {
  7099. bool isFriend =
  7100. SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
  7101. if (!isFriend && SemaRef.CurContext->isRecord())
  7102. return nullptr;
  7103. // Determine whether the function was written with a
  7104. // prototype. This true when:
  7105. // - we're in C++ (where every function has a prototype),
  7106. return FunctionDecl::Create(SemaRef.Context, DC,
  7107. D.getLocStart(),
  7108. NameInfo, R, TInfo, SC, isInline,
  7109. true/*HasPrototype*/, isConstexpr);
  7110. }
  7111. }
  7112. enum OpenCLParamType {
  7113. ValidKernelParam,
  7114. PtrPtrKernelParam,
  7115. PtrKernelParam,
  7116. InvalidAddrSpacePtrKernelParam,
  7117. InvalidKernelParam,
  7118. RecordKernelParam
  7119. };
  7120. static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
  7121. if (PT->isPointerType()) {
  7122. QualType PointeeType = PT->getPointeeType();
  7123. if (PointeeType->isPointerType())
  7124. return PtrPtrKernelParam;
  7125. if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
  7126. PointeeType.getAddressSpace() == LangAS::opencl_private ||
  7127. PointeeType.getAddressSpace() == LangAS::Default)
  7128. return InvalidAddrSpacePtrKernelParam;
  7129. return PtrKernelParam;
  7130. }
  7131. // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
  7132. // be used as builtin types.
  7133. if (PT->isImageType())
  7134. return PtrKernelParam;
  7135. if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
  7136. return InvalidKernelParam;
  7137. // OpenCL extension spec v1.2 s9.5:
  7138. // This extension adds support for half scalar and vector types as built-in
  7139. // types that can be used for arithmetic operations, conversions etc.
  7140. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
  7141. return InvalidKernelParam;
  7142. if (PT->isRecordType())
  7143. return RecordKernelParam;
  7144. return ValidKernelParam;
  7145. }
  7146. static void checkIsValidOpenCLKernelParameter(
  7147. Sema &S,
  7148. Declarator &D,
  7149. ParmVarDecl *Param,
  7150. llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
  7151. QualType PT = Param->getType();
  7152. // Cache the valid types we encounter to avoid rechecking structs that are
  7153. // used again
  7154. if (ValidTypes.count(PT.getTypePtr()))
  7155. return;
  7156. switch (getOpenCLKernelParameterType(S, PT)) {
  7157. case PtrPtrKernelParam:
  7158. // OpenCL v1.2 s6.9.a:
  7159. // A kernel function argument cannot be declared as a
  7160. // pointer to a pointer type.
  7161. S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
  7162. D.setInvalidType();
  7163. return;
  7164. case InvalidAddrSpacePtrKernelParam:
  7165. // OpenCL v1.0 s6.5:
  7166. // __kernel function arguments declared to be a pointer of a type can point
  7167. // to one of the following address spaces only : __global, __local or
  7168. // __constant.
  7169. S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
  7170. D.setInvalidType();
  7171. return;
  7172. // OpenCL v1.2 s6.9.k:
  7173. // Arguments to kernel functions in a program cannot be declared with the
  7174. // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
  7175. // uintptr_t or a struct and/or union that contain fields declared to be
  7176. // one of these built-in scalar types.
  7177. case InvalidKernelParam:
  7178. // OpenCL v1.2 s6.8 n:
  7179. // A kernel function argument cannot be declared
  7180. // of event_t type.
  7181. // Do not diagnose half type since it is diagnosed as invalid argument
  7182. // type for any function elsewhere.
  7183. if (!PT->isHalfType())
  7184. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7185. D.setInvalidType();
  7186. return;
  7187. case PtrKernelParam:
  7188. case ValidKernelParam:
  7189. ValidTypes.insert(PT.getTypePtr());
  7190. return;
  7191. case RecordKernelParam:
  7192. break;
  7193. }
  7194. // Track nested structs we will inspect
  7195. SmallVector<const Decl *, 4> VisitStack;
  7196. // Track where we are in the nested structs. Items will migrate from
  7197. // VisitStack to HistoryStack as we do the DFS for bad field.
  7198. SmallVector<const FieldDecl *, 4> HistoryStack;
  7199. HistoryStack.push_back(nullptr);
  7200. const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
  7201. VisitStack.push_back(PD);
  7202. assert(VisitStack.back() && "First decl null?");
  7203. do {
  7204. const Decl *Next = VisitStack.pop_back_val();
  7205. if (!Next) {
  7206. assert(!HistoryStack.empty());
  7207. // Found a marker, we have gone up a level
  7208. if (const FieldDecl *Hist = HistoryStack.pop_back_val())
  7209. ValidTypes.insert(Hist->getType().getTypePtr());
  7210. continue;
  7211. }
  7212. // Adds everything except the original parameter declaration (which is not a
  7213. // field itself) to the history stack.
  7214. const RecordDecl *RD;
  7215. if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
  7216. HistoryStack.push_back(Field);
  7217. RD = Field->getType()->castAs<RecordType>()->getDecl();
  7218. } else {
  7219. RD = cast<RecordDecl>(Next);
  7220. }
  7221. // Add a null marker so we know when we've gone back up a level
  7222. VisitStack.push_back(nullptr);
  7223. for (const auto *FD : RD->fields()) {
  7224. QualType QT = FD->getType();
  7225. if (ValidTypes.count(QT.getTypePtr()))
  7226. continue;
  7227. OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
  7228. if (ParamType == ValidKernelParam)
  7229. continue;
  7230. if (ParamType == RecordKernelParam) {
  7231. VisitStack.push_back(FD);
  7232. continue;
  7233. }
  7234. // OpenCL v1.2 s6.9.p:
  7235. // Arguments to kernel functions that are declared to be a struct or union
  7236. // do not allow OpenCL objects to be passed as elements of the struct or
  7237. // union.
  7238. if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
  7239. ParamType == InvalidAddrSpacePtrKernelParam) {
  7240. S.Diag(Param->getLocation(),
  7241. diag::err_record_with_pointers_kernel_param)
  7242. << PT->isUnionType()
  7243. << PT;
  7244. } else {
  7245. S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
  7246. }
  7247. S.Diag(PD->getLocation(), diag::note_within_field_of_type)
  7248. << PD->getDeclName();
  7249. // We have an error, now let's go back up through history and show where
  7250. // the offending field came from
  7251. for (ArrayRef<const FieldDecl *>::const_iterator
  7252. I = HistoryStack.begin() + 1,
  7253. E = HistoryStack.end();
  7254. I != E; ++I) {
  7255. const FieldDecl *OuterField = *I;
  7256. S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
  7257. << OuterField->getType();
  7258. }
  7259. S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
  7260. << QT->isPointerType()
  7261. << QT;
  7262. D.setInvalidType();
  7263. return;
  7264. }
  7265. } while (!VisitStack.empty());
  7266. }
  7267. /// Find the DeclContext in which a tag is implicitly declared if we see an
  7268. /// elaborated type specifier in the specified context, and lookup finds
  7269. /// nothing.
  7270. static DeclContext *getTagInjectionContext(DeclContext *DC) {
  7271. while (!DC->isFileContext() && !DC->isFunctionOrMethod())
  7272. DC = DC->getParent();
  7273. return DC;
  7274. }
  7275. /// Find the Scope in which a tag is implicitly declared if we see an
  7276. /// elaborated type specifier in the specified context, and lookup finds
  7277. /// nothing.
  7278. static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
  7279. while (S->isClassScope() ||
  7280. (LangOpts.CPlusPlus &&
  7281. S->isFunctionPrototypeScope()) ||
  7282. ((S->getFlags() & Scope::DeclScope) == 0) ||
  7283. (S->getEntity() && S->getEntity()->isTransparentContext()))
  7284. S = S->getParent();
  7285. return S;
  7286. }
  7287. NamedDecl*
  7288. Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
  7289. TypeSourceInfo *TInfo, LookupResult &Previous,
  7290. MultiTemplateParamsArg TemplateParamLists,
  7291. bool &AddToScope) {
  7292. QualType R = TInfo->getType();
  7293. assert(R.getTypePtr()->isFunctionType());
  7294. // TODO: consider using NameInfo for diagnostic.
  7295. DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
  7296. DeclarationName Name = NameInfo.getName();
  7297. StorageClass SC = getFunctionStorageClass(*this, D);
  7298. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  7299. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  7300. diag::err_invalid_thread)
  7301. << DeclSpec::getSpecifierName(TSCS);
  7302. if (D.isFirstDeclarationOfMember())
  7303. adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
  7304. D.getIdentifierLoc());
  7305. bool isFriend = false;
  7306. FunctionTemplateDecl *FunctionTemplate = nullptr;
  7307. bool isMemberSpecialization = false;
  7308. bool isFunctionTemplateSpecialization = false;
  7309. bool isDependentClassScopeExplicitSpecialization = false;
  7310. bool HasExplicitTemplateArgs = false;
  7311. TemplateArgumentListInfo TemplateArgs;
  7312. bool isVirtualOkay = false;
  7313. DeclContext *OriginalDC = DC;
  7314. bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
  7315. FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
  7316. isVirtualOkay);
  7317. if (!NewFD) return nullptr;
  7318. if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
  7319. NewFD->setTopLevelDeclInObjCContainer();
  7320. // Set the lexical context. If this is a function-scope declaration, or has a
  7321. // C++ scope specifier, or is the object of a friend declaration, the lexical
  7322. // context will be different from the semantic context.
  7323. NewFD->setLexicalDeclContext(CurContext);
  7324. if (IsLocalExternDecl)
  7325. NewFD->setLocalExternDecl();
  7326. if (getLangOpts().CPlusPlus) {
  7327. bool isInline = D.getDeclSpec().isInlineSpecified();
  7328. bool isVirtual = D.getDeclSpec().isVirtualSpecified();
  7329. bool isExplicit = D.getDeclSpec().isExplicitSpecified();
  7330. bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
  7331. isFriend = D.getDeclSpec().isFriendSpecified();
  7332. if (isFriend && !isInline && D.isFunctionDefinition()) {
  7333. // C++ [class.friend]p5
  7334. // A function can be defined in a friend declaration of a
  7335. // class . . . . Such a function is implicitly inline.
  7336. NewFD->setImplicitlyInline();
  7337. }
  7338. // If this is a method defined in an __interface, and is not a constructor
  7339. // or an overloaded operator, then set the pure flag (isVirtual will already
  7340. // return true).
  7341. if (const CXXRecordDecl *Parent =
  7342. dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
  7343. if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
  7344. NewFD->setPure(true);
  7345. // C++ [class.union]p2
  7346. // A union can have member functions, but not virtual functions.
  7347. if (isVirtual && Parent->isUnion())
  7348. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
  7349. }
  7350. SetNestedNameSpecifier(NewFD, D);
  7351. isMemberSpecialization = false;
  7352. isFunctionTemplateSpecialization = false;
  7353. if (D.isInvalidType())
  7354. NewFD->setInvalidDecl();
  7355. // Match up the template parameter lists with the scope specifier, then
  7356. // determine whether we have a template or a template specialization.
  7357. bool Invalid = false;
  7358. if (TemplateParameterList *TemplateParams =
  7359. MatchTemplateParametersToScopeSpecifier(
  7360. D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
  7361. D.getCXXScopeSpec(),
  7362. D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
  7363. ? D.getName().TemplateId
  7364. : nullptr,
  7365. TemplateParamLists, isFriend, isMemberSpecialization,
  7366. Invalid)) {
  7367. if (TemplateParams->size() > 0) {
  7368. // This is a function template
  7369. // Check that we can declare a template here.
  7370. if (CheckTemplateDeclScope(S, TemplateParams))
  7371. NewFD->setInvalidDecl();
  7372. // A destructor cannot be a template.
  7373. if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
  7374. Diag(NewFD->getLocation(), diag::err_destructor_template);
  7375. NewFD->setInvalidDecl();
  7376. }
  7377. // If we're adding a template to a dependent context, we may need to
  7378. // rebuilding some of the types used within the template parameter list,
  7379. // now that we know what the current instantiation is.
  7380. if (DC->isDependentContext()) {
  7381. ContextRAII SavedContext(*this, DC);
  7382. if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
  7383. Invalid = true;
  7384. }
  7385. FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
  7386. NewFD->getLocation(),
  7387. Name, TemplateParams,
  7388. NewFD);
  7389. FunctionTemplate->setLexicalDeclContext(CurContext);
  7390. NewFD->setDescribedFunctionTemplate(FunctionTemplate);
  7391. // For source fidelity, store the other template param lists.
  7392. if (TemplateParamLists.size() > 1) {
  7393. NewFD->setTemplateParameterListsInfo(Context,
  7394. TemplateParamLists.drop_back(1));
  7395. }
  7396. } else {
  7397. // This is a function template specialization.
  7398. isFunctionTemplateSpecialization = true;
  7399. // For source fidelity, store all the template param lists.
  7400. if (TemplateParamLists.size() > 0)
  7401. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7402. // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
  7403. if (isFriend) {
  7404. // We want to remove the "template<>", found here.
  7405. SourceRange RemoveRange = TemplateParams->getSourceRange();
  7406. // If we remove the template<> and the name is not a
  7407. // template-id, we're actually silently creating a problem:
  7408. // the friend declaration will refer to an untemplated decl,
  7409. // and clearly the user wants a template specialization. So
  7410. // we need to insert '<>' after the name.
  7411. SourceLocation InsertLoc;
  7412. if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
  7413. InsertLoc = D.getName().getSourceRange().getEnd();
  7414. InsertLoc = getLocForEndOfToken(InsertLoc);
  7415. }
  7416. Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
  7417. << Name << RemoveRange
  7418. << FixItHint::CreateRemoval(RemoveRange)
  7419. << FixItHint::CreateInsertion(InsertLoc, "<>");
  7420. }
  7421. }
  7422. }
  7423. else {
  7424. // All template param lists were matched against the scope specifier:
  7425. // this is NOT (an explicit specialization of) a template.
  7426. if (TemplateParamLists.size() > 0)
  7427. // For source fidelity, store all the template param lists.
  7428. NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
  7429. }
  7430. if (Invalid) {
  7431. NewFD->setInvalidDecl();
  7432. if (FunctionTemplate)
  7433. FunctionTemplate->setInvalidDecl();
  7434. }
  7435. // C++ [dcl.fct.spec]p5:
  7436. // The virtual specifier shall only be used in declarations of
  7437. // nonstatic class member functions that appear within a
  7438. // member-specification of a class declaration; see 10.3.
  7439. //
  7440. if (isVirtual && !NewFD->isInvalidDecl()) {
  7441. if (!isVirtualOkay) {
  7442. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7443. diag::err_virtual_non_function);
  7444. } else if (!CurContext->isRecord()) {
  7445. // 'virtual' was specified outside of the class.
  7446. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7447. diag::err_virtual_out_of_class)
  7448. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7449. } else if (NewFD->getDescribedFunctionTemplate()) {
  7450. // C++ [temp.mem]p3:
  7451. // A member function template shall not be virtual.
  7452. Diag(D.getDeclSpec().getVirtualSpecLoc(),
  7453. diag::err_virtual_member_function_template)
  7454. << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
  7455. } else {
  7456. // Okay: Add virtual to the method.
  7457. NewFD->setVirtualAsWritten(true);
  7458. }
  7459. if (getLangOpts().CPlusPlus14 &&
  7460. NewFD->getReturnType()->isUndeducedType())
  7461. Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
  7462. }
  7463. if (getLangOpts().CPlusPlus14 &&
  7464. (NewFD->isDependentContext() ||
  7465. (isFriend && CurContext->isDependentContext())) &&
  7466. NewFD->getReturnType()->isUndeducedType()) {
  7467. // If the function template is referenced directly (for instance, as a
  7468. // member of the current instantiation), pretend it has a dependent type.
  7469. // This is not really justified by the standard, but is the only sane
  7470. // thing to do.
  7471. // FIXME: For a friend function, we have not marked the function as being
  7472. // a friend yet, so 'isDependentContext' on the FD doesn't work.
  7473. const FunctionProtoType *FPT =
  7474. NewFD->getType()->castAs<FunctionProtoType>();
  7475. QualType Result =
  7476. SubstAutoType(FPT->getReturnType(), Context.DependentTy);
  7477. NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
  7478. FPT->getExtProtoInfo()));
  7479. }
  7480. // C++ [dcl.fct.spec]p3:
  7481. // The inline specifier shall not appear on a block scope function
  7482. // declaration.
  7483. if (isInline && !NewFD->isInvalidDecl()) {
  7484. if (CurContext->isFunctionOrMethod()) {
  7485. // 'inline' is not allowed on block scope function declaration.
  7486. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7487. diag::err_inline_declaration_block_scope) << Name
  7488. << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
  7489. }
  7490. }
  7491. // C++ [dcl.fct.spec]p6:
  7492. // The explicit specifier shall be used only in the declaration of a
  7493. // constructor or conversion function within its class definition;
  7494. // see 12.3.1 and 12.3.2.
  7495. if (isExplicit && !NewFD->isInvalidDecl() &&
  7496. !isa<CXXDeductionGuideDecl>(NewFD)) {
  7497. if (!CurContext->isRecord()) {
  7498. // 'explicit' was specified outside of the class.
  7499. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7500. diag::err_explicit_out_of_class)
  7501. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7502. } else if (!isa<CXXConstructorDecl>(NewFD) &&
  7503. !isa<CXXConversionDecl>(NewFD)) {
  7504. // 'explicit' was specified on a function that wasn't a constructor
  7505. // or conversion function.
  7506. Diag(D.getDeclSpec().getExplicitSpecLoc(),
  7507. diag::err_explicit_non_ctor_or_conv_function)
  7508. << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
  7509. }
  7510. }
  7511. if (isConstexpr) {
  7512. // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
  7513. // are implicitly inline.
  7514. NewFD->setImplicitlyInline();
  7515. // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
  7516. // be either constructors or to return a literal type. Therefore,
  7517. // destructors cannot be declared constexpr.
  7518. if (isa<CXXDestructorDecl>(NewFD))
  7519. Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
  7520. }
  7521. // If __module_private__ was specified, mark the function accordingly.
  7522. if (D.getDeclSpec().isModulePrivateSpecified()) {
  7523. if (isFunctionTemplateSpecialization) {
  7524. SourceLocation ModulePrivateLoc
  7525. = D.getDeclSpec().getModulePrivateSpecLoc();
  7526. Diag(ModulePrivateLoc, diag::err_module_private_specialization)
  7527. << 0
  7528. << FixItHint::CreateRemoval(ModulePrivateLoc);
  7529. } else {
  7530. NewFD->setModulePrivate();
  7531. if (FunctionTemplate)
  7532. FunctionTemplate->setModulePrivate();
  7533. }
  7534. }
  7535. if (isFriend) {
  7536. if (FunctionTemplate) {
  7537. FunctionTemplate->setObjectOfFriendDecl();
  7538. FunctionTemplate->setAccess(AS_public);
  7539. }
  7540. NewFD->setObjectOfFriendDecl();
  7541. NewFD->setAccess(AS_public);
  7542. }
  7543. // If a function is defined as defaulted or deleted, mark it as such now.
  7544. // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
  7545. // definition kind to FDK_Definition.
  7546. switch (D.getFunctionDefinitionKind()) {
  7547. case FDK_Declaration:
  7548. case FDK_Definition:
  7549. break;
  7550. case FDK_Defaulted:
  7551. NewFD->setDefaulted();
  7552. break;
  7553. case FDK_Deleted:
  7554. NewFD->setDeletedAsWritten();
  7555. break;
  7556. }
  7557. if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
  7558. D.isFunctionDefinition()) {
  7559. // C++ [class.mfct]p2:
  7560. // A member function may be defined (8.4) in its class definition, in
  7561. // which case it is an inline member function (7.1.2)
  7562. NewFD->setImplicitlyInline();
  7563. }
  7564. if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
  7565. !CurContext->isRecord()) {
  7566. // C++ [class.static]p1:
  7567. // A data or function member of a class may be declared static
  7568. // in a class definition, in which case it is a static member of
  7569. // the class.
  7570. // Complain about the 'static' specifier if it's on an out-of-line
  7571. // member function definition.
  7572. Diag(D.getDeclSpec().getStorageClassSpecLoc(),
  7573. diag::err_static_out_of_line)
  7574. << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
  7575. }
  7576. // C++11 [except.spec]p15:
  7577. // A deallocation function with no exception-specification is treated
  7578. // as if it were specified with noexcept(true).
  7579. const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
  7580. if ((Name.getCXXOverloadedOperator() == OO_Delete ||
  7581. Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
  7582. getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
  7583. NewFD->setType(Context.getFunctionType(
  7584. FPT->getReturnType(), FPT->getParamTypes(),
  7585. FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
  7586. }
  7587. // Filter out previous declarations that don't match the scope.
  7588. FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
  7589. D.getCXXScopeSpec().isNotEmpty() ||
  7590. isMemberSpecialization ||
  7591. isFunctionTemplateSpecialization);
  7592. // Handle GNU asm-label extension (encoded as an attribute).
  7593. if (Expr *E = (Expr*) D.getAsmLabel()) {
  7594. // The parser guarantees this is a string.
  7595. StringLiteral *SE = cast<StringLiteral>(E);
  7596. NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
  7597. SE->getString(), 0));
  7598. } else if (!ExtnameUndeclaredIdentifiers.empty()) {
  7599. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
  7600. ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
  7601. if (I != ExtnameUndeclaredIdentifiers.end()) {
  7602. if (isDeclExternC(NewFD)) {
  7603. NewFD->addAttr(I->second);
  7604. ExtnameUndeclaredIdentifiers.erase(I);
  7605. } else
  7606. Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
  7607. << /*Variable*/0 << NewFD;
  7608. }
  7609. }
  7610. // Copy the parameter declarations from the declarator D to the function
  7611. // declaration NewFD, if they are available. First scavenge them into Params.
  7612. SmallVector<ParmVarDecl*, 16> Params;
  7613. unsigned FTIIdx;
  7614. if (D.isFunctionDeclarator(FTIIdx)) {
  7615. DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
  7616. // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
  7617. // function that takes no arguments, not a function that takes a
  7618. // single void argument.
  7619. // We let through "const void" here because Sema::GetTypeForDeclarator
  7620. // already checks for that case.
  7621. if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
  7622. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  7623. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  7624. assert(Param->getDeclContext() != NewFD && "Was set before ?");
  7625. Param->setDeclContext(NewFD);
  7626. Params.push_back(Param);
  7627. if (Param->isInvalidDecl())
  7628. NewFD->setInvalidDecl();
  7629. }
  7630. }
  7631. if (!getLangOpts().CPlusPlus) {
  7632. // In C, find all the tag declarations from the prototype and move them
  7633. // into the function DeclContext. Remove them from the surrounding tag
  7634. // injection context of the function, which is typically but not always
  7635. // the TU.
  7636. DeclContext *PrototypeTagContext =
  7637. getTagInjectionContext(NewFD->getLexicalDeclContext());
  7638. for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
  7639. auto *TD = dyn_cast<TagDecl>(NonParmDecl);
  7640. // We don't want to reparent enumerators. Look at their parent enum
  7641. // instead.
  7642. if (!TD) {
  7643. if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
  7644. TD = cast<EnumDecl>(ECD->getDeclContext());
  7645. }
  7646. if (!TD)
  7647. continue;
  7648. DeclContext *TagDC = TD->getLexicalDeclContext();
  7649. if (!TagDC->containsDecl(TD))
  7650. continue;
  7651. TagDC->removeDecl(TD);
  7652. TD->setDeclContext(NewFD);
  7653. NewFD->addDecl(TD);
  7654. // Preserve the lexical DeclContext if it is not the surrounding tag
  7655. // injection context of the FD. In this example, the semantic context of
  7656. // E will be f and the lexical context will be S, while both the
  7657. // semantic and lexical contexts of S will be f:
  7658. // void f(struct S { enum E { a } f; } s);
  7659. if (TagDC != PrototypeTagContext)
  7660. TD->setLexicalDeclContext(TagDC);
  7661. }
  7662. }
  7663. } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
  7664. // When we're declaring a function with a typedef, typeof, etc as in the
  7665. // following example, we'll need to synthesize (unnamed)
  7666. // parameters for use in the declaration.
  7667. //
  7668. // @code
  7669. // typedef void fn(int);
  7670. // fn f;
  7671. // @endcode
  7672. // Synthesize a parameter for each argument type.
  7673. for (const auto &AI : FT->param_types()) {
  7674. ParmVarDecl *Param =
  7675. BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
  7676. Param->setScopeInfo(0, Params.size());
  7677. Params.push_back(Param);
  7678. }
  7679. } else {
  7680. assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
  7681. "Should not need args for typedef of non-prototype fn");
  7682. }
  7683. // Finally, we know we have the right number of parameters, install them.
  7684. NewFD->setParams(Params);
  7685. if (D.getDeclSpec().isNoreturnSpecified())
  7686. NewFD->addAttr(
  7687. ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
  7688. Context, 0));
  7689. // Functions returning a variably modified type violate C99 6.7.5.2p2
  7690. // because all functions have linkage.
  7691. if (!NewFD->isInvalidDecl() &&
  7692. NewFD->getReturnType()->isVariablyModifiedType()) {
  7693. Diag(NewFD->getLocation(), diag::err_vm_func_decl);
  7694. NewFD->setInvalidDecl();
  7695. }
  7696. // Apply an implicit SectionAttr if '#pragma clang section text' is active
  7697. if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
  7698. !NewFD->hasAttr<SectionAttr>()) {
  7699. NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
  7700. PragmaClangTextSection.SectionName,
  7701. PragmaClangTextSection.PragmaLocation));
  7702. }
  7703. // Apply an implicit SectionAttr if #pragma code_seg is active.
  7704. if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
  7705. !NewFD->hasAttr<SectionAttr>()) {
  7706. NewFD->addAttr(
  7707. SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
  7708. CodeSegStack.CurrentValue->getString(),
  7709. CodeSegStack.CurrentPragmaLocation));
  7710. if (UnifySection(CodeSegStack.CurrentValue->getString(),
  7711. ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
  7712. ASTContext::PSF_Read,
  7713. NewFD))
  7714. NewFD->dropAttr<SectionAttr>();
  7715. }
  7716. // Handle attributes.
  7717. ProcessDeclAttributes(S, NewFD, D);
  7718. if (getLangOpts().OpenCL) {
  7719. // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
  7720. // type declaration will generate a compilation error.
  7721. LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
  7722. if (AddressSpace != LangAS::Default) {
  7723. Diag(NewFD->getLocation(),
  7724. diag::err_opencl_return_value_with_address_space);
  7725. NewFD->setInvalidDecl();
  7726. }
  7727. }
  7728. if (!getLangOpts().CPlusPlus) {
  7729. // Perform semantic checking on the function declaration.
  7730. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7731. CheckMain(NewFD, D.getDeclSpec());
  7732. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7733. CheckMSVCRTEntryPoint(NewFD);
  7734. if (!NewFD->isInvalidDecl())
  7735. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7736. isMemberSpecialization));
  7737. else if (!Previous.empty())
  7738. // Recover gracefully from an invalid redeclaration.
  7739. D.setRedeclaration(true);
  7740. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7741. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7742. "previous declaration set still overloaded");
  7743. // Diagnose no-prototype function declarations with calling conventions that
  7744. // don't support variadic calls. Only do this in C and do it after merging
  7745. // possibly prototyped redeclarations.
  7746. const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
  7747. if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
  7748. CallingConv CC = FT->getExtInfo().getCC();
  7749. if (!supportsVariadicCall(CC)) {
  7750. // Windows system headers sometimes accidentally use stdcall without
  7751. // (void) parameters, so we relax this to a warning.
  7752. int DiagID =
  7753. CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
  7754. Diag(NewFD->getLocation(), DiagID)
  7755. << FunctionType::getNameForCallConv(CC);
  7756. }
  7757. }
  7758. } else {
  7759. // C++11 [replacement.functions]p3:
  7760. // The program's definitions shall not be specified as inline.
  7761. //
  7762. // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
  7763. //
  7764. // Suppress the diagnostic if the function is __attribute__((used)), since
  7765. // that forces an external definition to be emitted.
  7766. if (D.getDeclSpec().isInlineSpecified() &&
  7767. NewFD->isReplaceableGlobalAllocationFunction() &&
  7768. !NewFD->hasAttr<UsedAttr>())
  7769. Diag(D.getDeclSpec().getInlineSpecLoc(),
  7770. diag::ext_operator_new_delete_declared_inline)
  7771. << NewFD->getDeclName();
  7772. // If the declarator is a template-id, translate the parser's template
  7773. // argument list into our AST format.
  7774. if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
  7775. TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
  7776. TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
  7777. TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
  7778. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
  7779. TemplateId->NumArgs);
  7780. translateTemplateArguments(TemplateArgsPtr,
  7781. TemplateArgs);
  7782. HasExplicitTemplateArgs = true;
  7783. if (NewFD->isInvalidDecl()) {
  7784. HasExplicitTemplateArgs = false;
  7785. } else if (FunctionTemplate) {
  7786. // Function template with explicit template arguments.
  7787. Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
  7788. << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
  7789. HasExplicitTemplateArgs = false;
  7790. } else {
  7791. assert((isFunctionTemplateSpecialization ||
  7792. D.getDeclSpec().isFriendSpecified()) &&
  7793. "should have a 'template<>' for this decl");
  7794. // "friend void foo<>(int);" is an implicit specialization decl.
  7795. isFunctionTemplateSpecialization = true;
  7796. }
  7797. } else if (isFriend && isFunctionTemplateSpecialization) {
  7798. // This combination is only possible in a recovery case; the user
  7799. // wrote something like:
  7800. // template <> friend void foo(int);
  7801. // which we're recovering from as if the user had written:
  7802. // friend void foo<>(int);
  7803. // Go ahead and fake up a template id.
  7804. HasExplicitTemplateArgs = true;
  7805. TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
  7806. TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
  7807. }
  7808. // We do not add HD attributes to specializations here because
  7809. // they may have different constexpr-ness compared to their
  7810. // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
  7811. // may end up with different effective targets. Instead, a
  7812. // specialization inherits its target attributes from its template
  7813. // in the CheckFunctionTemplateSpecialization() call below.
  7814. if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
  7815. maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
  7816. // If it's a friend (and only if it's a friend), it's possible
  7817. // that either the specialized function type or the specialized
  7818. // template is dependent, and therefore matching will fail. In
  7819. // this case, don't check the specialization yet.
  7820. bool InstantiationDependent = false;
  7821. if (isFunctionTemplateSpecialization && isFriend &&
  7822. (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
  7823. TemplateSpecializationType::anyDependentTemplateArguments(
  7824. TemplateArgs,
  7825. InstantiationDependent))) {
  7826. assert(HasExplicitTemplateArgs &&
  7827. "friend function specialization without template args");
  7828. if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
  7829. Previous))
  7830. NewFD->setInvalidDecl();
  7831. } else if (isFunctionTemplateSpecialization) {
  7832. if (CurContext->isDependentContext() && CurContext->isRecord()
  7833. && !isFriend) {
  7834. isDependentClassScopeExplicitSpecialization = true;
  7835. } else if (!NewFD->isInvalidDecl() &&
  7836. CheckFunctionTemplateSpecialization(
  7837. NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
  7838. Previous))
  7839. NewFD->setInvalidDecl();
  7840. // C++ [dcl.stc]p1:
  7841. // A storage-class-specifier shall not be specified in an explicit
  7842. // specialization (14.7.3)
  7843. FunctionTemplateSpecializationInfo *Info =
  7844. NewFD->getTemplateSpecializationInfo();
  7845. if (Info && SC != SC_None) {
  7846. if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
  7847. Diag(NewFD->getLocation(),
  7848. diag::err_explicit_specialization_inconsistent_storage_class)
  7849. << SC
  7850. << FixItHint::CreateRemoval(
  7851. D.getDeclSpec().getStorageClassSpecLoc());
  7852. else
  7853. Diag(NewFD->getLocation(),
  7854. diag::ext_explicit_specialization_storage_class)
  7855. << FixItHint::CreateRemoval(
  7856. D.getDeclSpec().getStorageClassSpecLoc());
  7857. }
  7858. } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
  7859. if (CheckMemberSpecialization(NewFD, Previous))
  7860. NewFD->setInvalidDecl();
  7861. }
  7862. // Perform semantic checking on the function declaration.
  7863. if (!isDependentClassScopeExplicitSpecialization) {
  7864. if (!NewFD->isInvalidDecl() && NewFD->isMain())
  7865. CheckMain(NewFD, D.getDeclSpec());
  7866. if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
  7867. CheckMSVCRTEntryPoint(NewFD);
  7868. if (!NewFD->isInvalidDecl())
  7869. D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
  7870. isMemberSpecialization));
  7871. else if (!Previous.empty())
  7872. // Recover gracefully from an invalid redeclaration.
  7873. D.setRedeclaration(true);
  7874. }
  7875. assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
  7876. Previous.getResultKind() != LookupResult::FoundOverloaded) &&
  7877. "previous declaration set still overloaded");
  7878. NamedDecl *PrincipalDecl = (FunctionTemplate
  7879. ? cast<NamedDecl>(FunctionTemplate)
  7880. : NewFD);
  7881. if (isFriend && NewFD->getPreviousDecl()) {
  7882. AccessSpecifier Access = AS_public;
  7883. if (!NewFD->isInvalidDecl())
  7884. Access = NewFD->getPreviousDecl()->getAccess();
  7885. NewFD->setAccess(Access);
  7886. if (FunctionTemplate) FunctionTemplate->setAccess(Access);
  7887. }
  7888. if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
  7889. PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
  7890. PrincipalDecl->setNonMemberOperator();
  7891. // If we have a function template, check the template parameter
  7892. // list. This will check and merge default template arguments.
  7893. if (FunctionTemplate) {
  7894. FunctionTemplateDecl *PrevTemplate =
  7895. FunctionTemplate->getPreviousDecl();
  7896. CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
  7897. PrevTemplate ? PrevTemplate->getTemplateParameters()
  7898. : nullptr,
  7899. D.getDeclSpec().isFriendSpecified()
  7900. ? (D.isFunctionDefinition()
  7901. ? TPC_FriendFunctionTemplateDefinition
  7902. : TPC_FriendFunctionTemplate)
  7903. : (D.getCXXScopeSpec().isSet() &&
  7904. DC && DC->isRecord() &&
  7905. DC->isDependentContext())
  7906. ? TPC_ClassTemplateMember
  7907. : TPC_FunctionTemplate);
  7908. }
  7909. if (NewFD->isInvalidDecl()) {
  7910. // Ignore all the rest of this.
  7911. } else if (!D.isRedeclaration()) {
  7912. struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
  7913. AddToScope };
  7914. // Fake up an access specifier if it's supposed to be a class member.
  7915. if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
  7916. NewFD->setAccess(AS_public);
  7917. // Qualified decls generally require a previous declaration.
  7918. if (D.getCXXScopeSpec().isSet()) {
  7919. // ...with the major exception of templated-scope or
  7920. // dependent-scope friend declarations.
  7921. // TODO: we currently also suppress this check in dependent
  7922. // contexts because (1) the parameter depth will be off when
  7923. // matching friend templates and (2) we might actually be
  7924. // selecting a friend based on a dependent factor. But there
  7925. // are situations where these conditions don't apply and we
  7926. // can actually do this check immediately.
  7927. if (isFriend &&
  7928. (TemplateParamLists.size() ||
  7929. D.getCXXScopeSpec().getScopeRep()->isDependent() ||
  7930. CurContext->isDependentContext())) {
  7931. // ignore these
  7932. } else {
  7933. // The user tried to provide an out-of-line definition for a
  7934. // function that is a member of a class or namespace, but there
  7935. // was no such member function declared (C++ [class.mfct]p2,
  7936. // C++ [namespace.memdef]p2). For example:
  7937. //
  7938. // class X {
  7939. // void f() const;
  7940. // };
  7941. //
  7942. // void X::f() { } // ill-formed
  7943. //
  7944. // Complain about this problem, and attempt to suggest close
  7945. // matches (e.g., those that differ only in cv-qualifiers and
  7946. // whether the parameter types are references).
  7947. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7948. *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
  7949. AddToScope = ExtraArgs.AddToScope;
  7950. return Result;
  7951. }
  7952. }
  7953. // Unqualified local friend declarations are required to resolve
  7954. // to something.
  7955. } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
  7956. if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
  7957. *this, Previous, NewFD, ExtraArgs, true, S)) {
  7958. AddToScope = ExtraArgs.AddToScope;
  7959. return Result;
  7960. }
  7961. }
  7962. } else if (!D.isFunctionDefinition() &&
  7963. isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
  7964. !isFriend && !isFunctionTemplateSpecialization &&
  7965. !isMemberSpecialization) {
  7966. // An out-of-line member function declaration must also be a
  7967. // definition (C++ [class.mfct]p2).
  7968. // Note that this is not the case for explicit specializations of
  7969. // function templates or member functions of class templates, per
  7970. // C++ [temp.expl.spec]p2. We also allow these declarations as an
  7971. // extension for compatibility with old SWIG code which likes to
  7972. // generate them.
  7973. Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
  7974. << D.getCXXScopeSpec().getRange();
  7975. }
  7976. }
  7977. ProcessPragmaWeak(S, NewFD);
  7978. checkAttributesAfterMerging(*this, *NewFD);
  7979. AddKnownFunctionAttributes(NewFD);
  7980. if (NewFD->hasAttr<OverloadableAttr>() &&
  7981. !NewFD->getType()->getAs<FunctionProtoType>()) {
  7982. Diag(NewFD->getLocation(),
  7983. diag::err_attribute_overloadable_no_prototype)
  7984. << NewFD;
  7985. // Turn this into a variadic function with no parameters.
  7986. const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
  7987. FunctionProtoType::ExtProtoInfo EPI(
  7988. Context.getDefaultCallingConvention(true, false));
  7989. EPI.Variadic = true;
  7990. EPI.ExtInfo = FT->getExtInfo();
  7991. QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
  7992. NewFD->setType(R);
  7993. }
  7994. // If there's a #pragma GCC visibility in scope, and this isn't a class
  7995. // member, set the visibility of this function.
  7996. if (!DC->isRecord() && NewFD->isExternallyVisible())
  7997. AddPushedVisibilityAttribute(NewFD);
  7998. // If there's a #pragma clang arc_cf_code_audited in scope, consider
  7999. // marking the function.
  8000. AddCFAuditedAttribute(NewFD);
  8001. // If this is a function definition, check if we have to apply optnone due to
  8002. // a pragma.
  8003. if(D.isFunctionDefinition())
  8004. AddRangeBasedOptnone(NewFD);
  8005. // If this is the first declaration of an extern C variable, update
  8006. // the map of such variables.
  8007. if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
  8008. isIncompleteDeclExternC(*this, NewFD))
  8009. RegisterLocallyScopedExternCDecl(NewFD, S);
  8010. // Set this FunctionDecl's range up to the right paren.
  8011. NewFD->setRangeEnd(D.getSourceRange().getEnd());
  8012. if (D.isRedeclaration() && !Previous.empty()) {
  8013. NamedDecl *Prev = Previous.getRepresentativeDecl();
  8014. checkDLLAttributeRedeclaration(*this, Prev, NewFD,
  8015. isMemberSpecialization ||
  8016. isFunctionTemplateSpecialization,
  8017. D.isFunctionDefinition());
  8018. }
  8019. if (getLangOpts().CUDA) {
  8020. IdentifierInfo *II = NewFD->getIdentifier();
  8021. if (II &&
  8022. II->isStr(getLangOpts().HIP ? "hipConfigureCall"
  8023. : "cudaConfigureCall") &&
  8024. !NewFD->isInvalidDecl() &&
  8025. NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  8026. if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
  8027. Diag(NewFD->getLocation(), diag::err_config_scalar_return);
  8028. Context.setcudaConfigureCallDecl(NewFD);
  8029. }
  8030. // Variadic functions, other than a *declaration* of printf, are not allowed
  8031. // in device-side CUDA code, unless someone passed
  8032. // -fcuda-allow-variadic-functions.
  8033. if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
  8034. (NewFD->hasAttr<CUDADeviceAttr>() ||
  8035. NewFD->hasAttr<CUDAGlobalAttr>()) &&
  8036. !(II && II->isStr("printf") && NewFD->isExternC() &&
  8037. !D.isFunctionDefinition())) {
  8038. Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
  8039. }
  8040. }
  8041. MarkUnusedFileScopedDecl(NewFD);
  8042. if (getLangOpts().CPlusPlus) {
  8043. if (FunctionTemplate) {
  8044. if (NewFD->isInvalidDecl())
  8045. FunctionTemplate->setInvalidDecl();
  8046. return FunctionTemplate;
  8047. }
  8048. if (isMemberSpecialization && !NewFD->isInvalidDecl())
  8049. CompleteMemberSpecialization(NewFD, Previous);
  8050. }
  8051. if (NewFD->hasAttr<OpenCLKernelAttr>()) {
  8052. // OpenCL v1.2 s6.8 static is invalid for kernel functions.
  8053. if ((getLangOpts().OpenCLVersion >= 120)
  8054. && (SC == SC_Static)) {
  8055. Diag(D.getIdentifierLoc(), diag::err_static_kernel);
  8056. D.setInvalidType();
  8057. }
  8058. // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
  8059. if (!NewFD->getReturnType()->isVoidType()) {
  8060. SourceRange RTRange = NewFD->getReturnTypeSourceRange();
  8061. Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
  8062. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
  8063. : FixItHint());
  8064. D.setInvalidType();
  8065. }
  8066. llvm::SmallPtrSet<const Type *, 16> ValidTypes;
  8067. for (auto Param : NewFD->parameters())
  8068. checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
  8069. }
  8070. for (const ParmVarDecl *Param : NewFD->parameters()) {
  8071. QualType PT = Param->getType();
  8072. // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
  8073. // types.
  8074. if (getLangOpts().OpenCLVersion >= 200) {
  8075. if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
  8076. QualType ElemTy = PipeTy->getElementType();
  8077. if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
  8078. Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
  8079. D.setInvalidType();
  8080. }
  8081. }
  8082. }
  8083. }
  8084. // Here we have an function template explicit specialization at class scope.
  8085. // The actual specialization will be postponed to template instatiation
  8086. // time via the ClassScopeFunctionSpecializationDecl node.
  8087. if (isDependentClassScopeExplicitSpecialization) {
  8088. ClassScopeFunctionSpecializationDecl *NewSpec =
  8089. ClassScopeFunctionSpecializationDecl::Create(
  8090. Context, CurContext, NewFD->getLocation(),
  8091. cast<CXXMethodDecl>(NewFD),
  8092. HasExplicitTemplateArgs, TemplateArgs);
  8093. CurContext->addDecl(NewSpec);
  8094. AddToScope = false;
  8095. }
  8096. // Diagnose availability attributes. Availability cannot be used on functions
  8097. // that are run during load/unload.
  8098. if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
  8099. if (NewFD->hasAttr<ConstructorAttr>()) {
  8100. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8101. << 1;
  8102. NewFD->dropAttr<AvailabilityAttr>();
  8103. }
  8104. if (NewFD->hasAttr<DestructorAttr>()) {
  8105. Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
  8106. << 2;
  8107. NewFD->dropAttr<AvailabilityAttr>();
  8108. }
  8109. }
  8110. return NewFD;
  8111. }
  8112. /// Checks if the new declaration declared in dependent context must be
  8113. /// put in the same redeclaration chain as the specified declaration.
  8114. ///
  8115. /// \param D Declaration that is checked.
  8116. /// \param PrevDecl Previous declaration found with proper lookup method for the
  8117. /// same declaration name.
  8118. /// \returns True if D must be added to the redeclaration chain which PrevDecl
  8119. /// belongs to.
  8120. ///
  8121. bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
  8122. // Any declarations should be put into redeclaration chains except for
  8123. // friend declaration in a dependent context that names a function in
  8124. // namespace scope.
  8125. //
  8126. // This allows to compile code like:
  8127. //
  8128. // void func();
  8129. // template<typename T> class C1 { friend void func() { } };
  8130. // template<typename T> class C2 { friend void func() { } };
  8131. //
  8132. // This code snippet is a valid code unless both templates are instantiated.
  8133. return !(D->getLexicalDeclContext()->isDependentContext() &&
  8134. D->getDeclContext()->isFileContext() &&
  8135. D->getFriendObjectKind() != Decl::FOK_None);
  8136. }
  8137. /// Check the target attribute of the function for MultiVersion
  8138. /// validity.
  8139. ///
  8140. /// Returns true if there was an error, false otherwise.
  8141. static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
  8142. const auto *TA = FD->getAttr<TargetAttr>();
  8143. assert(TA && "MultiVersion Candidate requires a target attribute");
  8144. TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
  8145. const TargetInfo &TargetInfo = S.Context.getTargetInfo();
  8146. enum ErrType { Feature = 0, Architecture = 1 };
  8147. if (!ParseInfo.Architecture.empty() &&
  8148. !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
  8149. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8150. << Architecture << ParseInfo.Architecture;
  8151. return true;
  8152. }
  8153. for (const auto &Feat : ParseInfo.Features) {
  8154. auto BareFeat = StringRef{Feat}.substr(1);
  8155. if (Feat[0] == '-') {
  8156. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8157. << Feature << ("no-" + BareFeat).str();
  8158. return true;
  8159. }
  8160. if (!TargetInfo.validateCpuSupports(BareFeat) ||
  8161. !TargetInfo.isValidFeatureName(BareFeat)) {
  8162. S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
  8163. << Feature << BareFeat;
  8164. return true;
  8165. }
  8166. }
  8167. return false;
  8168. }
  8169. static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
  8170. const FunctionDecl *NewFD,
  8171. bool CausesMV) {
  8172. enum DoesntSupport {
  8173. FuncTemplates = 0,
  8174. VirtFuncs = 1,
  8175. DeducedReturn = 2,
  8176. Constructors = 3,
  8177. Destructors = 4,
  8178. DeletedFuncs = 5,
  8179. DefaultedFuncs = 6
  8180. };
  8181. enum Different {
  8182. CallingConv = 0,
  8183. ReturnType = 1,
  8184. ConstexprSpec = 2,
  8185. InlineSpec = 3,
  8186. StorageClass = 4,
  8187. Linkage = 5
  8188. };
  8189. // For now, disallow all other attributes. These should be opt-in, but
  8190. // an analysis of all of them is a future FIXME.
  8191. if (CausesMV && OldFD &&
  8192. std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
  8193. S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
  8194. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8195. return true;
  8196. }
  8197. if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
  8198. return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
  8199. if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8200. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8201. << FuncTemplates;
  8202. if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
  8203. if (NewCXXFD->isVirtual())
  8204. return S.Diag(NewCXXFD->getLocation(),
  8205. diag::err_multiversion_doesnt_support)
  8206. << VirtFuncs;
  8207. if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
  8208. return S.Diag(NewCXXCtor->getLocation(),
  8209. diag::err_multiversion_doesnt_support)
  8210. << Constructors;
  8211. if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
  8212. return S.Diag(NewCXXDtor->getLocation(),
  8213. diag::err_multiversion_doesnt_support)
  8214. << Destructors;
  8215. }
  8216. if (NewFD->isDeleted())
  8217. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8218. << DeletedFuncs;
  8219. if (NewFD->isDefaulted())
  8220. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8221. << DefaultedFuncs;
  8222. QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
  8223. const auto *NewType = cast<FunctionType>(NewQType);
  8224. QualType NewReturnType = NewType->getReturnType();
  8225. if (NewReturnType->isUndeducedType())
  8226. return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
  8227. << DeducedReturn;
  8228. // Only allow transition to MultiVersion if it hasn't been used.
  8229. if (OldFD && CausesMV && OldFD->isUsed(false))
  8230. return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
  8231. // Ensure the return type is identical.
  8232. if (OldFD) {
  8233. QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
  8234. const auto *OldType = cast<FunctionType>(OldQType);
  8235. FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
  8236. FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
  8237. if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
  8238. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8239. << CallingConv;
  8240. QualType OldReturnType = OldType->getReturnType();
  8241. if (OldReturnType != NewReturnType)
  8242. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8243. << ReturnType;
  8244. if (OldFD->isConstexpr() != NewFD->isConstexpr())
  8245. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8246. << ConstexprSpec;
  8247. if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
  8248. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8249. << InlineSpec;
  8250. if (OldFD->getStorageClass() != NewFD->getStorageClass())
  8251. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8252. << StorageClass;
  8253. if (OldFD->isExternC() != NewFD->isExternC())
  8254. return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
  8255. << Linkage;
  8256. if (S.CheckEquivalentExceptionSpec(
  8257. OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
  8258. NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
  8259. return true;
  8260. }
  8261. return false;
  8262. }
  8263. /// Check the validity of a mulitversion function declaration.
  8264. /// Also sets the multiversion'ness' of the function itself.
  8265. ///
  8266. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8267. ///
  8268. /// Returns true if there was an error, false otherwise.
  8269. static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
  8270. bool &Redeclaration, NamedDecl *&OldDecl,
  8271. bool &MergeTypeWithPrevious,
  8272. LookupResult &Previous) {
  8273. const auto *NewTA = NewFD->getAttr<TargetAttr>();
  8274. if (NewFD->isMain()) {
  8275. if (NewTA && NewTA->isDefaultVersion()) {
  8276. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
  8277. NewFD->setInvalidDecl();
  8278. return true;
  8279. }
  8280. return false;
  8281. }
  8282. // If there is no matching previous decl, only 'default' can
  8283. // cause MultiVersioning.
  8284. if (!OldDecl) {
  8285. if (NewTA && NewTA->isDefaultVersion()) {
  8286. if (!NewFD->getType()->getAs<FunctionProtoType>()) {
  8287. S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
  8288. NewFD->setInvalidDecl();
  8289. return true;
  8290. }
  8291. if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
  8292. NewFD->setInvalidDecl();
  8293. return true;
  8294. }
  8295. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8296. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8297. NewFD->setInvalidDecl();
  8298. return true;
  8299. }
  8300. NewFD->setIsMultiVersion();
  8301. }
  8302. return false;
  8303. }
  8304. if (OldDecl->getDeclContext()->getRedeclContext() !=
  8305. NewFD->getDeclContext()->getRedeclContext())
  8306. return false;
  8307. FunctionDecl *OldFD = OldDecl->getAsFunction();
  8308. // Unresolved 'using' statements (the other way OldDecl can be not a function)
  8309. // likely cannot cause a problem here.
  8310. if (!OldFD)
  8311. return false;
  8312. if (!OldFD->isMultiVersion() && !NewTA)
  8313. return false;
  8314. if (OldFD->isMultiVersion() && !NewTA) {
  8315. S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
  8316. NewFD->setInvalidDecl();
  8317. return true;
  8318. }
  8319. TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
  8320. // Sort order doesn't matter, it just needs to be consistent.
  8321. llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
  8322. const auto *OldTA = OldFD->getAttr<TargetAttr>();
  8323. if (!OldFD->isMultiVersion()) {
  8324. // If the old decl is NOT MultiVersioned yet, and we don't cause that
  8325. // to change, this is a simple redeclaration.
  8326. if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
  8327. return false;
  8328. // Otherwise, this decl causes MultiVersioning.
  8329. if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
  8330. S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
  8331. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8332. NewFD->setInvalidDecl();
  8333. return true;
  8334. }
  8335. if (!OldFD->getType()->getAs<FunctionProtoType>()) {
  8336. S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
  8337. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8338. NewFD->setInvalidDecl();
  8339. return true;
  8340. }
  8341. if (CheckMultiVersionValue(S, NewFD)) {
  8342. NewFD->setInvalidDecl();
  8343. return true;
  8344. }
  8345. if (CheckMultiVersionValue(S, OldFD)) {
  8346. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8347. NewFD->setInvalidDecl();
  8348. return true;
  8349. }
  8350. TargetAttr::ParsedTargetAttr OldParsed =
  8351. OldTA->parse(std::less<std::string>());
  8352. if (OldParsed == NewParsed) {
  8353. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8354. S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
  8355. NewFD->setInvalidDecl();
  8356. return true;
  8357. }
  8358. for (const auto *FD : OldFD->redecls()) {
  8359. const auto *CurTA = FD->getAttr<TargetAttr>();
  8360. if (!CurTA || CurTA->isInherited()) {
  8361. S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
  8362. S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
  8363. NewFD->setInvalidDecl();
  8364. return true;
  8365. }
  8366. }
  8367. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
  8368. NewFD->setInvalidDecl();
  8369. return true;
  8370. }
  8371. OldFD->setIsMultiVersion();
  8372. NewFD->setIsMultiVersion();
  8373. Redeclaration = false;
  8374. MergeTypeWithPrevious = false;
  8375. OldDecl = nullptr;
  8376. Previous.clear();
  8377. return false;
  8378. }
  8379. bool UseMemberUsingDeclRules =
  8380. S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
  8381. // Next, check ALL non-overloads to see if this is a redeclaration of a
  8382. // previous member of the MultiVersion set.
  8383. for (NamedDecl *ND : Previous) {
  8384. FunctionDecl *CurFD = ND->getAsFunction();
  8385. if (!CurFD)
  8386. continue;
  8387. if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
  8388. continue;
  8389. const auto *CurTA = CurFD->getAttr<TargetAttr>();
  8390. if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
  8391. NewFD->setIsMultiVersion();
  8392. Redeclaration = true;
  8393. OldDecl = ND;
  8394. return false;
  8395. }
  8396. TargetAttr::ParsedTargetAttr CurParsed =
  8397. CurTA->parse(std::less<std::string>());
  8398. if (CurParsed == NewParsed) {
  8399. S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
  8400. S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
  8401. NewFD->setInvalidDecl();
  8402. return true;
  8403. }
  8404. }
  8405. // Else, this is simply a non-redecl case.
  8406. if (CheckMultiVersionValue(S, NewFD)) {
  8407. NewFD->setInvalidDecl();
  8408. return true;
  8409. }
  8410. if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
  8411. NewFD->setInvalidDecl();
  8412. return true;
  8413. }
  8414. NewFD->setIsMultiVersion();
  8415. Redeclaration = false;
  8416. MergeTypeWithPrevious = false;
  8417. OldDecl = nullptr;
  8418. Previous.clear();
  8419. return false;
  8420. }
  8421. /// Perform semantic checking of a new function declaration.
  8422. ///
  8423. /// Performs semantic analysis of the new function declaration
  8424. /// NewFD. This routine performs all semantic checking that does not
  8425. /// require the actual declarator involved in the declaration, and is
  8426. /// used both for the declaration of functions as they are parsed
  8427. /// (called via ActOnDeclarator) and for the declaration of functions
  8428. /// that have been instantiated via C++ template instantiation (called
  8429. /// via InstantiateDecl).
  8430. ///
  8431. /// \param IsMemberSpecialization whether this new function declaration is
  8432. /// a member specialization (that replaces any definition provided by the
  8433. /// previous declaration).
  8434. ///
  8435. /// This sets NewFD->isInvalidDecl() to true if there was an error.
  8436. ///
  8437. /// \returns true if the function declaration is a redeclaration.
  8438. bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
  8439. LookupResult &Previous,
  8440. bool IsMemberSpecialization) {
  8441. assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
  8442. "Variably modified return types are not handled here");
  8443. // Determine whether the type of this function should be merged with
  8444. // a previous visible declaration. This never happens for functions in C++,
  8445. // and always happens in C if the previous declaration was visible.
  8446. bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
  8447. !Previous.isShadowed();
  8448. bool Redeclaration = false;
  8449. NamedDecl *OldDecl = nullptr;
  8450. bool MayNeedOverloadableChecks = false;
  8451. // Merge or overload the declaration with an existing declaration of
  8452. // the same name, if appropriate.
  8453. if (!Previous.empty()) {
  8454. // Determine whether NewFD is an overload of PrevDecl or
  8455. // a declaration that requires merging. If it's an overload,
  8456. // there's no more work to do here; we'll just add the new
  8457. // function to the scope.
  8458. if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
  8459. NamedDecl *Candidate = Previous.getRepresentativeDecl();
  8460. if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
  8461. Redeclaration = true;
  8462. OldDecl = Candidate;
  8463. }
  8464. } else {
  8465. MayNeedOverloadableChecks = true;
  8466. switch (CheckOverload(S, NewFD, Previous, OldDecl,
  8467. /*NewIsUsingDecl*/ false)) {
  8468. case Ovl_Match:
  8469. Redeclaration = true;
  8470. break;
  8471. case Ovl_NonFunction:
  8472. Redeclaration = true;
  8473. break;
  8474. case Ovl_Overload:
  8475. Redeclaration = false;
  8476. break;
  8477. }
  8478. }
  8479. }
  8480. // Check for a previous extern "C" declaration with this name.
  8481. if (!Redeclaration &&
  8482. checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
  8483. if (!Previous.empty()) {
  8484. // This is an extern "C" declaration with the same name as a previous
  8485. // declaration, and thus redeclares that entity...
  8486. Redeclaration = true;
  8487. OldDecl = Previous.getFoundDecl();
  8488. MergeTypeWithPrevious = false;
  8489. // ... except in the presence of __attribute__((overloadable)).
  8490. if (OldDecl->hasAttr<OverloadableAttr>() ||
  8491. NewFD->hasAttr<OverloadableAttr>()) {
  8492. if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
  8493. MayNeedOverloadableChecks = true;
  8494. Redeclaration = false;
  8495. OldDecl = nullptr;
  8496. }
  8497. }
  8498. }
  8499. }
  8500. if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
  8501. MergeTypeWithPrevious, Previous))
  8502. return Redeclaration;
  8503. // C++11 [dcl.constexpr]p8:
  8504. // A constexpr specifier for a non-static member function that is not
  8505. // a constructor declares that member function to be const.
  8506. //
  8507. // This needs to be delayed until we know whether this is an out-of-line
  8508. // definition of a static member function.
  8509. //
  8510. // This rule is not present in C++1y, so we produce a backwards
  8511. // compatibility warning whenever it happens in C++11.
  8512. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
  8513. if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
  8514. !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
  8515. (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
  8516. CXXMethodDecl *OldMD = nullptr;
  8517. if (OldDecl)
  8518. OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
  8519. if (!OldMD || !OldMD->isStatic()) {
  8520. const FunctionProtoType *FPT =
  8521. MD->getType()->castAs<FunctionProtoType>();
  8522. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8523. EPI.TypeQuals |= Qualifiers::Const;
  8524. MD->setType(Context.getFunctionType(FPT->getReturnType(),
  8525. FPT->getParamTypes(), EPI));
  8526. // Warn that we did this, if we're not performing template instantiation.
  8527. // In that case, we'll have warned already when the template was defined.
  8528. if (!inTemplateInstantiation()) {
  8529. SourceLocation AddConstLoc;
  8530. if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
  8531. .IgnoreParens().getAs<FunctionTypeLoc>())
  8532. AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
  8533. Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
  8534. << FixItHint::CreateInsertion(AddConstLoc, " const");
  8535. }
  8536. }
  8537. }
  8538. if (Redeclaration) {
  8539. // NewFD and OldDecl represent declarations that need to be
  8540. // merged.
  8541. if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
  8542. NewFD->setInvalidDecl();
  8543. return Redeclaration;
  8544. }
  8545. Previous.clear();
  8546. Previous.addDecl(OldDecl);
  8547. if (FunctionTemplateDecl *OldTemplateDecl =
  8548. dyn_cast<FunctionTemplateDecl>(OldDecl)) {
  8549. auto *OldFD = OldTemplateDecl->getTemplatedDecl();
  8550. NewFD->setPreviousDeclaration(OldFD);
  8551. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8552. FunctionTemplateDecl *NewTemplateDecl
  8553. = NewFD->getDescribedFunctionTemplate();
  8554. assert(NewTemplateDecl && "Template/non-template mismatch");
  8555. if (NewFD->isCXXClassMember()) {
  8556. NewFD->setAccess(OldTemplateDecl->getAccess());
  8557. NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
  8558. }
  8559. // If this is an explicit specialization of a member that is a function
  8560. // template, mark it as a member specialization.
  8561. if (IsMemberSpecialization &&
  8562. NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
  8563. NewTemplateDecl->setMemberSpecialization();
  8564. assert(OldTemplateDecl->isMemberSpecialization());
  8565. // Explicit specializations of a member template do not inherit deleted
  8566. // status from the parent member template that they are specializing.
  8567. if (OldFD->isDeleted()) {
  8568. // FIXME: This assert will not hold in the presence of modules.
  8569. assert(OldFD->getCanonicalDecl() == OldFD);
  8570. // FIXME: We need an update record for this AST mutation.
  8571. OldFD->setDeletedAsWritten(false);
  8572. }
  8573. }
  8574. } else {
  8575. if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
  8576. auto *OldFD = cast<FunctionDecl>(OldDecl);
  8577. // This needs to happen first so that 'inline' propagates.
  8578. NewFD->setPreviousDeclaration(OldFD);
  8579. adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
  8580. if (NewFD->isCXXClassMember())
  8581. NewFD->setAccess(OldFD->getAccess());
  8582. }
  8583. }
  8584. } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
  8585. !NewFD->getAttr<OverloadableAttr>()) {
  8586. assert((Previous.empty() ||
  8587. llvm::any_of(Previous,
  8588. [](const NamedDecl *ND) {
  8589. return ND->hasAttr<OverloadableAttr>();
  8590. })) &&
  8591. "Non-redecls shouldn't happen without overloadable present");
  8592. auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
  8593. const auto *FD = dyn_cast<FunctionDecl>(ND);
  8594. return FD && !FD->hasAttr<OverloadableAttr>();
  8595. });
  8596. if (OtherUnmarkedIter != Previous.end()) {
  8597. Diag(NewFD->getLocation(),
  8598. diag::err_attribute_overloadable_multiple_unmarked_overloads);
  8599. Diag((*OtherUnmarkedIter)->getLocation(),
  8600. diag::note_attribute_overloadable_prev_overload)
  8601. << false;
  8602. NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
  8603. }
  8604. }
  8605. // Semantic checking for this function declaration (in isolation).
  8606. if (getLangOpts().CPlusPlus) {
  8607. // C++-specific checks.
  8608. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
  8609. CheckConstructor(Constructor);
  8610. } else if (CXXDestructorDecl *Destructor =
  8611. dyn_cast<CXXDestructorDecl>(NewFD)) {
  8612. CXXRecordDecl *Record = Destructor->getParent();
  8613. QualType ClassType = Context.getTypeDeclType(Record);
  8614. // FIXME: Shouldn't we be able to perform this check even when the class
  8615. // type is dependent? Both gcc and edg can handle that.
  8616. if (!ClassType->isDependentType()) {
  8617. DeclarationName Name
  8618. = Context.DeclarationNames.getCXXDestructorName(
  8619. Context.getCanonicalType(ClassType));
  8620. if (NewFD->getDeclName() != Name) {
  8621. Diag(NewFD->getLocation(), diag::err_destructor_name);
  8622. NewFD->setInvalidDecl();
  8623. return Redeclaration;
  8624. }
  8625. }
  8626. } else if (CXXConversionDecl *Conversion
  8627. = dyn_cast<CXXConversionDecl>(NewFD)) {
  8628. ActOnConversionDeclarator(Conversion);
  8629. } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
  8630. if (auto *TD = Guide->getDescribedFunctionTemplate())
  8631. CheckDeductionGuideTemplate(TD);
  8632. // A deduction guide is not on the list of entities that can be
  8633. // explicitly specialized.
  8634. if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
  8635. Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
  8636. << /*explicit specialization*/ 1;
  8637. }
  8638. // Find any virtual functions that this function overrides.
  8639. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
  8640. if (!Method->isFunctionTemplateSpecialization() &&
  8641. !Method->getDescribedFunctionTemplate() &&
  8642. Method->isCanonicalDecl()) {
  8643. if (AddOverriddenMethods(Method->getParent(), Method)) {
  8644. // If the function was marked as "static", we have a problem.
  8645. if (NewFD->getStorageClass() == SC_Static) {
  8646. ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
  8647. }
  8648. }
  8649. }
  8650. if (Method->isStatic())
  8651. checkThisInStaticMemberFunctionType(Method);
  8652. }
  8653. // Extra checking for C++ overloaded operators (C++ [over.oper]).
  8654. if (NewFD->isOverloadedOperator() &&
  8655. CheckOverloadedOperatorDeclaration(NewFD)) {
  8656. NewFD->setInvalidDecl();
  8657. return Redeclaration;
  8658. }
  8659. // Extra checking for C++0x literal operators (C++0x [over.literal]).
  8660. if (NewFD->getLiteralIdentifier() &&
  8661. CheckLiteralOperatorDeclaration(NewFD)) {
  8662. NewFD->setInvalidDecl();
  8663. return Redeclaration;
  8664. }
  8665. // In C++, check default arguments now that we have merged decls. Unless
  8666. // the lexical context is the class, because in this case this is done
  8667. // during delayed parsing anyway.
  8668. if (!CurContext->isRecord())
  8669. CheckCXXDefaultArguments(NewFD);
  8670. // If this function declares a builtin function, check the type of this
  8671. // declaration against the expected type for the builtin.
  8672. if (unsigned BuiltinID = NewFD->getBuiltinID()) {
  8673. ASTContext::GetBuiltinTypeError Error;
  8674. LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
  8675. QualType T = Context.GetBuiltinType(BuiltinID, Error);
  8676. // If the type of the builtin differs only in its exception
  8677. // specification, that's OK.
  8678. // FIXME: If the types do differ in this way, it would be better to
  8679. // retain the 'noexcept' form of the type.
  8680. if (!T.isNull() &&
  8681. !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
  8682. NewFD->getType()))
  8683. // The type of this function differs from the type of the builtin,
  8684. // so forget about the builtin entirely.
  8685. Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
  8686. }
  8687. // If this function is declared as being extern "C", then check to see if
  8688. // the function returns a UDT (class, struct, or union type) that is not C
  8689. // compatible, and if it does, warn the user.
  8690. // But, issue any diagnostic on the first declaration only.
  8691. if (Previous.empty() && NewFD->isExternC()) {
  8692. QualType R = NewFD->getReturnType();
  8693. if (R->isIncompleteType() && !R->isVoidType())
  8694. Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
  8695. << NewFD << R;
  8696. else if (!R.isPODType(Context) && !R->isVoidType() &&
  8697. !R->isObjCObjectPointerType())
  8698. Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
  8699. }
  8700. // C++1z [dcl.fct]p6:
  8701. // [...] whether the function has a non-throwing exception-specification
  8702. // [is] part of the function type
  8703. //
  8704. // This results in an ABI break between C++14 and C++17 for functions whose
  8705. // declared type includes an exception-specification in a parameter or
  8706. // return type. (Exception specifications on the function itself are OK in
  8707. // most cases, and exception specifications are not permitted in most other
  8708. // contexts where they could make it into a mangling.)
  8709. if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
  8710. auto HasNoexcept = [&](QualType T) -> bool {
  8711. // Strip off declarator chunks that could be between us and a function
  8712. // type. We don't need to look far, exception specifications are very
  8713. // restricted prior to C++17.
  8714. if (auto *RT = T->getAs<ReferenceType>())
  8715. T = RT->getPointeeType();
  8716. else if (T->isAnyPointerType())
  8717. T = T->getPointeeType();
  8718. else if (auto *MPT = T->getAs<MemberPointerType>())
  8719. T = MPT->getPointeeType();
  8720. if (auto *FPT = T->getAs<FunctionProtoType>())
  8721. if (FPT->isNothrow())
  8722. return true;
  8723. return false;
  8724. };
  8725. auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
  8726. bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
  8727. for (QualType T : FPT->param_types())
  8728. AnyNoexcept |= HasNoexcept(T);
  8729. if (AnyNoexcept)
  8730. Diag(NewFD->getLocation(),
  8731. diag::warn_cxx17_compat_exception_spec_in_signature)
  8732. << NewFD;
  8733. }
  8734. if (!Redeclaration && LangOpts.CUDA)
  8735. checkCUDATargetOverload(NewFD, Previous);
  8736. }
  8737. return Redeclaration;
  8738. }
  8739. void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
  8740. // C++11 [basic.start.main]p3:
  8741. // A program that [...] declares main to be inline, static or
  8742. // constexpr is ill-formed.
  8743. // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
  8744. // appear in a declaration of main.
  8745. // static main is not an error under C99, but we should warn about it.
  8746. // We accept _Noreturn main as an extension.
  8747. if (FD->getStorageClass() == SC_Static)
  8748. Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
  8749. ? diag::err_static_main : diag::warn_static_main)
  8750. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  8751. if (FD->isInlineSpecified())
  8752. Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
  8753. << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
  8754. if (DS.isNoreturnSpecified()) {
  8755. SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
  8756. SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
  8757. Diag(NoreturnLoc, diag::ext_noreturn_main);
  8758. Diag(NoreturnLoc, diag::note_main_remove_noreturn)
  8759. << FixItHint::CreateRemoval(NoreturnRange);
  8760. }
  8761. if (FD->isConstexpr()) {
  8762. Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
  8763. << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
  8764. FD->setConstexpr(false);
  8765. }
  8766. if (getLangOpts().OpenCL) {
  8767. Diag(FD->getLocation(), diag::err_opencl_no_main)
  8768. << FD->hasAttr<OpenCLKernelAttr>();
  8769. FD->setInvalidDecl();
  8770. return;
  8771. }
  8772. QualType T = FD->getType();
  8773. assert(T->isFunctionType() && "function decl is not of function type");
  8774. const FunctionType* FT = T->castAs<FunctionType>();
  8775. // Set default calling convention for main()
  8776. if (FT->getCallConv() != CC_C) {
  8777. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
  8778. FD->setType(QualType(FT, 0));
  8779. T = Context.getCanonicalType(FD->getType());
  8780. }
  8781. if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
  8782. // In C with GNU extensions we allow main() to have non-integer return
  8783. // type, but we should warn about the extension, and we disable the
  8784. // implicit-return-zero rule.
  8785. // GCC in C mode accepts qualified 'int'.
  8786. if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
  8787. FD->setHasImplicitReturnZero(true);
  8788. else {
  8789. Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
  8790. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8791. if (RTRange.isValid())
  8792. Diag(RTRange.getBegin(), diag::note_main_change_return_type)
  8793. << FixItHint::CreateReplacement(RTRange, "int");
  8794. }
  8795. } else {
  8796. // In C and C++, main magically returns 0 if you fall off the end;
  8797. // set the flag which tells us that.
  8798. // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
  8799. // All the standards say that main() should return 'int'.
  8800. if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
  8801. FD->setHasImplicitReturnZero(true);
  8802. else {
  8803. // Otherwise, this is just a flat-out error.
  8804. SourceRange RTRange = FD->getReturnTypeSourceRange();
  8805. Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
  8806. << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
  8807. : FixItHint());
  8808. FD->setInvalidDecl(true);
  8809. }
  8810. }
  8811. // Treat protoless main() as nullary.
  8812. if (isa<FunctionNoProtoType>(FT)) return;
  8813. const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
  8814. unsigned nparams = FTP->getNumParams();
  8815. assert(FD->getNumParams() == nparams);
  8816. bool HasExtraParameters = (nparams > 3);
  8817. if (FTP->isVariadic()) {
  8818. Diag(FD->getLocation(), diag::ext_variadic_main);
  8819. // FIXME: if we had information about the location of the ellipsis, we
  8820. // could add a FixIt hint to remove it as a parameter.
  8821. }
  8822. // Darwin passes an undocumented fourth argument of type char**. If
  8823. // other platforms start sprouting these, the logic below will start
  8824. // getting shifty.
  8825. if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
  8826. HasExtraParameters = false;
  8827. if (HasExtraParameters) {
  8828. Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
  8829. FD->setInvalidDecl(true);
  8830. nparams = 3;
  8831. }
  8832. // FIXME: a lot of the following diagnostics would be improved
  8833. // if we had some location information about types.
  8834. QualType CharPP =
  8835. Context.getPointerType(Context.getPointerType(Context.CharTy));
  8836. QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
  8837. for (unsigned i = 0; i < nparams; ++i) {
  8838. QualType AT = FTP->getParamType(i);
  8839. bool mismatch = true;
  8840. if (Context.hasSameUnqualifiedType(AT, Expected[i]))
  8841. mismatch = false;
  8842. else if (Expected[i] == CharPP) {
  8843. // As an extension, the following forms are okay:
  8844. // char const **
  8845. // char const * const *
  8846. // char * const *
  8847. QualifierCollector qs;
  8848. const PointerType* PT;
  8849. if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
  8850. (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
  8851. Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
  8852. Context.CharTy)) {
  8853. qs.removeConst();
  8854. mismatch = !qs.empty();
  8855. }
  8856. }
  8857. if (mismatch) {
  8858. Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
  8859. // TODO: suggest replacing given type with expected type
  8860. FD->setInvalidDecl(true);
  8861. }
  8862. }
  8863. if (nparams == 1 && !FD->isInvalidDecl()) {
  8864. Diag(FD->getLocation(), diag::warn_main_one_arg);
  8865. }
  8866. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8867. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8868. FD->setInvalidDecl();
  8869. }
  8870. }
  8871. void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
  8872. QualType T = FD->getType();
  8873. assert(T->isFunctionType() && "function decl is not of function type");
  8874. const FunctionType *FT = T->castAs<FunctionType>();
  8875. // Set an implicit return of 'zero' if the function can return some integral,
  8876. // enumeration, pointer or nullptr type.
  8877. if (FT->getReturnType()->isIntegralOrEnumerationType() ||
  8878. FT->getReturnType()->isAnyPointerType() ||
  8879. FT->getReturnType()->isNullPtrType())
  8880. // DllMain is exempt because a return value of zero means it failed.
  8881. if (FD->getName() != "DllMain")
  8882. FD->setHasImplicitReturnZero(true);
  8883. if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
  8884. Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
  8885. FD->setInvalidDecl();
  8886. }
  8887. }
  8888. bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
  8889. // FIXME: Need strict checking. In C89, we need to check for
  8890. // any assignment, increment, decrement, function-calls, or
  8891. // commas outside of a sizeof. In C99, it's the same list,
  8892. // except that the aforementioned are allowed in unevaluated
  8893. // expressions. Everything else falls under the
  8894. // "may accept other forms of constant expressions" exception.
  8895. // (We never end up here for C++, so the constant expression
  8896. // rules there don't matter.)
  8897. const Expr *Culprit;
  8898. if (Init->isConstantInitializer(Context, false, &Culprit))
  8899. return false;
  8900. Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
  8901. << Culprit->getSourceRange();
  8902. return true;
  8903. }
  8904. namespace {
  8905. // Visits an initialization expression to see if OrigDecl is evaluated in
  8906. // its own initialization and throws a warning if it does.
  8907. class SelfReferenceChecker
  8908. : public EvaluatedExprVisitor<SelfReferenceChecker> {
  8909. Sema &S;
  8910. Decl *OrigDecl;
  8911. bool isRecordType;
  8912. bool isPODType;
  8913. bool isReferenceType;
  8914. bool isInitList;
  8915. llvm::SmallVector<unsigned, 4> InitFieldIndex;
  8916. public:
  8917. typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
  8918. SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
  8919. S(S), OrigDecl(OrigDecl) {
  8920. isPODType = false;
  8921. isRecordType = false;
  8922. isReferenceType = false;
  8923. isInitList = false;
  8924. if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
  8925. isPODType = VD->getType().isPODType(S.Context);
  8926. isRecordType = VD->getType()->isRecordType();
  8927. isReferenceType = VD->getType()->isReferenceType();
  8928. }
  8929. }
  8930. // For most expressions, just call the visitor. For initializer lists,
  8931. // track the index of the field being initialized since fields are
  8932. // initialized in order allowing use of previously initialized fields.
  8933. void CheckExpr(Expr *E) {
  8934. InitListExpr *InitList = dyn_cast<InitListExpr>(E);
  8935. if (!InitList) {
  8936. Visit(E);
  8937. return;
  8938. }
  8939. // Track and increment the index here.
  8940. isInitList = true;
  8941. InitFieldIndex.push_back(0);
  8942. for (auto Child : InitList->children()) {
  8943. CheckExpr(cast<Expr>(Child));
  8944. ++InitFieldIndex.back();
  8945. }
  8946. InitFieldIndex.pop_back();
  8947. }
  8948. // Returns true if MemberExpr is checked and no further checking is needed.
  8949. // Returns false if additional checking is required.
  8950. bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
  8951. llvm::SmallVector<FieldDecl*, 4> Fields;
  8952. Expr *Base = E;
  8953. bool ReferenceField = false;
  8954. // Get the field memebers used.
  8955. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  8956. FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
  8957. if (!FD)
  8958. return false;
  8959. Fields.push_back(FD);
  8960. if (FD->getType()->isReferenceType())
  8961. ReferenceField = true;
  8962. Base = ME->getBase()->IgnoreParenImpCasts();
  8963. }
  8964. // Keep checking only if the base Decl is the same.
  8965. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
  8966. if (!DRE || DRE->getDecl() != OrigDecl)
  8967. return false;
  8968. // A reference field can be bound to an unininitialized field.
  8969. if (CheckReference && !ReferenceField)
  8970. return true;
  8971. // Convert FieldDecls to their index number.
  8972. llvm::SmallVector<unsigned, 4> UsedFieldIndex;
  8973. for (const FieldDecl *I : llvm::reverse(Fields))
  8974. UsedFieldIndex.push_back(I->getFieldIndex());
  8975. // See if a warning is needed by checking the first difference in index
  8976. // numbers. If field being used has index less than the field being
  8977. // initialized, then the use is safe.
  8978. for (auto UsedIter = UsedFieldIndex.begin(),
  8979. UsedEnd = UsedFieldIndex.end(),
  8980. OrigIter = InitFieldIndex.begin(),
  8981. OrigEnd = InitFieldIndex.end();
  8982. UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
  8983. if (*UsedIter < *OrigIter)
  8984. return true;
  8985. if (*UsedIter > *OrigIter)
  8986. break;
  8987. }
  8988. // TODO: Add a different warning which will print the field names.
  8989. HandleDeclRefExpr(DRE);
  8990. return true;
  8991. }
  8992. // For most expressions, the cast is directly above the DeclRefExpr.
  8993. // For conditional operators, the cast can be outside the conditional
  8994. // operator if both expressions are DeclRefExpr's.
  8995. void HandleValue(Expr *E) {
  8996. E = E->IgnoreParens();
  8997. if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
  8998. HandleDeclRefExpr(DRE);
  8999. return;
  9000. }
  9001. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  9002. Visit(CO->getCond());
  9003. HandleValue(CO->getTrueExpr());
  9004. HandleValue(CO->getFalseExpr());
  9005. return;
  9006. }
  9007. if (BinaryConditionalOperator *BCO =
  9008. dyn_cast<BinaryConditionalOperator>(E)) {
  9009. Visit(BCO->getCond());
  9010. HandleValue(BCO->getFalseExpr());
  9011. return;
  9012. }
  9013. if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
  9014. HandleValue(OVE->getSourceExpr());
  9015. return;
  9016. }
  9017. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  9018. if (BO->getOpcode() == BO_Comma) {
  9019. Visit(BO->getLHS());
  9020. HandleValue(BO->getRHS());
  9021. return;
  9022. }
  9023. }
  9024. if (isa<MemberExpr>(E)) {
  9025. if (isInitList) {
  9026. if (CheckInitListMemberExpr(cast<MemberExpr>(E),
  9027. false /*CheckReference*/))
  9028. return;
  9029. }
  9030. Expr *Base = E->IgnoreParenImpCasts();
  9031. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9032. // Check for static member variables and don't warn on them.
  9033. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9034. return;
  9035. Base = ME->getBase()->IgnoreParenImpCasts();
  9036. }
  9037. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
  9038. HandleDeclRefExpr(DRE);
  9039. return;
  9040. }
  9041. Visit(E);
  9042. }
  9043. // Reference types not handled in HandleValue are handled here since all
  9044. // uses of references are bad, not just r-value uses.
  9045. void VisitDeclRefExpr(DeclRefExpr *E) {
  9046. if (isReferenceType)
  9047. HandleDeclRefExpr(E);
  9048. }
  9049. void VisitImplicitCastExpr(ImplicitCastExpr *E) {
  9050. if (E->getCastKind() == CK_LValueToRValue) {
  9051. HandleValue(E->getSubExpr());
  9052. return;
  9053. }
  9054. Inherited::VisitImplicitCastExpr(E);
  9055. }
  9056. void VisitMemberExpr(MemberExpr *E) {
  9057. if (isInitList) {
  9058. if (CheckInitListMemberExpr(E, true /*CheckReference*/))
  9059. return;
  9060. }
  9061. // Don't warn on arrays since they can be treated as pointers.
  9062. if (E->getType()->canDecayToPointerType()) return;
  9063. // Warn when a non-static method call is followed by non-static member
  9064. // field accesses, which is followed by a DeclRefExpr.
  9065. CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
  9066. bool Warn = (MD && !MD->isStatic());
  9067. Expr *Base = E->getBase()->IgnoreParenImpCasts();
  9068. while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
  9069. if (!isa<FieldDecl>(ME->getMemberDecl()))
  9070. Warn = false;
  9071. Base = ME->getBase()->IgnoreParenImpCasts();
  9072. }
  9073. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
  9074. if (Warn)
  9075. HandleDeclRefExpr(DRE);
  9076. return;
  9077. }
  9078. // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
  9079. // Visit that expression.
  9080. Visit(Base);
  9081. }
  9082. void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
  9083. Expr *Callee = E->getCallee();
  9084. if (isa<UnresolvedLookupExpr>(Callee))
  9085. return Inherited::VisitCXXOperatorCallExpr(E);
  9086. Visit(Callee);
  9087. for (auto Arg: E->arguments())
  9088. HandleValue(Arg->IgnoreParenImpCasts());
  9089. }
  9090. void VisitUnaryOperator(UnaryOperator *E) {
  9091. // For POD record types, addresses of its own members are well-defined.
  9092. if (E->getOpcode() == UO_AddrOf && isRecordType &&
  9093. isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
  9094. if (!isPODType)
  9095. HandleValue(E->getSubExpr());
  9096. return;
  9097. }
  9098. if (E->isIncrementDecrementOp()) {
  9099. HandleValue(E->getSubExpr());
  9100. return;
  9101. }
  9102. Inherited::VisitUnaryOperator(E);
  9103. }
  9104. void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
  9105. void VisitCXXConstructExpr(CXXConstructExpr *E) {
  9106. if (E->getConstructor()->isCopyConstructor()) {
  9107. Expr *ArgExpr = E->getArg(0);
  9108. if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
  9109. if (ILE->getNumInits() == 1)
  9110. ArgExpr = ILE->getInit(0);
  9111. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
  9112. if (ICE->getCastKind() == CK_NoOp)
  9113. ArgExpr = ICE->getSubExpr();
  9114. HandleValue(ArgExpr);
  9115. return;
  9116. }
  9117. Inherited::VisitCXXConstructExpr(E);
  9118. }
  9119. void VisitCallExpr(CallExpr *E) {
  9120. // Treat std::move as a use.
  9121. if (E->isCallToStdMove()) {
  9122. HandleValue(E->getArg(0));
  9123. return;
  9124. }
  9125. Inherited::VisitCallExpr(E);
  9126. }
  9127. void VisitBinaryOperator(BinaryOperator *E) {
  9128. if (E->isCompoundAssignmentOp()) {
  9129. HandleValue(E->getLHS());
  9130. Visit(E->getRHS());
  9131. return;
  9132. }
  9133. Inherited::VisitBinaryOperator(E);
  9134. }
  9135. // A custom visitor for BinaryConditionalOperator is needed because the
  9136. // regular visitor would check the condition and true expression separately
  9137. // but both point to the same place giving duplicate diagnostics.
  9138. void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
  9139. Visit(E->getCond());
  9140. Visit(E->getFalseExpr());
  9141. }
  9142. void HandleDeclRefExpr(DeclRefExpr *DRE) {
  9143. Decl* ReferenceDecl = DRE->getDecl();
  9144. if (OrigDecl != ReferenceDecl) return;
  9145. unsigned diag;
  9146. if (isReferenceType) {
  9147. diag = diag::warn_uninit_self_reference_in_reference_init;
  9148. } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
  9149. diag = diag::warn_static_self_reference_in_init;
  9150. } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
  9151. isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
  9152. DRE->getDecl()->getType()->isRecordType()) {
  9153. diag = diag::warn_uninit_self_reference_in_init;
  9154. } else {
  9155. // Local variables will be handled by the CFG analysis.
  9156. return;
  9157. }
  9158. S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
  9159. S.PDiag(diag)
  9160. << DRE->getDecl()
  9161. << OrigDecl->getLocation()
  9162. << DRE->getSourceRange());
  9163. }
  9164. };
  9165. /// CheckSelfReference - Warns if OrigDecl is used in expression E.
  9166. static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
  9167. bool DirectInit) {
  9168. // Parameters arguments are occassionially constructed with itself,
  9169. // for instance, in recursive functions. Skip them.
  9170. if (isa<ParmVarDecl>(OrigDecl))
  9171. return;
  9172. E = E->IgnoreParens();
  9173. // Skip checking T a = a where T is not a record or reference type.
  9174. // Doing so is a way to silence uninitialized warnings.
  9175. if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
  9176. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
  9177. if (ICE->getCastKind() == CK_LValueToRValue)
  9178. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
  9179. if (DRE->getDecl() == OrigDecl)
  9180. return;
  9181. SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
  9182. }
  9183. } // end anonymous namespace
  9184. namespace {
  9185. // Simple wrapper to add the name of a variable or (if no variable is
  9186. // available) a DeclarationName into a diagnostic.
  9187. struct VarDeclOrName {
  9188. VarDecl *VDecl;
  9189. DeclarationName Name;
  9190. friend const Sema::SemaDiagnosticBuilder &
  9191. operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
  9192. return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
  9193. }
  9194. };
  9195. } // end anonymous namespace
  9196. QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
  9197. DeclarationName Name, QualType Type,
  9198. TypeSourceInfo *TSI,
  9199. SourceRange Range, bool DirectInit,
  9200. Expr *Init) {
  9201. bool IsInitCapture = !VDecl;
  9202. assert((!VDecl || !VDecl->isInitCapture()) &&
  9203. "init captures are expected to be deduced prior to initialization");
  9204. VarDeclOrName VN{VDecl, Name};
  9205. DeducedType *Deduced = Type->getContainedDeducedType();
  9206. assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
  9207. // C++11 [dcl.spec.auto]p3
  9208. if (!Init) {
  9209. assert(VDecl && "no init for init capture deduction?");
  9210. // Except for class argument deduction, and then for an initializing
  9211. // declaration only, i.e. no static at class scope or extern.
  9212. if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
  9213. VDecl->hasExternalStorage() ||
  9214. VDecl->isStaticDataMember()) {
  9215. Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
  9216. << VDecl->getDeclName() << Type;
  9217. return QualType();
  9218. }
  9219. }
  9220. ArrayRef<Expr*> DeduceInits;
  9221. if (Init)
  9222. DeduceInits = Init;
  9223. if (DirectInit) {
  9224. if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
  9225. DeduceInits = PL->exprs();
  9226. }
  9227. if (isa<DeducedTemplateSpecializationType>(Deduced)) {
  9228. assert(VDecl && "non-auto type for init capture deduction?");
  9229. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9230. InitializationKind Kind = InitializationKind::CreateForInit(
  9231. VDecl->getLocation(), DirectInit, Init);
  9232. // FIXME: Initialization should not be taking a mutable list of inits.
  9233. SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
  9234. return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
  9235. InitsCopy);
  9236. }
  9237. if (DirectInit) {
  9238. if (auto *IL = dyn_cast<InitListExpr>(Init))
  9239. DeduceInits = IL->inits();
  9240. }
  9241. // Deduction only works if we have exactly one source expression.
  9242. if (DeduceInits.empty()) {
  9243. // It isn't possible to write this directly, but it is possible to
  9244. // end up in this situation with "auto x(some_pack...);"
  9245. Diag(Init->getLocStart(), IsInitCapture
  9246. ? diag::err_init_capture_no_expression
  9247. : diag::err_auto_var_init_no_expression)
  9248. << VN << Type << Range;
  9249. return QualType();
  9250. }
  9251. if (DeduceInits.size() > 1) {
  9252. Diag(DeduceInits[1]->getLocStart(),
  9253. IsInitCapture ? diag::err_init_capture_multiple_expressions
  9254. : diag::err_auto_var_init_multiple_expressions)
  9255. << VN << Type << Range;
  9256. return QualType();
  9257. }
  9258. Expr *DeduceInit = DeduceInits[0];
  9259. if (DirectInit && isa<InitListExpr>(DeduceInit)) {
  9260. Diag(Init->getLocStart(), IsInitCapture
  9261. ? diag::err_init_capture_paren_braces
  9262. : diag::err_auto_var_init_paren_braces)
  9263. << isa<InitListExpr>(Init) << VN << Type << Range;
  9264. return QualType();
  9265. }
  9266. // Expressions default to 'id' when we're in a debugger.
  9267. bool DefaultedAnyToId = false;
  9268. if (getLangOpts().DebuggerCastResultToId &&
  9269. Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
  9270. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9271. if (Result.isInvalid()) {
  9272. return QualType();
  9273. }
  9274. Init = Result.get();
  9275. DefaultedAnyToId = true;
  9276. }
  9277. // C++ [dcl.decomp]p1:
  9278. // If the assignment-expression [...] has array type A and no ref-qualifier
  9279. // is present, e has type cv A
  9280. if (VDecl && isa<DecompositionDecl>(VDecl) &&
  9281. Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
  9282. DeduceInit->getType()->isConstantArrayType())
  9283. return Context.getQualifiedType(DeduceInit->getType(),
  9284. Type.getQualifiers());
  9285. QualType DeducedType;
  9286. if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
  9287. if (!IsInitCapture)
  9288. DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
  9289. else if (isa<InitListExpr>(Init))
  9290. Diag(Range.getBegin(),
  9291. diag::err_init_capture_deduction_failure_from_init_list)
  9292. << VN
  9293. << (DeduceInit->getType().isNull() ? TSI->getType()
  9294. : DeduceInit->getType())
  9295. << DeduceInit->getSourceRange();
  9296. else
  9297. Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
  9298. << VN << TSI->getType()
  9299. << (DeduceInit->getType().isNull() ? TSI->getType()
  9300. : DeduceInit->getType())
  9301. << DeduceInit->getSourceRange();
  9302. }
  9303. // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
  9304. // 'id' instead of a specific object type prevents most of our usual
  9305. // checks.
  9306. // We only want to warn outside of template instantiations, though:
  9307. // inside a template, the 'id' could have come from a parameter.
  9308. if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
  9309. !DeducedType.isNull() && DeducedType->isObjCIdType()) {
  9310. SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
  9311. Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
  9312. }
  9313. return DeducedType;
  9314. }
  9315. bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
  9316. Expr *Init) {
  9317. QualType DeducedType = deduceVarTypeFromInitializer(
  9318. VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
  9319. VDecl->getSourceRange(), DirectInit, Init);
  9320. if (DeducedType.isNull()) {
  9321. VDecl->setInvalidDecl();
  9322. return true;
  9323. }
  9324. VDecl->setType(DeducedType);
  9325. assert(VDecl->isLinkageValid());
  9326. // In ARC, infer lifetime.
  9327. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
  9328. VDecl->setInvalidDecl();
  9329. // If this is a redeclaration, check that the type we just deduced matches
  9330. // the previously declared type.
  9331. if (VarDecl *Old = VDecl->getPreviousDecl()) {
  9332. // We never need to merge the type, because we cannot form an incomplete
  9333. // array of auto, nor deduce such a type.
  9334. MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
  9335. }
  9336. // Check the deduced type is valid for a variable declaration.
  9337. CheckVariableDeclarationType(VDecl);
  9338. return VDecl->isInvalidDecl();
  9339. }
  9340. /// AddInitializerToDecl - Adds the initializer Init to the
  9341. /// declaration dcl. If DirectInit is true, this is C++ direct
  9342. /// initialization rather than copy initialization.
  9343. void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
  9344. // If there is no declaration, there was an error parsing it. Just ignore
  9345. // the initializer.
  9346. if (!RealDecl || RealDecl->isInvalidDecl()) {
  9347. CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
  9348. return;
  9349. }
  9350. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
  9351. // Pure-specifiers are handled in ActOnPureSpecifier.
  9352. Diag(Method->getLocation(), diag::err_member_function_initialization)
  9353. << Method->getDeclName() << Init->getSourceRange();
  9354. Method->setInvalidDecl();
  9355. return;
  9356. }
  9357. VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
  9358. if (!VDecl) {
  9359. assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
  9360. Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
  9361. RealDecl->setInvalidDecl();
  9362. return;
  9363. }
  9364. // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
  9365. if (VDecl->getType()->isUndeducedType()) {
  9366. // Attempt typo correction early so that the type of the init expression can
  9367. // be deduced based on the chosen correction if the original init contains a
  9368. // TypoExpr.
  9369. ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
  9370. if (!Res.isUsable()) {
  9371. RealDecl->setInvalidDecl();
  9372. return;
  9373. }
  9374. Init = Res.get();
  9375. if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
  9376. return;
  9377. }
  9378. // dllimport cannot be used on variable definitions.
  9379. if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
  9380. Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
  9381. VDecl->setInvalidDecl();
  9382. return;
  9383. }
  9384. if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
  9385. // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
  9386. Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
  9387. VDecl->setInvalidDecl();
  9388. return;
  9389. }
  9390. if (!VDecl->getType()->isDependentType()) {
  9391. // A definition must end up with a complete type, which means it must be
  9392. // complete with the restriction that an array type might be completed by
  9393. // the initializer; note that later code assumes this restriction.
  9394. QualType BaseDeclType = VDecl->getType();
  9395. if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
  9396. BaseDeclType = Array->getElementType();
  9397. if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
  9398. diag::err_typecheck_decl_incomplete_type)) {
  9399. RealDecl->setInvalidDecl();
  9400. return;
  9401. }
  9402. // The variable can not have an abstract class type.
  9403. if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
  9404. diag::err_abstract_type_in_decl,
  9405. AbstractVariableType))
  9406. VDecl->setInvalidDecl();
  9407. }
  9408. // If adding the initializer will turn this declaration into a definition,
  9409. // and we already have a definition for this variable, diagnose or otherwise
  9410. // handle the situation.
  9411. VarDecl *Def;
  9412. if ((Def = VDecl->getDefinition()) && Def != VDecl &&
  9413. (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
  9414. !VDecl->isThisDeclarationADemotedDefinition() &&
  9415. checkVarDeclRedefinition(Def, VDecl))
  9416. return;
  9417. if (getLangOpts().CPlusPlus) {
  9418. // C++ [class.static.data]p4
  9419. // If a static data member is of const integral or const
  9420. // enumeration type, its declaration in the class definition can
  9421. // specify a constant-initializer which shall be an integral
  9422. // constant expression (5.19). In that case, the member can appear
  9423. // in integral constant expressions. The member shall still be
  9424. // defined in a namespace scope if it is used in the program and the
  9425. // namespace scope definition shall not contain an initializer.
  9426. //
  9427. // We already performed a redefinition check above, but for static
  9428. // data members we also need to check whether there was an in-class
  9429. // declaration with an initializer.
  9430. if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
  9431. Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
  9432. << VDecl->getDeclName();
  9433. Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
  9434. diag::note_previous_initializer)
  9435. << 0;
  9436. return;
  9437. }
  9438. if (VDecl->hasLocalStorage())
  9439. setFunctionHasBranchProtectedScope();
  9440. if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
  9441. VDecl->setInvalidDecl();
  9442. return;
  9443. }
  9444. }
  9445. // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
  9446. // a kernel function cannot be initialized."
  9447. if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
  9448. Diag(VDecl->getLocation(), diag::err_local_cant_init);
  9449. VDecl->setInvalidDecl();
  9450. return;
  9451. }
  9452. // Get the decls type and save a reference for later, since
  9453. // CheckInitializerTypes may change it.
  9454. QualType DclT = VDecl->getType(), SavT = DclT;
  9455. // Expressions default to 'id' when we're in a debugger
  9456. // and we are assigning it to a variable of Objective-C pointer type.
  9457. if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
  9458. Init->getType() == Context.UnknownAnyTy) {
  9459. ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
  9460. if (Result.isInvalid()) {
  9461. VDecl->setInvalidDecl();
  9462. return;
  9463. }
  9464. Init = Result.get();
  9465. }
  9466. // Perform the initialization.
  9467. ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
  9468. if (!VDecl->isInvalidDecl()) {
  9469. InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
  9470. InitializationKind Kind = InitializationKind::CreateForInit(
  9471. VDecl->getLocation(), DirectInit, Init);
  9472. MultiExprArg Args = Init;
  9473. if (CXXDirectInit)
  9474. Args = MultiExprArg(CXXDirectInit->getExprs(),
  9475. CXXDirectInit->getNumExprs());
  9476. // Try to correct any TypoExprs in the initialization arguments.
  9477. for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
  9478. ExprResult Res = CorrectDelayedTyposInExpr(
  9479. Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
  9480. InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
  9481. return Init.Failed() ? ExprError() : E;
  9482. });
  9483. if (Res.isInvalid()) {
  9484. VDecl->setInvalidDecl();
  9485. } else if (Res.get() != Args[Idx]) {
  9486. Args[Idx] = Res.get();
  9487. }
  9488. }
  9489. if (VDecl->isInvalidDecl())
  9490. return;
  9491. InitializationSequence InitSeq(*this, Entity, Kind, Args,
  9492. /*TopLevelOfInitList=*/false,
  9493. /*TreatUnavailableAsInvalid=*/false);
  9494. ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
  9495. if (Result.isInvalid()) {
  9496. VDecl->setInvalidDecl();
  9497. return;
  9498. }
  9499. Init = Result.getAs<Expr>();
  9500. }
  9501. // Check for self-references within variable initializers.
  9502. // Variables declared within a function/method body (except for references)
  9503. // are handled by a dataflow analysis.
  9504. if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
  9505. VDecl->getType()->isReferenceType()) {
  9506. CheckSelfReference(*this, RealDecl, Init, DirectInit);
  9507. }
  9508. // If the type changed, it means we had an incomplete type that was
  9509. // completed by the initializer. For example:
  9510. // int ary[] = { 1, 3, 5 };
  9511. // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
  9512. if (!VDecl->isInvalidDecl() && (DclT != SavT))
  9513. VDecl->setType(DclT);
  9514. if (!VDecl->isInvalidDecl()) {
  9515. checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
  9516. if (VDecl->hasAttr<BlocksAttr>())
  9517. checkRetainCycles(VDecl, Init);
  9518. // It is safe to assign a weak reference into a strong variable.
  9519. // Although this code can still have problems:
  9520. // id x = self.weakProp;
  9521. // id y = self.weakProp;
  9522. // we do not warn to warn spuriously when 'x' and 'y' are on separate
  9523. // paths through the function. This should be revisited if
  9524. // -Wrepeated-use-of-weak is made flow-sensitive.
  9525. if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
  9526. VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
  9527. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
  9528. Init->getLocStart()))
  9529. getCurFunction()->markSafeWeakUse(Init);
  9530. }
  9531. // The initialization is usually a full-expression.
  9532. //
  9533. // FIXME: If this is a braced initialization of an aggregate, it is not
  9534. // an expression, and each individual field initializer is a separate
  9535. // full-expression. For instance, in:
  9536. //
  9537. // struct Temp { ~Temp(); };
  9538. // struct S { S(Temp); };
  9539. // struct T { S a, b; } t = { Temp(), Temp() }
  9540. //
  9541. // we should destroy the first Temp before constructing the second.
  9542. ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
  9543. false,
  9544. VDecl->isConstexpr());
  9545. if (Result.isInvalid()) {
  9546. VDecl->setInvalidDecl();
  9547. return;
  9548. }
  9549. Init = Result.get();
  9550. // Attach the initializer to the decl.
  9551. VDecl->setInit(Init);
  9552. if (VDecl->isLocalVarDecl()) {
  9553. // Don't check the initializer if the declaration is malformed.
  9554. if (VDecl->isInvalidDecl()) {
  9555. // do nothing
  9556. // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
  9557. // This is true even in OpenCL C++.
  9558. } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
  9559. CheckForConstantInitializer(Init, DclT);
  9560. // Otherwise, C++ does not restrict the initializer.
  9561. } else if (getLangOpts().CPlusPlus) {
  9562. // do nothing
  9563. // C99 6.7.8p4: All the expressions in an initializer for an object that has
  9564. // static storage duration shall be constant expressions or string literals.
  9565. } else if (VDecl->getStorageClass() == SC_Static) {
  9566. CheckForConstantInitializer(Init, DclT);
  9567. // C89 is stricter than C99 for aggregate initializers.
  9568. // C89 6.5.7p3: All the expressions [...] in an initializer list
  9569. // for an object that has aggregate or union type shall be
  9570. // constant expressions.
  9571. } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
  9572. isa<InitListExpr>(Init)) {
  9573. const Expr *Culprit;
  9574. if (!Init->isConstantInitializer(Context, false, &Culprit)) {
  9575. Diag(Culprit->getExprLoc(),
  9576. diag::ext_aggregate_init_not_constant)
  9577. << Culprit->getSourceRange();
  9578. }
  9579. }
  9580. } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
  9581. VDecl->getLexicalDeclContext()->isRecord()) {
  9582. // This is an in-class initialization for a static data member, e.g.,
  9583. //
  9584. // struct S {
  9585. // static const int value = 17;
  9586. // };
  9587. // C++ [class.mem]p4:
  9588. // A member-declarator can contain a constant-initializer only
  9589. // if it declares a static member (9.4) of const integral or
  9590. // const enumeration type, see 9.4.2.
  9591. //
  9592. // C++11 [class.static.data]p3:
  9593. // If a non-volatile non-inline const static data member is of integral
  9594. // or enumeration type, its declaration in the class definition can
  9595. // specify a brace-or-equal-initializer in which every initializer-clause
  9596. // that is an assignment-expression is a constant expression. A static
  9597. // data member of literal type can be declared in the class definition
  9598. // with the constexpr specifier; if so, its declaration shall specify a
  9599. // brace-or-equal-initializer in which every initializer-clause that is
  9600. // an assignment-expression is a constant expression.
  9601. // Do nothing on dependent types.
  9602. if (DclT->isDependentType()) {
  9603. // Allow any 'static constexpr' members, whether or not they are of literal
  9604. // type. We separately check that every constexpr variable is of literal
  9605. // type.
  9606. } else if (VDecl->isConstexpr()) {
  9607. // Require constness.
  9608. } else if (!DclT.isConstQualified()) {
  9609. Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
  9610. << Init->getSourceRange();
  9611. VDecl->setInvalidDecl();
  9612. // We allow integer constant expressions in all cases.
  9613. } else if (DclT->isIntegralOrEnumerationType()) {
  9614. // Check whether the expression is a constant expression.
  9615. SourceLocation Loc;
  9616. if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
  9617. // In C++11, a non-constexpr const static data member with an
  9618. // in-class initializer cannot be volatile.
  9619. Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
  9620. else if (Init->isValueDependent())
  9621. ; // Nothing to check.
  9622. else if (Init->isIntegerConstantExpr(Context, &Loc))
  9623. ; // Ok, it's an ICE!
  9624. else if (Init->isEvaluatable(Context)) {
  9625. // If we can constant fold the initializer through heroics, accept it,
  9626. // but report this as a use of an extension for -pedantic.
  9627. Diag(Loc, diag::ext_in_class_initializer_non_constant)
  9628. << Init->getSourceRange();
  9629. } else {
  9630. // Otherwise, this is some crazy unknown case. Report the issue at the
  9631. // location provided by the isIntegerConstantExpr failed check.
  9632. Diag(Loc, diag::err_in_class_initializer_non_constant)
  9633. << Init->getSourceRange();
  9634. VDecl->setInvalidDecl();
  9635. }
  9636. // We allow foldable floating-point constants as an extension.
  9637. } else if (DclT->isFloatingType()) { // also permits complex, which is ok
  9638. // In C++98, this is a GNU extension. In C++11, it is not, but we support
  9639. // it anyway and provide a fixit to add the 'constexpr'.
  9640. if (getLangOpts().CPlusPlus11) {
  9641. Diag(VDecl->getLocation(),
  9642. diag::ext_in_class_initializer_float_type_cxx11)
  9643. << DclT << Init->getSourceRange();
  9644. Diag(VDecl->getLocStart(),
  9645. diag::note_in_class_initializer_float_type_cxx11)
  9646. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9647. } else {
  9648. Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
  9649. << DclT << Init->getSourceRange();
  9650. if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
  9651. Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
  9652. << Init->getSourceRange();
  9653. VDecl->setInvalidDecl();
  9654. }
  9655. }
  9656. // Suggest adding 'constexpr' in C++11 for literal types.
  9657. } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
  9658. Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
  9659. << DclT << Init->getSourceRange()
  9660. << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
  9661. VDecl->setConstexpr(true);
  9662. } else {
  9663. Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
  9664. << DclT << Init->getSourceRange();
  9665. VDecl->setInvalidDecl();
  9666. }
  9667. } else if (VDecl->isFileVarDecl()) {
  9668. // In C, extern is typically used to avoid tentative definitions when
  9669. // declaring variables in headers, but adding an intializer makes it a
  9670. // definition. This is somewhat confusing, so GCC and Clang both warn on it.
  9671. // In C++, extern is often used to give implictly static const variables
  9672. // external linkage, so don't warn in that case. If selectany is present,
  9673. // this might be header code intended for C and C++ inclusion, so apply the
  9674. // C++ rules.
  9675. if (VDecl->getStorageClass() == SC_Extern &&
  9676. ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
  9677. !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
  9678. !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
  9679. !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
  9680. Diag(VDecl->getLocation(), diag::warn_extern_init);
  9681. // C99 6.7.8p4. All file scoped initializers need to be constant.
  9682. if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
  9683. CheckForConstantInitializer(Init, DclT);
  9684. }
  9685. // We will represent direct-initialization similarly to copy-initialization:
  9686. // int x(1); -as-> int x = 1;
  9687. // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
  9688. //
  9689. // Clients that want to distinguish between the two forms, can check for
  9690. // direct initializer using VarDecl::getInitStyle().
  9691. // A major benefit is that clients that don't particularly care about which
  9692. // exactly form was it (like the CodeGen) can handle both cases without
  9693. // special case code.
  9694. // C++ 8.5p11:
  9695. // The form of initialization (using parentheses or '=') is generally
  9696. // insignificant, but does matter when the entity being initialized has a
  9697. // class type.
  9698. if (CXXDirectInit) {
  9699. assert(DirectInit && "Call-style initializer must be direct init.");
  9700. VDecl->setInitStyle(VarDecl::CallInit);
  9701. } else if (DirectInit) {
  9702. // This must be list-initialization. No other way is direct-initialization.
  9703. VDecl->setInitStyle(VarDecl::ListInit);
  9704. }
  9705. CheckCompleteVariableDeclaration(VDecl);
  9706. }
  9707. /// ActOnInitializerError - Given that there was an error parsing an
  9708. /// initializer for the given declaration, try to return to some form
  9709. /// of sanity.
  9710. void Sema::ActOnInitializerError(Decl *D) {
  9711. // Our main concern here is re-establishing invariants like "a
  9712. // variable's type is either dependent or complete".
  9713. if (!D || D->isInvalidDecl()) return;
  9714. VarDecl *VD = dyn_cast<VarDecl>(D);
  9715. if (!VD) return;
  9716. // Bindings are not usable if we can't make sense of the initializer.
  9717. if (auto *DD = dyn_cast<DecompositionDecl>(D))
  9718. for (auto *BD : DD->bindings())
  9719. BD->setInvalidDecl();
  9720. // Auto types are meaningless if we can't make sense of the initializer.
  9721. if (ParsingInitForAutoVars.count(D)) {
  9722. D->setInvalidDecl();
  9723. return;
  9724. }
  9725. QualType Ty = VD->getType();
  9726. if (Ty->isDependentType()) return;
  9727. // Require a complete type.
  9728. if (RequireCompleteType(VD->getLocation(),
  9729. Context.getBaseElementType(Ty),
  9730. diag::err_typecheck_decl_incomplete_type)) {
  9731. VD->setInvalidDecl();
  9732. return;
  9733. }
  9734. // Require a non-abstract type.
  9735. if (RequireNonAbstractType(VD->getLocation(), Ty,
  9736. diag::err_abstract_type_in_decl,
  9737. AbstractVariableType)) {
  9738. VD->setInvalidDecl();
  9739. return;
  9740. }
  9741. // Don't bother complaining about constructors or destructors,
  9742. // though.
  9743. }
  9744. void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
  9745. // If there is no declaration, there was an error parsing it. Just ignore it.
  9746. if (!RealDecl)
  9747. return;
  9748. if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
  9749. QualType Type = Var->getType();
  9750. // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
  9751. if (isa<DecompositionDecl>(RealDecl)) {
  9752. Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
  9753. Var->setInvalidDecl();
  9754. return;
  9755. }
  9756. if (Type->isUndeducedType() &&
  9757. DeduceVariableDeclarationType(Var, false, nullptr))
  9758. return;
  9759. // C++11 [class.static.data]p3: A static data member can be declared with
  9760. // the constexpr specifier; if so, its declaration shall specify
  9761. // a brace-or-equal-initializer.
  9762. // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
  9763. // the definition of a variable [...] or the declaration of a static data
  9764. // member.
  9765. if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
  9766. !Var->isThisDeclarationADemotedDefinition()) {
  9767. if (Var->isStaticDataMember()) {
  9768. // C++1z removes the relevant rule; the in-class declaration is always
  9769. // a definition there.
  9770. if (!getLangOpts().CPlusPlus17) {
  9771. Diag(Var->getLocation(),
  9772. diag::err_constexpr_static_mem_var_requires_init)
  9773. << Var->getDeclName();
  9774. Var->setInvalidDecl();
  9775. return;
  9776. }
  9777. } else {
  9778. Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
  9779. Var->setInvalidDecl();
  9780. return;
  9781. }
  9782. }
  9783. // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
  9784. // be initialized.
  9785. if (!Var->isInvalidDecl() &&
  9786. Var->getType().getAddressSpace() == LangAS::opencl_constant &&
  9787. Var->getStorageClass() != SC_Extern && !Var->getInit()) {
  9788. Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
  9789. Var->setInvalidDecl();
  9790. return;
  9791. }
  9792. switch (Var->isThisDeclarationADefinition()) {
  9793. case VarDecl::Definition:
  9794. if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
  9795. break;
  9796. // We have an out-of-line definition of a static data member
  9797. // that has an in-class initializer, so we type-check this like
  9798. // a declaration.
  9799. //
  9800. LLVM_FALLTHROUGH;
  9801. case VarDecl::DeclarationOnly:
  9802. // It's only a declaration.
  9803. // Block scope. C99 6.7p7: If an identifier for an object is
  9804. // declared with no linkage (C99 6.2.2p6), the type for the
  9805. // object shall be complete.
  9806. if (!Type->isDependentType() && Var->isLocalVarDecl() &&
  9807. !Var->hasLinkage() && !Var->isInvalidDecl() &&
  9808. RequireCompleteType(Var->getLocation(), Type,
  9809. diag::err_typecheck_decl_incomplete_type))
  9810. Var->setInvalidDecl();
  9811. // Make sure that the type is not abstract.
  9812. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9813. RequireNonAbstractType(Var->getLocation(), Type,
  9814. diag::err_abstract_type_in_decl,
  9815. AbstractVariableType))
  9816. Var->setInvalidDecl();
  9817. if (!Type->isDependentType() && !Var->isInvalidDecl() &&
  9818. Var->getStorageClass() == SC_PrivateExtern) {
  9819. Diag(Var->getLocation(), diag::warn_private_extern);
  9820. Diag(Var->getLocation(), diag::note_private_extern);
  9821. }
  9822. return;
  9823. case VarDecl::TentativeDefinition:
  9824. // File scope. C99 6.9.2p2: A declaration of an identifier for an
  9825. // object that has file scope without an initializer, and without a
  9826. // storage-class specifier or with the storage-class specifier "static",
  9827. // constitutes a tentative definition. Note: A tentative definition with
  9828. // external linkage is valid (C99 6.2.2p5).
  9829. if (!Var->isInvalidDecl()) {
  9830. if (const IncompleteArrayType *ArrayT
  9831. = Context.getAsIncompleteArrayType(Type)) {
  9832. if (RequireCompleteType(Var->getLocation(),
  9833. ArrayT->getElementType(),
  9834. diag::err_illegal_decl_array_incomplete_type))
  9835. Var->setInvalidDecl();
  9836. } else if (Var->getStorageClass() == SC_Static) {
  9837. // C99 6.9.2p3: If the declaration of an identifier for an object is
  9838. // a tentative definition and has internal linkage (C99 6.2.2p3), the
  9839. // declared type shall not be an incomplete type.
  9840. // NOTE: code such as the following
  9841. // static struct s;
  9842. // struct s { int a; };
  9843. // is accepted by gcc. Hence here we issue a warning instead of
  9844. // an error and we do not invalidate the static declaration.
  9845. // NOTE: to avoid multiple warnings, only check the first declaration.
  9846. if (Var->isFirstDecl())
  9847. RequireCompleteType(Var->getLocation(), Type,
  9848. diag::ext_typecheck_decl_incomplete_type);
  9849. }
  9850. }
  9851. // Record the tentative definition; we're done.
  9852. if (!Var->isInvalidDecl())
  9853. TentativeDefinitions.push_back(Var);
  9854. return;
  9855. }
  9856. // Provide a specific diagnostic for uninitialized variable
  9857. // definitions with incomplete array type.
  9858. if (Type->isIncompleteArrayType()) {
  9859. Diag(Var->getLocation(),
  9860. diag::err_typecheck_incomplete_array_needs_initializer);
  9861. Var->setInvalidDecl();
  9862. return;
  9863. }
  9864. // Provide a specific diagnostic for uninitialized variable
  9865. // definitions with reference type.
  9866. if (Type->isReferenceType()) {
  9867. Diag(Var->getLocation(), diag::err_reference_var_requires_init)
  9868. << Var->getDeclName()
  9869. << SourceRange(Var->getLocation(), Var->getLocation());
  9870. Var->setInvalidDecl();
  9871. return;
  9872. }
  9873. // Do not attempt to type-check the default initializer for a
  9874. // variable with dependent type.
  9875. if (Type->isDependentType())
  9876. return;
  9877. if (Var->isInvalidDecl())
  9878. return;
  9879. if (!Var->hasAttr<AliasAttr>()) {
  9880. if (RequireCompleteType(Var->getLocation(),
  9881. Context.getBaseElementType(Type),
  9882. diag::err_typecheck_decl_incomplete_type)) {
  9883. Var->setInvalidDecl();
  9884. return;
  9885. }
  9886. } else {
  9887. return;
  9888. }
  9889. // The variable can not have an abstract class type.
  9890. if (RequireNonAbstractType(Var->getLocation(), Type,
  9891. diag::err_abstract_type_in_decl,
  9892. AbstractVariableType)) {
  9893. Var->setInvalidDecl();
  9894. return;
  9895. }
  9896. // Check for jumps past the implicit initializer. C++0x
  9897. // clarifies that this applies to a "variable with automatic
  9898. // storage duration", not a "local variable".
  9899. // C++11 [stmt.dcl]p3
  9900. // A program that jumps from a point where a variable with automatic
  9901. // storage duration is not in scope to a point where it is in scope is
  9902. // ill-formed unless the variable has scalar type, class type with a
  9903. // trivial default constructor and a trivial destructor, a cv-qualified
  9904. // version of one of these types, or an array of one of the preceding
  9905. // types and is declared without an initializer.
  9906. if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
  9907. if (const RecordType *Record
  9908. = Context.getBaseElementType(Type)->getAs<RecordType>()) {
  9909. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
  9910. // Mark the function (if we're in one) for further checking even if the
  9911. // looser rules of C++11 do not require such checks, so that we can
  9912. // diagnose incompatibilities with C++98.
  9913. if (!CXXRecord->isPOD())
  9914. setFunctionHasBranchProtectedScope();
  9915. }
  9916. }
  9917. // C++03 [dcl.init]p9:
  9918. // If no initializer is specified for an object, and the
  9919. // object is of (possibly cv-qualified) non-POD class type (or
  9920. // array thereof), the object shall be default-initialized; if
  9921. // the object is of const-qualified type, the underlying class
  9922. // type shall have a user-declared default
  9923. // constructor. Otherwise, if no initializer is specified for
  9924. // a non- static object, the object and its subobjects, if
  9925. // any, have an indeterminate initial value); if the object
  9926. // or any of its subobjects are of const-qualified type, the
  9927. // program is ill-formed.
  9928. // C++0x [dcl.init]p11:
  9929. // If no initializer is specified for an object, the object is
  9930. // default-initialized; [...].
  9931. InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
  9932. InitializationKind Kind
  9933. = InitializationKind::CreateDefault(Var->getLocation());
  9934. InitializationSequence InitSeq(*this, Entity, Kind, None);
  9935. ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
  9936. if (Init.isInvalid())
  9937. Var->setInvalidDecl();
  9938. else if (Init.get()) {
  9939. Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
  9940. // This is important for template substitution.
  9941. Var->setInitStyle(VarDecl::CallInit);
  9942. }
  9943. CheckCompleteVariableDeclaration(Var);
  9944. }
  9945. }
  9946. void Sema::ActOnCXXForRangeDecl(Decl *D) {
  9947. // If there is no declaration, there was an error parsing it. Ignore it.
  9948. if (!D)
  9949. return;
  9950. VarDecl *VD = dyn_cast<VarDecl>(D);
  9951. if (!VD) {
  9952. Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
  9953. D->setInvalidDecl();
  9954. return;
  9955. }
  9956. VD->setCXXForRangeDecl(true);
  9957. // for-range-declaration cannot be given a storage class specifier.
  9958. int Error = -1;
  9959. switch (VD->getStorageClass()) {
  9960. case SC_None:
  9961. break;
  9962. case SC_Extern:
  9963. Error = 0;
  9964. break;
  9965. case SC_Static:
  9966. Error = 1;
  9967. break;
  9968. case SC_PrivateExtern:
  9969. Error = 2;
  9970. break;
  9971. case SC_Auto:
  9972. Error = 3;
  9973. break;
  9974. case SC_Register:
  9975. Error = 4;
  9976. break;
  9977. }
  9978. if (Error != -1) {
  9979. Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
  9980. << VD->getDeclName() << Error;
  9981. D->setInvalidDecl();
  9982. }
  9983. }
  9984. StmtResult
  9985. Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
  9986. IdentifierInfo *Ident,
  9987. ParsedAttributes &Attrs,
  9988. SourceLocation AttrEnd) {
  9989. // C++1y [stmt.iter]p1:
  9990. // A range-based for statement of the form
  9991. // for ( for-range-identifier : for-range-initializer ) statement
  9992. // is equivalent to
  9993. // for ( auto&& for-range-identifier : for-range-initializer ) statement
  9994. DeclSpec DS(Attrs.getPool().getFactory());
  9995. const char *PrevSpec;
  9996. unsigned DiagID;
  9997. DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
  9998. getPrintingPolicy());
  9999. Declarator D(DS, DeclaratorContext::ForContext);
  10000. D.SetIdentifier(Ident, IdentLoc);
  10001. D.takeAttributes(Attrs, AttrEnd);
  10002. ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
  10003. D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
  10004. EmptyAttrs, IdentLoc);
  10005. Decl *Var = ActOnDeclarator(S, D);
  10006. cast<VarDecl>(Var)->setCXXForRangeDecl(true);
  10007. FinalizeDeclaration(Var);
  10008. return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
  10009. AttrEnd.isValid() ? AttrEnd : IdentLoc);
  10010. }
  10011. void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
  10012. if (var->isInvalidDecl()) return;
  10013. if (getLangOpts().OpenCL) {
  10014. // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
  10015. // initialiser
  10016. if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
  10017. !var->hasInit()) {
  10018. Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
  10019. << 1 /*Init*/;
  10020. var->setInvalidDecl();
  10021. return;
  10022. }
  10023. }
  10024. // In Objective-C, don't allow jumps past the implicit initialization of a
  10025. // local retaining variable.
  10026. if (getLangOpts().ObjC1 &&
  10027. var->hasLocalStorage()) {
  10028. switch (var->getType().getObjCLifetime()) {
  10029. case Qualifiers::OCL_None:
  10030. case Qualifiers::OCL_ExplicitNone:
  10031. case Qualifiers::OCL_Autoreleasing:
  10032. break;
  10033. case Qualifiers::OCL_Weak:
  10034. case Qualifiers::OCL_Strong:
  10035. setFunctionHasBranchProtectedScope();
  10036. break;
  10037. }
  10038. }
  10039. if (var->hasLocalStorage() &&
  10040. var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
  10041. setFunctionHasBranchProtectedScope();
  10042. // Warn about externally-visible variables being defined without a
  10043. // prior declaration. We only want to do this for global
  10044. // declarations, but we also specifically need to avoid doing it for
  10045. // class members because the linkage of an anonymous class can
  10046. // change if it's later given a typedef name.
  10047. if (var->isThisDeclarationADefinition() &&
  10048. var->getDeclContext()->getRedeclContext()->isFileContext() &&
  10049. var->isExternallyVisible() && var->hasLinkage() &&
  10050. !var->isInline() && !var->getDescribedVarTemplate() &&
  10051. !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
  10052. !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
  10053. var->getLocation())) {
  10054. // Find a previous declaration that's not a definition.
  10055. VarDecl *prev = var->getPreviousDecl();
  10056. while (prev && prev->isThisDeclarationADefinition())
  10057. prev = prev->getPreviousDecl();
  10058. if (!prev)
  10059. Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
  10060. }
  10061. // Cache the result of checking for constant initialization.
  10062. Optional<bool> CacheHasConstInit;
  10063. const Expr *CacheCulprit;
  10064. auto checkConstInit = [&]() mutable {
  10065. if (!CacheHasConstInit)
  10066. CacheHasConstInit = var->getInit()->isConstantInitializer(
  10067. Context, var->getType()->isReferenceType(), &CacheCulprit);
  10068. return *CacheHasConstInit;
  10069. };
  10070. if (var->getTLSKind() == VarDecl::TLS_Static) {
  10071. if (var->getType().isDestructedType()) {
  10072. // GNU C++98 edits for __thread, [basic.start.term]p3:
  10073. // The type of an object with thread storage duration shall not
  10074. // have a non-trivial destructor.
  10075. Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
  10076. if (getLangOpts().CPlusPlus11)
  10077. Diag(var->getLocation(), diag::note_use_thread_local);
  10078. } else if (getLangOpts().CPlusPlus && var->hasInit()) {
  10079. if (!checkConstInit()) {
  10080. // GNU C++98 edits for __thread, [basic.start.init]p4:
  10081. // An object of thread storage duration shall not require dynamic
  10082. // initialization.
  10083. // FIXME: Need strict checking here.
  10084. Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
  10085. << CacheCulprit->getSourceRange();
  10086. if (getLangOpts().CPlusPlus11)
  10087. Diag(var->getLocation(), diag::note_use_thread_local);
  10088. }
  10089. }
  10090. }
  10091. // Apply section attributes and pragmas to global variables.
  10092. bool GlobalStorage = var->hasGlobalStorage();
  10093. if (GlobalStorage && var->isThisDeclarationADefinition() &&
  10094. !inTemplateInstantiation()) {
  10095. PragmaStack<StringLiteral *> *Stack = nullptr;
  10096. int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
  10097. if (var->getType().isConstQualified())
  10098. Stack = &ConstSegStack;
  10099. else if (!var->getInit()) {
  10100. Stack = &BSSSegStack;
  10101. SectionFlags |= ASTContext::PSF_Write;
  10102. } else {
  10103. Stack = &DataSegStack;
  10104. SectionFlags |= ASTContext::PSF_Write;
  10105. }
  10106. if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
  10107. var->addAttr(SectionAttr::CreateImplicit(
  10108. Context, SectionAttr::Declspec_allocate,
  10109. Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
  10110. }
  10111. if (const SectionAttr *SA = var->getAttr<SectionAttr>())
  10112. if (UnifySection(SA->getName(), SectionFlags, var))
  10113. var->dropAttr<SectionAttr>();
  10114. // Apply the init_seg attribute if this has an initializer. If the
  10115. // initializer turns out to not be dynamic, we'll end up ignoring this
  10116. // attribute.
  10117. if (CurInitSeg && var->getInit())
  10118. var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
  10119. CurInitSegLoc));
  10120. }
  10121. // All the following checks are C++ only.
  10122. if (!getLangOpts().CPlusPlus) {
  10123. // If this variable must be emitted, add it as an initializer for the
  10124. // current module.
  10125. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10126. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10127. return;
  10128. }
  10129. if (auto *DD = dyn_cast<DecompositionDecl>(var))
  10130. CheckCompleteDecompositionDeclaration(DD);
  10131. QualType type = var->getType();
  10132. if (type->isDependentType()) return;
  10133. // __block variables might require us to capture a copy-initializer.
  10134. if (var->hasAttr<BlocksAttr>()) {
  10135. // It's currently invalid to ever have a __block variable with an
  10136. // array type; should we diagnose that here?
  10137. // Regardless, we don't want to ignore array nesting when
  10138. // constructing this copy.
  10139. if (type->isStructureOrClassType()) {
  10140. EnterExpressionEvaluationContext scope(
  10141. *this, ExpressionEvaluationContext::PotentiallyEvaluated);
  10142. SourceLocation poi = var->getLocation();
  10143. Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
  10144. ExprResult result
  10145. = PerformMoveOrCopyInitialization(
  10146. InitializedEntity::InitializeBlock(poi, type, false),
  10147. var, var->getType(), varRef, /*AllowNRVO=*/true);
  10148. if (!result.isInvalid()) {
  10149. result = MaybeCreateExprWithCleanups(result);
  10150. Expr *init = result.getAs<Expr>();
  10151. Context.setBlockVarCopyInits(var, init);
  10152. }
  10153. }
  10154. }
  10155. Expr *Init = var->getInit();
  10156. bool IsGlobal = GlobalStorage && !var->isStaticLocal();
  10157. QualType baseType = Context.getBaseElementType(type);
  10158. if (Init && !Init->isValueDependent()) {
  10159. if (var->isConstexpr()) {
  10160. SmallVector<PartialDiagnosticAt, 8> Notes;
  10161. if (!var->evaluateValue(Notes) || !var->isInitICE()) {
  10162. SourceLocation DiagLoc = var->getLocation();
  10163. // If the note doesn't add any useful information other than a source
  10164. // location, fold it into the primary diagnostic.
  10165. if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
  10166. diag::note_invalid_subexpr_in_const_expr) {
  10167. DiagLoc = Notes[0].first;
  10168. Notes.clear();
  10169. }
  10170. Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
  10171. << var << Init->getSourceRange();
  10172. for (unsigned I = 0, N = Notes.size(); I != N; ++I)
  10173. Diag(Notes[I].first, Notes[I].second);
  10174. }
  10175. } else if (var->isUsableInConstantExpressions(Context)) {
  10176. // Check whether the initializer of a const variable of integral or
  10177. // enumeration type is an ICE now, since we can't tell whether it was
  10178. // initialized by a constant expression if we check later.
  10179. var->checkInitIsICE();
  10180. }
  10181. // Don't emit further diagnostics about constexpr globals since they
  10182. // were just diagnosed.
  10183. if (!var->isConstexpr() && GlobalStorage &&
  10184. var->hasAttr<RequireConstantInitAttr>()) {
  10185. // FIXME: Need strict checking in C++03 here.
  10186. bool DiagErr = getLangOpts().CPlusPlus11
  10187. ? !var->checkInitIsICE() : !checkConstInit();
  10188. if (DiagErr) {
  10189. auto attr = var->getAttr<RequireConstantInitAttr>();
  10190. Diag(var->getLocation(), diag::err_require_constant_init_failed)
  10191. << Init->getSourceRange();
  10192. Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
  10193. << attr->getRange();
  10194. if (getLangOpts().CPlusPlus11) {
  10195. APValue Value;
  10196. SmallVector<PartialDiagnosticAt, 8> Notes;
  10197. Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
  10198. for (auto &it : Notes)
  10199. Diag(it.first, it.second);
  10200. } else {
  10201. Diag(CacheCulprit->getExprLoc(),
  10202. diag::note_invalid_subexpr_in_const_expr)
  10203. << CacheCulprit->getSourceRange();
  10204. }
  10205. }
  10206. }
  10207. else if (!var->isConstexpr() && IsGlobal &&
  10208. !getDiagnostics().isIgnored(diag::warn_global_constructor,
  10209. var->getLocation())) {
  10210. // Warn about globals which don't have a constant initializer. Don't
  10211. // warn about globals with a non-trivial destructor because we already
  10212. // warned about them.
  10213. CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
  10214. if (!(RD && !RD->hasTrivialDestructor())) {
  10215. if (!checkConstInit())
  10216. Diag(var->getLocation(), diag::warn_global_constructor)
  10217. << Init->getSourceRange();
  10218. }
  10219. }
  10220. }
  10221. // Require the destructor.
  10222. if (const RecordType *recordType = baseType->getAs<RecordType>())
  10223. FinalizeVarWithDestructor(var, recordType);
  10224. // If this variable must be emitted, add it as an initializer for the current
  10225. // module.
  10226. if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
  10227. Context.addModuleInitializer(ModuleScopes.back().Module, var);
  10228. }
  10229. /// Determines if a variable's alignment is dependent.
  10230. static bool hasDependentAlignment(VarDecl *VD) {
  10231. if (VD->getType()->isDependentType())
  10232. return true;
  10233. for (auto *I : VD->specific_attrs<AlignedAttr>())
  10234. if (I->isAlignmentDependent())
  10235. return true;
  10236. return false;
  10237. }
  10238. /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
  10239. /// any semantic actions necessary after any initializer has been attached.
  10240. void Sema::FinalizeDeclaration(Decl *ThisDecl) {
  10241. // Note that we are no longer parsing the initializer for this declaration.
  10242. ParsingInitForAutoVars.erase(ThisDecl);
  10243. VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
  10244. if (!VD)
  10245. return;
  10246. // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
  10247. if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
  10248. !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
  10249. if (PragmaClangBSSSection.Valid)
  10250. VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
  10251. PragmaClangBSSSection.SectionName,
  10252. PragmaClangBSSSection.PragmaLocation));
  10253. if (PragmaClangDataSection.Valid)
  10254. VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
  10255. PragmaClangDataSection.SectionName,
  10256. PragmaClangDataSection.PragmaLocation));
  10257. if (PragmaClangRodataSection.Valid)
  10258. VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
  10259. PragmaClangRodataSection.SectionName,
  10260. PragmaClangRodataSection.PragmaLocation));
  10261. }
  10262. if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
  10263. for (auto *BD : DD->bindings()) {
  10264. FinalizeDeclaration(BD);
  10265. }
  10266. }
  10267. checkAttributesAfterMerging(*this, *VD);
  10268. // Perform TLS alignment check here after attributes attached to the variable
  10269. // which may affect the alignment have been processed. Only perform the check
  10270. // if the target has a maximum TLS alignment (zero means no constraints).
  10271. if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
  10272. // Protect the check so that it's not performed on dependent types and
  10273. // dependent alignments (we can't determine the alignment in that case).
  10274. if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
  10275. !VD->isInvalidDecl()) {
  10276. CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
  10277. if (Context.getDeclAlign(VD) > MaxAlignChars) {
  10278. Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
  10279. << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
  10280. << (unsigned)MaxAlignChars.getQuantity();
  10281. }
  10282. }
  10283. }
  10284. if (VD->isStaticLocal()) {
  10285. if (FunctionDecl *FD =
  10286. dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
  10287. // Static locals inherit dll attributes from their function.
  10288. if (Attr *A = getDLLAttr(FD)) {
  10289. auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
  10290. NewAttr->setInherited(true);
  10291. VD->addAttr(NewAttr);
  10292. }
  10293. // CUDA E.2.9.4: Within the body of a __device__ or __global__
  10294. // function, only __shared__ variables may be declared with
  10295. // static storage class.
  10296. if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
  10297. CUDADiagIfDeviceCode(VD->getLocation(),
  10298. diag::err_device_static_local_var)
  10299. << CurrentCUDATarget())
  10300. VD->setInvalidDecl();
  10301. }
  10302. }
  10303. // Perform check for initializers of device-side global variables.
  10304. // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
  10305. // 7.5). We must also apply the same checks to all __shared__
  10306. // variables whether they are local or not. CUDA also allows
  10307. // constant initializers for __constant__ and __device__ variables.
  10308. if (getLangOpts().CUDA) {
  10309. const Expr *Init = VD->getInit();
  10310. if (Init && VD->hasGlobalStorage()) {
  10311. if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
  10312. VD->hasAttr<CUDASharedAttr>()) {
  10313. assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
  10314. bool AllowedInit = false;
  10315. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
  10316. AllowedInit =
  10317. isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
  10318. // We'll allow constant initializers even if it's a non-empty
  10319. // constructor according to CUDA rules. This deviates from NVCC,
  10320. // but allows us to handle things like constexpr constructors.
  10321. if (!AllowedInit &&
  10322. (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
  10323. AllowedInit = VD->getInit()->isConstantInitializer(
  10324. Context, VD->getType()->isReferenceType());
  10325. // Also make sure that destructor, if there is one, is empty.
  10326. if (AllowedInit)
  10327. if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
  10328. AllowedInit =
  10329. isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
  10330. if (!AllowedInit) {
  10331. Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
  10332. ? diag::err_shared_var_init
  10333. : diag::err_dynamic_var_init)
  10334. << Init->getSourceRange();
  10335. VD->setInvalidDecl();
  10336. }
  10337. } else {
  10338. // This is a host-side global variable. Check that the initializer is
  10339. // callable from the host side.
  10340. const FunctionDecl *InitFn = nullptr;
  10341. if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
  10342. InitFn = CE->getConstructor();
  10343. } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
  10344. InitFn = CE->getDirectCallee();
  10345. }
  10346. if (InitFn) {
  10347. CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
  10348. if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
  10349. Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
  10350. << InitFnTarget << InitFn;
  10351. Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
  10352. VD->setInvalidDecl();
  10353. }
  10354. }
  10355. }
  10356. }
  10357. }
  10358. // Grab the dllimport or dllexport attribute off of the VarDecl.
  10359. const InheritableAttr *DLLAttr = getDLLAttr(VD);
  10360. // Imported static data members cannot be defined out-of-line.
  10361. if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
  10362. if (VD->isStaticDataMember() && VD->isOutOfLine() &&
  10363. VD->isThisDeclarationADefinition()) {
  10364. // We allow definitions of dllimport class template static data members
  10365. // with a warning.
  10366. CXXRecordDecl *Context =
  10367. cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
  10368. bool IsClassTemplateMember =
  10369. isa<ClassTemplatePartialSpecializationDecl>(Context) ||
  10370. Context->getDescribedClassTemplate();
  10371. Diag(VD->getLocation(),
  10372. IsClassTemplateMember
  10373. ? diag::warn_attribute_dllimport_static_field_definition
  10374. : diag::err_attribute_dllimport_static_field_definition);
  10375. Diag(IA->getLocation(), diag::note_attribute);
  10376. if (!IsClassTemplateMember)
  10377. VD->setInvalidDecl();
  10378. }
  10379. }
  10380. // dllimport/dllexport variables cannot be thread local, their TLS index
  10381. // isn't exported with the variable.
  10382. if (DLLAttr && VD->getTLSKind()) {
  10383. auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
  10384. if (F && getDLLAttr(F)) {
  10385. assert(VD->isStaticLocal());
  10386. // But if this is a static local in a dlimport/dllexport function, the
  10387. // function will never be inlined, which means the var would never be
  10388. // imported, so having it marked import/export is safe.
  10389. } else {
  10390. Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
  10391. << DLLAttr;
  10392. VD->setInvalidDecl();
  10393. }
  10394. }
  10395. if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
  10396. if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
  10397. Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
  10398. VD->dropAttr<UsedAttr>();
  10399. }
  10400. }
  10401. const DeclContext *DC = VD->getDeclContext();
  10402. // If there's a #pragma GCC visibility in scope, and this isn't a class
  10403. // member, set the visibility of this variable.
  10404. if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
  10405. AddPushedVisibilityAttribute(VD);
  10406. // FIXME: Warn on unused var template partial specializations.
  10407. if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
  10408. MarkUnusedFileScopedDecl(VD);
  10409. // Now we have parsed the initializer and can update the table of magic
  10410. // tag values.
  10411. if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
  10412. !VD->getType()->isIntegralOrEnumerationType())
  10413. return;
  10414. for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
  10415. const Expr *MagicValueExpr = VD->getInit();
  10416. if (!MagicValueExpr) {
  10417. continue;
  10418. }
  10419. llvm::APSInt MagicValueInt;
  10420. if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
  10421. Diag(I->getRange().getBegin(),
  10422. diag::err_type_tag_for_datatype_not_ice)
  10423. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10424. continue;
  10425. }
  10426. if (MagicValueInt.getActiveBits() > 64) {
  10427. Diag(I->getRange().getBegin(),
  10428. diag::err_type_tag_for_datatype_too_large)
  10429. << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
  10430. continue;
  10431. }
  10432. uint64_t MagicValue = MagicValueInt.getZExtValue();
  10433. RegisterTypeTagForDatatype(I->getArgumentKind(),
  10434. MagicValue,
  10435. I->getMatchingCType(),
  10436. I->getLayoutCompatible(),
  10437. I->getMustBeNull());
  10438. }
  10439. }
  10440. static bool hasDeducedAuto(DeclaratorDecl *DD) {
  10441. auto *VD = dyn_cast<VarDecl>(DD);
  10442. return VD && !VD->getType()->hasAutoForTrailingReturnType();
  10443. }
  10444. Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
  10445. ArrayRef<Decl *> Group) {
  10446. SmallVector<Decl*, 8> Decls;
  10447. if (DS.isTypeSpecOwned())
  10448. Decls.push_back(DS.getRepAsDecl());
  10449. DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
  10450. DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
  10451. bool DiagnosedMultipleDecomps = false;
  10452. DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
  10453. bool DiagnosedNonDeducedAuto = false;
  10454. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10455. if (Decl *D = Group[i]) {
  10456. // For declarators, there are some additional syntactic-ish checks we need
  10457. // to perform.
  10458. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  10459. if (!FirstDeclaratorInGroup)
  10460. FirstDeclaratorInGroup = DD;
  10461. if (!FirstDecompDeclaratorInGroup)
  10462. FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
  10463. if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
  10464. !hasDeducedAuto(DD))
  10465. FirstNonDeducedAutoInGroup = DD;
  10466. if (FirstDeclaratorInGroup != DD) {
  10467. // A decomposition declaration cannot be combined with any other
  10468. // declaration in the same group.
  10469. if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
  10470. Diag(FirstDecompDeclaratorInGroup->getLocation(),
  10471. diag::err_decomp_decl_not_alone)
  10472. << FirstDeclaratorInGroup->getSourceRange()
  10473. << DD->getSourceRange();
  10474. DiagnosedMultipleDecomps = true;
  10475. }
  10476. // A declarator that uses 'auto' in any way other than to declare a
  10477. // variable with a deduced type cannot be combined with any other
  10478. // declarator in the same group.
  10479. if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
  10480. Diag(FirstNonDeducedAutoInGroup->getLocation(),
  10481. diag::err_auto_non_deduced_not_alone)
  10482. << FirstNonDeducedAutoInGroup->getType()
  10483. ->hasAutoForTrailingReturnType()
  10484. << FirstDeclaratorInGroup->getSourceRange()
  10485. << DD->getSourceRange();
  10486. DiagnosedNonDeducedAuto = true;
  10487. }
  10488. }
  10489. }
  10490. Decls.push_back(D);
  10491. }
  10492. }
  10493. if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
  10494. if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
  10495. handleTagNumbering(Tag, S);
  10496. if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
  10497. getLangOpts().CPlusPlus)
  10498. Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
  10499. }
  10500. }
  10501. return BuildDeclaratorGroup(Decls);
  10502. }
  10503. /// BuildDeclaratorGroup - convert a list of declarations into a declaration
  10504. /// group, performing any necessary semantic checking.
  10505. Sema::DeclGroupPtrTy
  10506. Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
  10507. // C++14 [dcl.spec.auto]p7: (DR1347)
  10508. // If the type that replaces the placeholder type is not the same in each
  10509. // deduction, the program is ill-formed.
  10510. if (Group.size() > 1) {
  10511. QualType Deduced;
  10512. VarDecl *DeducedDecl = nullptr;
  10513. for (unsigned i = 0, e = Group.size(); i != e; ++i) {
  10514. VarDecl *D = dyn_cast<VarDecl>(Group[i]);
  10515. if (!D || D->isInvalidDecl())
  10516. break;
  10517. DeducedType *DT = D->getType()->getContainedDeducedType();
  10518. if (!DT || DT->getDeducedType().isNull())
  10519. continue;
  10520. if (Deduced.isNull()) {
  10521. Deduced = DT->getDeducedType();
  10522. DeducedDecl = D;
  10523. } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
  10524. auto *AT = dyn_cast<AutoType>(DT);
  10525. Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
  10526. diag::err_auto_different_deductions)
  10527. << (AT ? (unsigned)AT->getKeyword() : 3)
  10528. << Deduced << DeducedDecl->getDeclName()
  10529. << DT->getDeducedType() << D->getDeclName()
  10530. << DeducedDecl->getInit()->getSourceRange()
  10531. << D->getInit()->getSourceRange();
  10532. D->setInvalidDecl();
  10533. break;
  10534. }
  10535. }
  10536. }
  10537. ActOnDocumentableDecls(Group);
  10538. return DeclGroupPtrTy::make(
  10539. DeclGroupRef::Create(Context, Group.data(), Group.size()));
  10540. }
  10541. void Sema::ActOnDocumentableDecl(Decl *D) {
  10542. ActOnDocumentableDecls(D);
  10543. }
  10544. void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
  10545. // Don't parse the comment if Doxygen diagnostics are ignored.
  10546. if (Group.empty() || !Group[0])
  10547. return;
  10548. if (Diags.isIgnored(diag::warn_doc_param_not_found,
  10549. Group[0]->getLocation()) &&
  10550. Diags.isIgnored(diag::warn_unknown_comment_command_name,
  10551. Group[0]->getLocation()))
  10552. return;
  10553. if (Group.size() >= 2) {
  10554. // This is a decl group. Normally it will contain only declarations
  10555. // produced from declarator list. But in case we have any definitions or
  10556. // additional declaration references:
  10557. // 'typedef struct S {} S;'
  10558. // 'typedef struct S *S;'
  10559. // 'struct S *pS;'
  10560. // FinalizeDeclaratorGroup adds these as separate declarations.
  10561. Decl *MaybeTagDecl = Group[0];
  10562. if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
  10563. Group = Group.slice(1);
  10564. }
  10565. }
  10566. // See if there are any new comments that are not attached to a decl.
  10567. ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
  10568. if (!Comments.empty() &&
  10569. !Comments.back()->isAttached()) {
  10570. // There is at least one comment that not attached to a decl.
  10571. // Maybe it should be attached to one of these decls?
  10572. //
  10573. // Note that this way we pick up not only comments that precede the
  10574. // declaration, but also comments that *follow* the declaration -- thanks to
  10575. // the lookahead in the lexer: we've consumed the semicolon and looked
  10576. // ahead through comments.
  10577. for (unsigned i = 0, e = Group.size(); i != e; ++i)
  10578. Context.getCommentForDecl(Group[i], &PP);
  10579. }
  10580. }
  10581. /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
  10582. /// to introduce parameters into function prototype scope.
  10583. Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
  10584. const DeclSpec &DS = D.getDeclSpec();
  10585. // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
  10586. // C++03 [dcl.stc]p2 also permits 'auto'.
  10587. StorageClass SC = SC_None;
  10588. if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
  10589. SC = SC_Register;
  10590. // In C++11, the 'register' storage class specifier is deprecated.
  10591. // In C++17, it is not allowed, but we tolerate it as an extension.
  10592. if (getLangOpts().CPlusPlus11) {
  10593. Diag(DS.getStorageClassSpecLoc(),
  10594. getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
  10595. : diag::warn_deprecated_register)
  10596. << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
  10597. }
  10598. } else if (getLangOpts().CPlusPlus &&
  10599. DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
  10600. SC = SC_Auto;
  10601. } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
  10602. Diag(DS.getStorageClassSpecLoc(),
  10603. diag::err_invalid_storage_class_in_func_decl);
  10604. D.getMutableDeclSpec().ClearStorageClassSpecs();
  10605. }
  10606. if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
  10607. Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
  10608. << DeclSpec::getSpecifierName(TSCS);
  10609. if (DS.isInlineSpecified())
  10610. Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
  10611. << getLangOpts().CPlusPlus17;
  10612. if (DS.isConstexprSpecified())
  10613. Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
  10614. << 0;
  10615. DiagnoseFunctionSpecifiers(DS);
  10616. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  10617. QualType parmDeclType = TInfo->getType();
  10618. if (getLangOpts().CPlusPlus) {
  10619. // Check that there are no default arguments inside the type of this
  10620. // parameter.
  10621. CheckExtraCXXDefaultArguments(D);
  10622. // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
  10623. if (D.getCXXScopeSpec().isSet()) {
  10624. Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
  10625. << D.getCXXScopeSpec().getRange();
  10626. D.getCXXScopeSpec().clear();
  10627. }
  10628. }
  10629. // Ensure we have a valid name
  10630. IdentifierInfo *II = nullptr;
  10631. if (D.hasName()) {
  10632. II = D.getIdentifier();
  10633. if (!II) {
  10634. Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
  10635. << GetNameForDeclarator(D).getName();
  10636. D.setInvalidType(true);
  10637. }
  10638. }
  10639. // Check for redeclaration of parameters, e.g. int foo(int x, int x);
  10640. if (II) {
  10641. LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
  10642. ForVisibleRedeclaration);
  10643. LookupName(R, S);
  10644. if (R.isSingleResult()) {
  10645. NamedDecl *PrevDecl = R.getFoundDecl();
  10646. if (PrevDecl->isTemplateParameter()) {
  10647. // Maybe we will complain about the shadowed template parameter.
  10648. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  10649. // Just pretend that we didn't see the previous declaration.
  10650. PrevDecl = nullptr;
  10651. } else if (S->isDeclScope(PrevDecl)) {
  10652. Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
  10653. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  10654. // Recover by removing the name
  10655. II = nullptr;
  10656. D.SetIdentifier(nullptr, D.getIdentifierLoc());
  10657. D.setInvalidType(true);
  10658. }
  10659. }
  10660. }
  10661. // Temporarily put parameter variables in the translation unit, not
  10662. // the enclosing context. This prevents them from accidentally
  10663. // looking like class members in C++.
  10664. ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
  10665. D.getLocStart(),
  10666. D.getIdentifierLoc(), II,
  10667. parmDeclType, TInfo,
  10668. SC);
  10669. if (D.isInvalidType())
  10670. New->setInvalidDecl();
  10671. assert(S->isFunctionPrototypeScope());
  10672. assert(S->getFunctionPrototypeDepth() >= 1);
  10673. New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
  10674. S->getNextFunctionPrototypeIndex());
  10675. // Add the parameter declaration into this scope.
  10676. S->AddDecl(New);
  10677. if (II)
  10678. IdResolver.AddDecl(New);
  10679. ProcessDeclAttributes(S, New, D);
  10680. if (D.getDeclSpec().isModulePrivateSpecified())
  10681. Diag(New->getLocation(), diag::err_module_private_local)
  10682. << 1 << New->getDeclName()
  10683. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  10684. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  10685. if (New->hasAttr<BlocksAttr>()) {
  10686. Diag(New->getLocation(), diag::err_block_on_nonlocal);
  10687. }
  10688. return New;
  10689. }
  10690. /// Synthesizes a variable for a parameter arising from a
  10691. /// typedef.
  10692. ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
  10693. SourceLocation Loc,
  10694. QualType T) {
  10695. /* FIXME: setting StartLoc == Loc.
  10696. Would it be worth to modify callers so as to provide proper source
  10697. location for the unnamed parameters, embedding the parameter's type? */
  10698. ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
  10699. T, Context.getTrivialTypeSourceInfo(T, Loc),
  10700. SC_None, nullptr);
  10701. Param->setImplicit();
  10702. return Param;
  10703. }
  10704. void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
  10705. // Don't diagnose unused-parameter errors in template instantiations; we
  10706. // will already have done so in the template itself.
  10707. if (inTemplateInstantiation())
  10708. return;
  10709. for (const ParmVarDecl *Parameter : Parameters) {
  10710. if (!Parameter->isReferenced() && Parameter->getDeclName() &&
  10711. !Parameter->hasAttr<UnusedAttr>()) {
  10712. Diag(Parameter->getLocation(), diag::warn_unused_parameter)
  10713. << Parameter->getDeclName();
  10714. }
  10715. }
  10716. }
  10717. void Sema::DiagnoseSizeOfParametersAndReturnValue(
  10718. ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
  10719. if (LangOpts.NumLargeByValueCopy == 0) // No check.
  10720. return;
  10721. // Warn if the return value is pass-by-value and larger than the specified
  10722. // threshold.
  10723. if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
  10724. unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
  10725. if (Size > LangOpts.NumLargeByValueCopy)
  10726. Diag(D->getLocation(), diag::warn_return_value_size)
  10727. << D->getDeclName() << Size;
  10728. }
  10729. // Warn if any parameter is pass-by-value and larger than the specified
  10730. // threshold.
  10731. for (const ParmVarDecl *Parameter : Parameters) {
  10732. QualType T = Parameter->getType();
  10733. if (T->isDependentType() || !T.isPODType(Context))
  10734. continue;
  10735. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  10736. if (Size > LangOpts.NumLargeByValueCopy)
  10737. Diag(Parameter->getLocation(), diag::warn_parameter_size)
  10738. << Parameter->getDeclName() << Size;
  10739. }
  10740. }
  10741. ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
  10742. SourceLocation NameLoc, IdentifierInfo *Name,
  10743. QualType T, TypeSourceInfo *TSInfo,
  10744. StorageClass SC) {
  10745. // In ARC, infer a lifetime qualifier for appropriate parameter types.
  10746. if (getLangOpts().ObjCAutoRefCount &&
  10747. T.getObjCLifetime() == Qualifiers::OCL_None &&
  10748. T->isObjCLifetimeType()) {
  10749. Qualifiers::ObjCLifetime lifetime;
  10750. // Special cases for arrays:
  10751. // - if it's const, use __unsafe_unretained
  10752. // - otherwise, it's an error
  10753. if (T->isArrayType()) {
  10754. if (!T.isConstQualified()) {
  10755. DelayedDiagnostics.add(
  10756. sema::DelayedDiagnostic::makeForbiddenType(
  10757. NameLoc, diag::err_arc_array_param_no_ownership, T, false));
  10758. }
  10759. lifetime = Qualifiers::OCL_ExplicitNone;
  10760. } else {
  10761. lifetime = T->getObjCARCImplicitLifetime();
  10762. }
  10763. T = Context.getLifetimeQualifiedType(T, lifetime);
  10764. }
  10765. ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
  10766. Context.getAdjustedParameterType(T),
  10767. TSInfo, SC, nullptr);
  10768. // Parameters can not be abstract class types.
  10769. // For record types, this is done by the AbstractClassUsageDiagnoser once
  10770. // the class has been completely parsed.
  10771. if (!CurContext->isRecord() &&
  10772. RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
  10773. AbstractParamType))
  10774. New->setInvalidDecl();
  10775. // Parameter declarators cannot be interface types. All ObjC objects are
  10776. // passed by reference.
  10777. if (T->isObjCObjectType()) {
  10778. SourceLocation TypeEndLoc =
  10779. getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
  10780. Diag(NameLoc,
  10781. diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
  10782. << FixItHint::CreateInsertion(TypeEndLoc, "*");
  10783. T = Context.getObjCObjectPointerType(T);
  10784. New->setType(T);
  10785. }
  10786. // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
  10787. // duration shall not be qualified by an address-space qualifier."
  10788. // Since all parameters have automatic store duration, they can not have
  10789. // an address space.
  10790. if (T.getAddressSpace() != LangAS::Default &&
  10791. // OpenCL allows function arguments declared to be an array of a type
  10792. // to be qualified with an address space.
  10793. !(getLangOpts().OpenCL &&
  10794. (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
  10795. Diag(NameLoc, diag::err_arg_with_address_space);
  10796. New->setInvalidDecl();
  10797. }
  10798. return New;
  10799. }
  10800. void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
  10801. SourceLocation LocAfterDecls) {
  10802. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
  10803. // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
  10804. // for a K&R function.
  10805. if (!FTI.hasPrototype) {
  10806. for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
  10807. --i;
  10808. if (FTI.Params[i].Param == nullptr) {
  10809. SmallString<256> Code;
  10810. llvm::raw_svector_ostream(Code)
  10811. << " int " << FTI.Params[i].Ident->getName() << ";\n";
  10812. Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
  10813. << FTI.Params[i].Ident
  10814. << FixItHint::CreateInsertion(LocAfterDecls, Code);
  10815. // Implicitly declare the argument as type 'int' for lack of a better
  10816. // type.
  10817. AttributeFactory attrs;
  10818. DeclSpec DS(attrs);
  10819. const char* PrevSpec; // unused
  10820. unsigned DiagID; // unused
  10821. DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
  10822. DiagID, Context.getPrintingPolicy());
  10823. // Use the identifier location for the type source range.
  10824. DS.SetRangeStart(FTI.Params[i].IdentLoc);
  10825. DS.SetRangeEnd(FTI.Params[i].IdentLoc);
  10826. Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
  10827. ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
  10828. FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
  10829. }
  10830. }
  10831. }
  10832. }
  10833. Decl *
  10834. Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
  10835. MultiTemplateParamsArg TemplateParameterLists,
  10836. SkipBodyInfo *SkipBody) {
  10837. assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
  10838. assert(D.isFunctionDeclarator() && "Not a function declarator!");
  10839. Scope *ParentScope = FnBodyScope->getParent();
  10840. D.setFunctionDefinitionKind(FDK_Definition);
  10841. Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
  10842. return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
  10843. }
  10844. void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
  10845. Consumer.HandleInlineFunctionDefinition(D);
  10846. }
  10847. static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
  10848. const FunctionDecl*& PossibleZeroParamPrototype) {
  10849. // Don't warn about invalid declarations.
  10850. if (FD->isInvalidDecl())
  10851. return false;
  10852. // Or declarations that aren't global.
  10853. if (!FD->isGlobal())
  10854. return false;
  10855. // Don't warn about C++ member functions.
  10856. if (isa<CXXMethodDecl>(FD))
  10857. return false;
  10858. // Don't warn about 'main'.
  10859. if (FD->isMain())
  10860. return false;
  10861. // Don't warn about inline functions.
  10862. if (FD->isInlined())
  10863. return false;
  10864. // Don't warn about function templates.
  10865. if (FD->getDescribedFunctionTemplate())
  10866. return false;
  10867. // Don't warn about function template specializations.
  10868. if (FD->isFunctionTemplateSpecialization())
  10869. return false;
  10870. // Don't warn for OpenCL kernels.
  10871. if (FD->hasAttr<OpenCLKernelAttr>())
  10872. return false;
  10873. // Don't warn on explicitly deleted functions.
  10874. if (FD->isDeleted())
  10875. return false;
  10876. bool MissingPrototype = true;
  10877. for (const FunctionDecl *Prev = FD->getPreviousDecl();
  10878. Prev; Prev = Prev->getPreviousDecl()) {
  10879. // Ignore any declarations that occur in function or method
  10880. // scope, because they aren't visible from the header.
  10881. if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
  10882. continue;
  10883. MissingPrototype = !Prev->getType()->isFunctionProtoType();
  10884. if (FD->getNumParams() == 0)
  10885. PossibleZeroParamPrototype = Prev;
  10886. break;
  10887. }
  10888. return MissingPrototype;
  10889. }
  10890. void
  10891. Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
  10892. const FunctionDecl *EffectiveDefinition,
  10893. SkipBodyInfo *SkipBody) {
  10894. const FunctionDecl *Definition = EffectiveDefinition;
  10895. if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
  10896. // If this is a friend function defined in a class template, it does not
  10897. // have a body until it is used, nevertheless it is a definition, see
  10898. // [temp.inst]p2:
  10899. //
  10900. // ... for the purpose of determining whether an instantiated redeclaration
  10901. // is valid according to [basic.def.odr] and [class.mem], a declaration that
  10902. // corresponds to a definition in the template is considered to be a
  10903. // definition.
  10904. //
  10905. // The following code must produce redefinition error:
  10906. //
  10907. // template<typename T> struct C20 { friend void func_20() {} };
  10908. // C20<int> c20i;
  10909. // void func_20() {}
  10910. //
  10911. for (auto I : FD->redecls()) {
  10912. if (I != FD && !I->isInvalidDecl() &&
  10913. I->getFriendObjectKind() != Decl::FOK_None) {
  10914. if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
  10915. if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
  10916. // A merged copy of the same function, instantiated as a member of
  10917. // the same class, is OK.
  10918. if (declaresSameEntity(OrigFD, Original) &&
  10919. declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
  10920. cast<Decl>(FD->getLexicalDeclContext())))
  10921. continue;
  10922. }
  10923. if (Original->isThisDeclarationADefinition()) {
  10924. Definition = I;
  10925. break;
  10926. }
  10927. }
  10928. }
  10929. }
  10930. }
  10931. if (!Definition)
  10932. return;
  10933. if (canRedefineFunction(Definition, getLangOpts()))
  10934. return;
  10935. // Don't emit an error when this is redefinition of a typo-corrected
  10936. // definition.
  10937. if (TypoCorrectedFunctionDefinitions.count(Definition))
  10938. return;
  10939. // If we don't have a visible definition of the function, and it's inline or
  10940. // a template, skip the new definition.
  10941. if (SkipBody && !hasVisibleDefinition(Definition) &&
  10942. (Definition->getFormalLinkage() == InternalLinkage ||
  10943. Definition->isInlined() ||
  10944. Definition->getDescribedFunctionTemplate() ||
  10945. Definition->getNumTemplateParameterLists())) {
  10946. SkipBody->ShouldSkip = true;
  10947. if (auto *TD = Definition->getDescribedFunctionTemplate())
  10948. makeMergedDefinitionVisible(TD);
  10949. makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
  10950. return;
  10951. }
  10952. if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
  10953. Definition->getStorageClass() == SC_Extern)
  10954. Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
  10955. << FD->getDeclName() << getLangOpts().CPlusPlus;
  10956. else
  10957. Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
  10958. Diag(Definition->getLocation(), diag::note_previous_definition);
  10959. FD->setInvalidDecl();
  10960. }
  10961. static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
  10962. Sema &S) {
  10963. CXXRecordDecl *const LambdaClass = CallOperator->getParent();
  10964. LambdaScopeInfo *LSI = S.PushLambdaScope();
  10965. LSI->CallOperator = CallOperator;
  10966. LSI->Lambda = LambdaClass;
  10967. LSI->ReturnType = CallOperator->getReturnType();
  10968. const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
  10969. if (LCD == LCD_None)
  10970. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
  10971. else if (LCD == LCD_ByCopy)
  10972. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
  10973. else if (LCD == LCD_ByRef)
  10974. LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
  10975. DeclarationNameInfo DNI = CallOperator->getNameInfo();
  10976. LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
  10977. LSI->Mutable = !CallOperator->isConst();
  10978. // Add the captures to the LSI so they can be noted as already
  10979. // captured within tryCaptureVar.
  10980. auto I = LambdaClass->field_begin();
  10981. for (const auto &C : LambdaClass->captures()) {
  10982. if (C.capturesVariable()) {
  10983. VarDecl *VD = C.getCapturedVar();
  10984. if (VD->isInitCapture())
  10985. S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
  10986. QualType CaptureType = VD->getType();
  10987. const bool ByRef = C.getCaptureKind() == LCK_ByRef;
  10988. LSI->addCapture(VD, /*IsBlock*/false, ByRef,
  10989. /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
  10990. /*EllipsisLoc*/C.isPackExpansion()
  10991. ? C.getEllipsisLoc() : SourceLocation(),
  10992. CaptureType, /*Expr*/ nullptr);
  10993. } else if (C.capturesThis()) {
  10994. LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
  10995. /*Expr*/ nullptr,
  10996. C.getCaptureKind() == LCK_StarThis);
  10997. } else {
  10998. LSI->addVLATypeCapture(C.getLocation(), I->getType());
  10999. }
  11000. ++I;
  11001. }
  11002. }
  11003. Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
  11004. SkipBodyInfo *SkipBody) {
  11005. if (!D) {
  11006. // Parsing the function declaration failed in some way. Push on a fake scope
  11007. // anyway so we can try to parse the function body.
  11008. PushFunctionScope();
  11009. return D;
  11010. }
  11011. FunctionDecl *FD = nullptr;
  11012. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
  11013. FD = FunTmpl->getTemplatedDecl();
  11014. else
  11015. FD = cast<FunctionDecl>(D);
  11016. // Check for defining attributes before the check for redefinition.
  11017. if (const auto *Attr = FD->getAttr<AliasAttr>()) {
  11018. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
  11019. FD->dropAttr<AliasAttr>();
  11020. FD->setInvalidDecl();
  11021. }
  11022. if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
  11023. Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
  11024. FD->dropAttr<IFuncAttr>();
  11025. FD->setInvalidDecl();
  11026. }
  11027. // See if this is a redefinition. If 'will have body' is already set, then
  11028. // these checks were already performed when it was set.
  11029. if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
  11030. CheckForFunctionRedefinition(FD, nullptr, SkipBody);
  11031. // If we're skipping the body, we're done. Don't enter the scope.
  11032. if (SkipBody && SkipBody->ShouldSkip)
  11033. return D;
  11034. }
  11035. // Mark this function as "will have a body eventually". This lets users to
  11036. // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
  11037. // this function.
  11038. FD->setWillHaveBody();
  11039. // If we are instantiating a generic lambda call operator, push
  11040. // a LambdaScopeInfo onto the function stack. But use the information
  11041. // that's already been calculated (ActOnLambdaExpr) to prime the current
  11042. // LambdaScopeInfo.
  11043. // When the template operator is being specialized, the LambdaScopeInfo,
  11044. // has to be properly restored so that tryCaptureVariable doesn't try
  11045. // and capture any new variables. In addition when calculating potential
  11046. // captures during transformation of nested lambdas, it is necessary to
  11047. // have the LSI properly restored.
  11048. if (isGenericLambdaCallOperatorSpecialization(FD)) {
  11049. assert(inTemplateInstantiation() &&
  11050. "There should be an active template instantiation on the stack "
  11051. "when instantiating a generic lambda!");
  11052. RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
  11053. } else {
  11054. // Enter a new function scope
  11055. PushFunctionScope();
  11056. }
  11057. // Builtin functions cannot be defined.
  11058. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11059. if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
  11060. !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
  11061. Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
  11062. FD->setInvalidDecl();
  11063. }
  11064. }
  11065. // The return type of a function definition must be complete
  11066. // (C99 6.9.1p3, C++ [dcl.fct]p6).
  11067. QualType ResultType = FD->getReturnType();
  11068. if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
  11069. !FD->isInvalidDecl() &&
  11070. RequireCompleteType(FD->getLocation(), ResultType,
  11071. diag::err_func_def_incomplete_result))
  11072. FD->setInvalidDecl();
  11073. if (FnBodyScope)
  11074. PushDeclContext(FnBodyScope, FD);
  11075. // Check the validity of our function parameters
  11076. CheckParmsForFunctionDef(FD->parameters(),
  11077. /*CheckParameterNames=*/true);
  11078. // Add non-parameter declarations already in the function to the current
  11079. // scope.
  11080. if (FnBodyScope) {
  11081. for (Decl *NPD : FD->decls()) {
  11082. auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
  11083. if (!NonParmDecl)
  11084. continue;
  11085. assert(!isa<ParmVarDecl>(NonParmDecl) &&
  11086. "parameters should not be in newly created FD yet");
  11087. // If the decl has a name, make it accessible in the current scope.
  11088. if (NonParmDecl->getDeclName())
  11089. PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
  11090. // Similarly, dive into enums and fish their constants out, making them
  11091. // accessible in this scope.
  11092. if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
  11093. for (auto *EI : ED->enumerators())
  11094. PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
  11095. }
  11096. }
  11097. }
  11098. // Introduce our parameters into the function scope
  11099. for (auto Param : FD->parameters()) {
  11100. Param->setOwningFunction(FD);
  11101. // If this has an identifier, add it to the scope stack.
  11102. if (Param->getIdentifier() && FnBodyScope) {
  11103. CheckShadow(FnBodyScope, Param);
  11104. PushOnScopeChains(Param, FnBodyScope);
  11105. }
  11106. }
  11107. // Ensure that the function's exception specification is instantiated.
  11108. if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
  11109. ResolveExceptionSpec(D->getLocation(), FPT);
  11110. // dllimport cannot be applied to non-inline function definitions.
  11111. if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
  11112. !FD->isTemplateInstantiation()) {
  11113. assert(!FD->hasAttr<DLLExportAttr>());
  11114. Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
  11115. FD->setInvalidDecl();
  11116. return D;
  11117. }
  11118. // We want to attach documentation to original Decl (which might be
  11119. // a function template).
  11120. ActOnDocumentableDecl(D);
  11121. if (getCurLexicalContext()->isObjCContainer() &&
  11122. getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
  11123. getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
  11124. Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
  11125. return D;
  11126. }
  11127. /// Given the set of return statements within a function body,
  11128. /// compute the variables that are subject to the named return value
  11129. /// optimization.
  11130. ///
  11131. /// Each of the variables that is subject to the named return value
  11132. /// optimization will be marked as NRVO variables in the AST, and any
  11133. /// return statement that has a marked NRVO variable as its NRVO candidate can
  11134. /// use the named return value optimization.
  11135. ///
  11136. /// This function applies a very simplistic algorithm for NRVO: if every return
  11137. /// statement in the scope of a variable has the same NRVO candidate, that
  11138. /// candidate is an NRVO variable.
  11139. void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
  11140. ReturnStmt **Returns = Scope->Returns.data();
  11141. for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
  11142. if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
  11143. if (!NRVOCandidate->isNRVOVariable())
  11144. Returns[I]->setNRVOCandidate(nullptr);
  11145. }
  11146. }
  11147. }
  11148. bool Sema::canDelayFunctionBody(const Declarator &D) {
  11149. // We can't delay parsing the body of a constexpr function template (yet).
  11150. if (D.getDeclSpec().isConstexprSpecified())
  11151. return false;
  11152. // We can't delay parsing the body of a function template with a deduced
  11153. // return type (yet).
  11154. if (D.getDeclSpec().hasAutoTypeSpec()) {
  11155. // If the placeholder introduces a non-deduced trailing return type,
  11156. // we can still delay parsing it.
  11157. if (D.getNumTypeObjects()) {
  11158. const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
  11159. if (Outer.Kind == DeclaratorChunk::Function &&
  11160. Outer.Fun.hasTrailingReturnType()) {
  11161. QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
  11162. return Ty.isNull() || !Ty->isUndeducedType();
  11163. }
  11164. }
  11165. return false;
  11166. }
  11167. return true;
  11168. }
  11169. bool Sema::canSkipFunctionBody(Decl *D) {
  11170. // We cannot skip the body of a function (or function template) which is
  11171. // constexpr, since we may need to evaluate its body in order to parse the
  11172. // rest of the file.
  11173. // We cannot skip the body of a function with an undeduced return type,
  11174. // because any callers of that function need to know the type.
  11175. if (const FunctionDecl *FD = D->getAsFunction())
  11176. if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
  11177. return false;
  11178. return Consumer.shouldSkipFunctionBody(D);
  11179. }
  11180. Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
  11181. if (!Decl)
  11182. return nullptr;
  11183. if (FunctionDecl *FD = Decl->getAsFunction())
  11184. FD->setHasSkippedBody();
  11185. else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
  11186. MD->setHasSkippedBody();
  11187. return Decl;
  11188. }
  11189. Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
  11190. return ActOnFinishFunctionBody(D, BodyArg, false);
  11191. }
  11192. Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
  11193. bool IsInstantiation) {
  11194. FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
  11195. sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
  11196. sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
  11197. if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
  11198. CheckCompletedCoroutineBody(FD, Body);
  11199. if (FD) {
  11200. FD->setBody(Body);
  11201. FD->setWillHaveBody(false);
  11202. if (getLangOpts().CPlusPlus14) {
  11203. if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
  11204. FD->getReturnType()->isUndeducedType()) {
  11205. // If the function has a deduced result type but contains no 'return'
  11206. // statements, the result type as written must be exactly 'auto', and
  11207. // the deduced result type is 'void'.
  11208. if (!FD->getReturnType()->getAs<AutoType>()) {
  11209. Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
  11210. << FD->getReturnType();
  11211. FD->setInvalidDecl();
  11212. } else {
  11213. // Substitute 'void' for the 'auto' in the type.
  11214. TypeLoc ResultType = getReturnTypeLoc(FD);
  11215. Context.adjustDeducedFunctionResultType(
  11216. FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
  11217. }
  11218. }
  11219. } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
  11220. // In C++11, we don't use 'auto' deduction rules for lambda call
  11221. // operators because we don't support return type deduction.
  11222. auto *LSI = getCurLambda();
  11223. if (LSI->HasImplicitReturnType) {
  11224. deduceClosureReturnType(*LSI);
  11225. // C++11 [expr.prim.lambda]p4:
  11226. // [...] if there are no return statements in the compound-statement
  11227. // [the deduced type is] the type void
  11228. QualType RetType =
  11229. LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
  11230. // Update the return type to the deduced type.
  11231. const FunctionProtoType *Proto =
  11232. FD->getType()->getAs<FunctionProtoType>();
  11233. FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
  11234. Proto->getExtProtoInfo()));
  11235. }
  11236. }
  11237. // If the function implicitly returns zero (like 'main') or is naked,
  11238. // don't complain about missing return statements.
  11239. if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
  11240. WP.disableCheckFallThrough();
  11241. // MSVC permits the use of pure specifier (=0) on function definition,
  11242. // defined at class scope, warn about this non-standard construct.
  11243. if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
  11244. Diag(FD->getLocation(), diag::ext_pure_function_definition);
  11245. if (!FD->isInvalidDecl()) {
  11246. // Don't diagnose unused parameters of defaulted or deleted functions.
  11247. if (!FD->isDeleted() && !FD->isDefaulted())
  11248. DiagnoseUnusedParameters(FD->parameters());
  11249. DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
  11250. FD->getReturnType(), FD);
  11251. // If this is a structor, we need a vtable.
  11252. if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
  11253. MarkVTableUsed(FD->getLocation(), Constructor->getParent());
  11254. else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
  11255. MarkVTableUsed(FD->getLocation(), Destructor->getParent());
  11256. // Try to apply the named return value optimization. We have to check
  11257. // if we can do this here because lambdas keep return statements around
  11258. // to deduce an implicit return type.
  11259. if (FD->getReturnType()->isRecordType() &&
  11260. (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
  11261. computeNRVO(Body, getCurFunction());
  11262. }
  11263. // GNU warning -Wmissing-prototypes:
  11264. // Warn if a global function is defined without a previous
  11265. // prototype declaration. This warning is issued even if the
  11266. // definition itself provides a prototype. The aim is to detect
  11267. // global functions that fail to be declared in header files.
  11268. const FunctionDecl *PossibleZeroParamPrototype = nullptr;
  11269. if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
  11270. Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
  11271. if (PossibleZeroParamPrototype) {
  11272. // We found a declaration that is not a prototype,
  11273. // but that could be a zero-parameter prototype
  11274. if (TypeSourceInfo *TI =
  11275. PossibleZeroParamPrototype->getTypeSourceInfo()) {
  11276. TypeLoc TL = TI->getTypeLoc();
  11277. if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
  11278. Diag(PossibleZeroParamPrototype->getLocation(),
  11279. diag::note_declaration_not_a_prototype)
  11280. << PossibleZeroParamPrototype
  11281. << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
  11282. }
  11283. }
  11284. // GNU warning -Wstrict-prototypes
  11285. // Warn if K&R function is defined without a previous declaration.
  11286. // This warning is issued only if the definition itself does not provide
  11287. // a prototype. Only K&R definitions do not provide a prototype.
  11288. // An empty list in a function declarator that is part of a definition
  11289. // of that function specifies that the function has no parameters
  11290. // (C99 6.7.5.3p14)
  11291. if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
  11292. !LangOpts.CPlusPlus) {
  11293. TypeSourceInfo *TI = FD->getTypeSourceInfo();
  11294. TypeLoc TL = TI->getTypeLoc();
  11295. FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
  11296. Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
  11297. }
  11298. }
  11299. if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  11300. const CXXMethodDecl *KeyFunction;
  11301. if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
  11302. MD->isVirtual() &&
  11303. (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
  11304. MD == KeyFunction->getCanonicalDecl()) {
  11305. // Update the key-function state if necessary for this ABI.
  11306. if (FD->isInlined() &&
  11307. !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  11308. Context.setNonKeyFunction(MD);
  11309. // If the newly-chosen key function is already defined, then we
  11310. // need to mark the vtable as used retroactively.
  11311. KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
  11312. const FunctionDecl *Definition;
  11313. if (KeyFunction && KeyFunction->isDefined(Definition))
  11314. MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
  11315. } else {
  11316. // We just defined they key function; mark the vtable as used.
  11317. MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
  11318. }
  11319. }
  11320. }
  11321. assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
  11322. "Function parsing confused");
  11323. } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
  11324. assert(MD == getCurMethodDecl() && "Method parsing confused");
  11325. MD->setBody(Body);
  11326. if (!MD->isInvalidDecl()) {
  11327. DiagnoseUnusedParameters(MD->parameters());
  11328. DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
  11329. MD->getReturnType(), MD);
  11330. if (Body)
  11331. computeNRVO(Body, getCurFunction());
  11332. }
  11333. if (getCurFunction()->ObjCShouldCallSuper) {
  11334. Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
  11335. << MD->getSelector().getAsString();
  11336. getCurFunction()->ObjCShouldCallSuper = false;
  11337. }
  11338. if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
  11339. const ObjCMethodDecl *InitMethod = nullptr;
  11340. bool isDesignated =
  11341. MD->isDesignatedInitializerForTheInterface(&InitMethod);
  11342. assert(isDesignated && InitMethod);
  11343. (void)isDesignated;
  11344. auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
  11345. auto IFace = MD->getClassInterface();
  11346. if (!IFace)
  11347. return false;
  11348. auto SuperD = IFace->getSuperClass();
  11349. if (!SuperD)
  11350. return false;
  11351. return SuperD->getIdentifier() ==
  11352. NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
  11353. };
  11354. // Don't issue this warning for unavailable inits or direct subclasses
  11355. // of NSObject.
  11356. if (!MD->isUnavailable() && !superIsNSObject(MD)) {
  11357. Diag(MD->getLocation(),
  11358. diag::warn_objc_designated_init_missing_super_call);
  11359. Diag(InitMethod->getLocation(),
  11360. diag::note_objc_designated_init_marked_here);
  11361. }
  11362. getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
  11363. }
  11364. if (getCurFunction()->ObjCWarnForNoInitDelegation) {
  11365. // Don't issue this warning for unavaialable inits.
  11366. if (!MD->isUnavailable())
  11367. Diag(MD->getLocation(),
  11368. diag::warn_objc_secondary_init_missing_init_call);
  11369. getCurFunction()->ObjCWarnForNoInitDelegation = false;
  11370. }
  11371. } else {
  11372. // Parsing the function declaration failed in some way. Pop the fake scope
  11373. // we pushed on.
  11374. PopFunctionScopeInfo(ActivePolicy, dcl);
  11375. return nullptr;
  11376. }
  11377. if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
  11378. DiagnoseUnguardedAvailabilityViolations(dcl);
  11379. assert(!getCurFunction()->ObjCShouldCallSuper &&
  11380. "This should only be set for ObjC methods, which should have been "
  11381. "handled in the block above.");
  11382. // Verify and clean out per-function state.
  11383. if (Body && (!FD || !FD->isDefaulted())) {
  11384. // C++ constructors that have function-try-blocks can't have return
  11385. // statements in the handlers of that block. (C++ [except.handle]p14)
  11386. // Verify this.
  11387. if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
  11388. DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
  11389. // Verify that gotos and switch cases don't jump into scopes illegally.
  11390. if (getCurFunction()->NeedsScopeChecking() &&
  11391. !PP.isCodeCompletionEnabled())
  11392. DiagnoseInvalidJumps(Body);
  11393. if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
  11394. if (!Destructor->getParent()->isDependentType())
  11395. CheckDestructor(Destructor);
  11396. MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
  11397. Destructor->getParent());
  11398. }
  11399. // If any errors have occurred, clear out any temporaries that may have
  11400. // been leftover. This ensures that these temporaries won't be picked up for
  11401. // deletion in some later function.
  11402. if (getDiagnostics().hasErrorOccurred() ||
  11403. getDiagnostics().getSuppressAllDiagnostics()) {
  11404. DiscardCleanupsInEvaluationContext();
  11405. }
  11406. if (!getDiagnostics().hasUncompilableErrorOccurred() &&
  11407. !isa<FunctionTemplateDecl>(dcl)) {
  11408. // Since the body is valid, issue any analysis-based warnings that are
  11409. // enabled.
  11410. ActivePolicy = &WP;
  11411. }
  11412. if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
  11413. (!CheckConstexprFunctionDecl(FD) ||
  11414. !CheckConstexprFunctionBody(FD, Body)))
  11415. FD->setInvalidDecl();
  11416. if (FD && FD->hasAttr<NakedAttr>()) {
  11417. for (const Stmt *S : Body->children()) {
  11418. // Allow local register variables without initializer as they don't
  11419. // require prologue.
  11420. bool RegisterVariables = false;
  11421. if (auto *DS = dyn_cast<DeclStmt>(S)) {
  11422. for (const auto *Decl : DS->decls()) {
  11423. if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
  11424. RegisterVariables =
  11425. Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
  11426. if (!RegisterVariables)
  11427. break;
  11428. }
  11429. }
  11430. }
  11431. if (RegisterVariables)
  11432. continue;
  11433. if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
  11434. Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
  11435. Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  11436. FD->setInvalidDecl();
  11437. break;
  11438. }
  11439. }
  11440. }
  11441. assert(ExprCleanupObjects.size() ==
  11442. ExprEvalContexts.back().NumCleanupObjects &&
  11443. "Leftover temporaries in function");
  11444. assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
  11445. assert(MaybeODRUseExprs.empty() &&
  11446. "Leftover expressions for odr-use checking");
  11447. }
  11448. if (!IsInstantiation)
  11449. PopDeclContext();
  11450. PopFunctionScopeInfo(ActivePolicy, dcl);
  11451. // If any errors have occurred, clear out any temporaries that may have
  11452. // been leftover. This ensures that these temporaries won't be picked up for
  11453. // deletion in some later function.
  11454. if (getDiagnostics().hasErrorOccurred()) {
  11455. DiscardCleanupsInEvaluationContext();
  11456. }
  11457. return dcl;
  11458. }
  11459. /// When we finish delayed parsing of an attribute, we must attach it to the
  11460. /// relevant Decl.
  11461. void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
  11462. ParsedAttributes &Attrs) {
  11463. // Always attach attributes to the underlying decl.
  11464. if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  11465. D = TD->getTemplatedDecl();
  11466. ProcessDeclAttributeList(S, D, Attrs.getList());
  11467. if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
  11468. if (Method->isStatic())
  11469. checkThisInStaticMemberFunctionAttributes(Method);
  11470. }
  11471. /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
  11472. /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
  11473. NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
  11474. IdentifierInfo &II, Scope *S) {
  11475. // Find the scope in which the identifier is injected and the corresponding
  11476. // DeclContext.
  11477. // FIXME: C89 does not say what happens if there is no enclosing block scope.
  11478. // In that case, we inject the declaration into the translation unit scope
  11479. // instead.
  11480. Scope *BlockScope = S;
  11481. while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
  11482. BlockScope = BlockScope->getParent();
  11483. Scope *ContextScope = BlockScope;
  11484. while (!ContextScope->getEntity())
  11485. ContextScope = ContextScope->getParent();
  11486. ContextRAII SavedContext(*this, ContextScope->getEntity());
  11487. // Before we produce a declaration for an implicitly defined
  11488. // function, see whether there was a locally-scoped declaration of
  11489. // this name as a function or variable. If so, use that
  11490. // (non-visible) declaration, and complain about it.
  11491. NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
  11492. if (ExternCPrev) {
  11493. // We still need to inject the function into the enclosing block scope so
  11494. // that later (non-call) uses can see it.
  11495. PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
  11496. // C89 footnote 38:
  11497. // If in fact it is not defined as having type "function returning int",
  11498. // the behavior is undefined.
  11499. if (!isa<FunctionDecl>(ExternCPrev) ||
  11500. !Context.typesAreCompatible(
  11501. cast<FunctionDecl>(ExternCPrev)->getType(),
  11502. Context.getFunctionNoProtoType(Context.IntTy))) {
  11503. Diag(Loc, diag::ext_use_out_of_scope_declaration)
  11504. << ExternCPrev << !getLangOpts().C99;
  11505. Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
  11506. return ExternCPrev;
  11507. }
  11508. }
  11509. // Extension in C99. Legal in C90, but warn about it.
  11510. // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
  11511. unsigned diag_id;
  11512. if (II.getName().startswith("__builtin_"))
  11513. diag_id = diag::warn_builtin_unknown;
  11514. else if (getLangOpts().C99 || getLangOpts().OpenCL)
  11515. diag_id = diag::ext_implicit_function_decl;
  11516. else
  11517. diag_id = diag::warn_implicit_function_decl;
  11518. Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
  11519. // If we found a prior declaration of this function, don't bother building
  11520. // another one. We've already pushed that one into scope, so there's nothing
  11521. // more to do.
  11522. if (ExternCPrev)
  11523. return ExternCPrev;
  11524. // Because typo correction is expensive, only do it if the implicit
  11525. // function declaration is going to be treated as an error.
  11526. if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
  11527. TypoCorrection Corrected;
  11528. if (S &&
  11529. (Corrected = CorrectTypo(
  11530. DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
  11531. llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
  11532. diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
  11533. /*ErrorRecovery*/false);
  11534. }
  11535. // Set a Declarator for the implicit definition: int foo();
  11536. const char *Dummy;
  11537. AttributeFactory attrFactory;
  11538. DeclSpec DS(attrFactory);
  11539. unsigned DiagID;
  11540. bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
  11541. Context.getPrintingPolicy());
  11542. (void)Error; // Silence warning.
  11543. assert(!Error && "Error setting up implicit decl!");
  11544. SourceLocation NoLoc;
  11545. Declarator D(DS, DeclaratorContext::BlockContext);
  11546. D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
  11547. /*IsAmbiguous=*/false,
  11548. /*LParenLoc=*/NoLoc,
  11549. /*Params=*/nullptr,
  11550. /*NumParams=*/0,
  11551. /*EllipsisLoc=*/NoLoc,
  11552. /*RParenLoc=*/NoLoc,
  11553. /*TypeQuals=*/0,
  11554. /*RefQualifierIsLvalueRef=*/true,
  11555. /*RefQualifierLoc=*/NoLoc,
  11556. /*ConstQualifierLoc=*/NoLoc,
  11557. /*VolatileQualifierLoc=*/NoLoc,
  11558. /*RestrictQualifierLoc=*/NoLoc,
  11559. /*MutableLoc=*/NoLoc,
  11560. EST_None,
  11561. /*ESpecRange=*/SourceRange(),
  11562. /*Exceptions=*/nullptr,
  11563. /*ExceptionRanges=*/nullptr,
  11564. /*NumExceptions=*/0,
  11565. /*NoexceptExpr=*/nullptr,
  11566. /*ExceptionSpecTokens=*/nullptr,
  11567. /*DeclsInPrototype=*/None,
  11568. Loc, Loc, D),
  11569. DS.getAttributes(),
  11570. SourceLocation());
  11571. D.SetIdentifier(&II, Loc);
  11572. // Insert this function into the enclosing block scope.
  11573. FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
  11574. FD->setImplicit();
  11575. AddKnownFunctionAttributes(FD);
  11576. return FD;
  11577. }
  11578. /// Adds any function attributes that we know a priori based on
  11579. /// the declaration of this function.
  11580. ///
  11581. /// These attributes can apply both to implicitly-declared builtins
  11582. /// (like __builtin___printf_chk) or to library-declared functions
  11583. /// like NSLog or printf.
  11584. ///
  11585. /// We need to check for duplicate attributes both here and where user-written
  11586. /// attributes are applied to declarations.
  11587. void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
  11588. if (FD->isInvalidDecl())
  11589. return;
  11590. // If this is a built-in function, map its builtin attributes to
  11591. // actual attributes.
  11592. if (unsigned BuiltinID = FD->getBuiltinID()) {
  11593. // Handle printf-formatting attributes.
  11594. unsigned FormatIdx;
  11595. bool HasVAListArg;
  11596. if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
  11597. if (!FD->hasAttr<FormatAttr>()) {
  11598. const char *fmt = "printf";
  11599. unsigned int NumParams = FD->getNumParams();
  11600. if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
  11601. FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
  11602. fmt = "NSString";
  11603. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11604. &Context.Idents.get(fmt),
  11605. FormatIdx+1,
  11606. HasVAListArg ? 0 : FormatIdx+2,
  11607. FD->getLocation()));
  11608. }
  11609. }
  11610. if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
  11611. HasVAListArg)) {
  11612. if (!FD->hasAttr<FormatAttr>())
  11613. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11614. &Context.Idents.get("scanf"),
  11615. FormatIdx+1,
  11616. HasVAListArg ? 0 : FormatIdx+2,
  11617. FD->getLocation()));
  11618. }
  11619. // Mark const if we don't care about errno and that is the only thing
  11620. // preventing the function from being const. This allows IRgen to use LLVM
  11621. // intrinsics for such functions.
  11622. if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
  11623. Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
  11624. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11625. // We make "fma" on some platforms const because we know it does not set
  11626. // errno in those environments even though it could set errno based on the
  11627. // C standard.
  11628. const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
  11629. if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
  11630. !FD->hasAttr<ConstAttr>()) {
  11631. switch (BuiltinID) {
  11632. case Builtin::BI__builtin_fma:
  11633. case Builtin::BI__builtin_fmaf:
  11634. case Builtin::BI__builtin_fmal:
  11635. case Builtin::BIfma:
  11636. case Builtin::BIfmaf:
  11637. case Builtin::BIfmal:
  11638. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11639. break;
  11640. default:
  11641. break;
  11642. }
  11643. }
  11644. if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
  11645. !FD->hasAttr<ReturnsTwiceAttr>())
  11646. FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
  11647. FD->getLocation()));
  11648. if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
  11649. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11650. if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
  11651. FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
  11652. if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
  11653. FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
  11654. if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
  11655. !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
  11656. // Add the appropriate attribute, depending on the CUDA compilation mode
  11657. // and which target the builtin belongs to. For example, during host
  11658. // compilation, aux builtins are __device__, while the rest are __host__.
  11659. if (getLangOpts().CUDAIsDevice !=
  11660. Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
  11661. FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
  11662. else
  11663. FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
  11664. }
  11665. }
  11666. // If C++ exceptions are enabled but we are told extern "C" functions cannot
  11667. // throw, add an implicit nothrow attribute to any extern "C" function we come
  11668. // across.
  11669. if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
  11670. FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
  11671. const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  11672. if (!FPT || FPT->getExceptionSpecType() == EST_None)
  11673. FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
  11674. }
  11675. IdentifierInfo *Name = FD->getIdentifier();
  11676. if (!Name)
  11677. return;
  11678. if ((!getLangOpts().CPlusPlus &&
  11679. FD->getDeclContext()->isTranslationUnit()) ||
  11680. (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
  11681. cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
  11682. LinkageSpecDecl::lang_c)) {
  11683. // Okay: this could be a libc/libm/Objective-C function we know
  11684. // about.
  11685. } else
  11686. return;
  11687. if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
  11688. // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
  11689. // target-specific builtins, perhaps?
  11690. if (!FD->hasAttr<FormatAttr>())
  11691. FD->addAttr(FormatAttr::CreateImplicit(Context,
  11692. &Context.Idents.get("printf"), 2,
  11693. Name->isStr("vasprintf") ? 0 : 3,
  11694. FD->getLocation()));
  11695. }
  11696. if (Name->isStr("__CFStringMakeConstantString")) {
  11697. // We already have a __builtin___CFStringMakeConstantString,
  11698. // but builds that use -fno-constant-cfstrings don't go through that.
  11699. if (!FD->hasAttr<FormatArgAttr>())
  11700. FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
  11701. FD->getLocation()));
  11702. }
  11703. }
  11704. TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
  11705. TypeSourceInfo *TInfo) {
  11706. assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
  11707. assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
  11708. if (!TInfo) {
  11709. assert(D.isInvalidType() && "no declarator info for valid type");
  11710. TInfo = Context.getTrivialTypeSourceInfo(T);
  11711. }
  11712. // Scope manipulation handled by caller.
  11713. TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
  11714. D.getLocStart(),
  11715. D.getIdentifierLoc(),
  11716. D.getIdentifier(),
  11717. TInfo);
  11718. // Bail out immediately if we have an invalid declaration.
  11719. if (D.isInvalidType()) {
  11720. NewTD->setInvalidDecl();
  11721. return NewTD;
  11722. }
  11723. if (D.getDeclSpec().isModulePrivateSpecified()) {
  11724. if (CurContext->isFunctionOrMethod())
  11725. Diag(NewTD->getLocation(), diag::err_module_private_local)
  11726. << 2 << NewTD->getDeclName()
  11727. << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
  11728. << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
  11729. else
  11730. NewTD->setModulePrivate();
  11731. }
  11732. // C++ [dcl.typedef]p8:
  11733. // If the typedef declaration defines an unnamed class (or
  11734. // enum), the first typedef-name declared by the declaration
  11735. // to be that class type (or enum type) is used to denote the
  11736. // class type (or enum type) for linkage purposes only.
  11737. // We need to check whether the type was declared in the declaration.
  11738. switch (D.getDeclSpec().getTypeSpecType()) {
  11739. case TST_enum:
  11740. case TST_struct:
  11741. case TST_interface:
  11742. case TST_union:
  11743. case TST_class: {
  11744. TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  11745. setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
  11746. break;
  11747. }
  11748. default:
  11749. break;
  11750. }
  11751. return NewTD;
  11752. }
  11753. /// Check that this is a valid underlying type for an enum declaration.
  11754. bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
  11755. SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
  11756. QualType T = TI->getType();
  11757. if (T->isDependentType())
  11758. return false;
  11759. if (const BuiltinType *BT = T->getAs<BuiltinType>())
  11760. if (BT->isInteger())
  11761. return false;
  11762. Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
  11763. return true;
  11764. }
  11765. /// Check whether this is a valid redeclaration of a previous enumeration.
  11766. /// \return true if the redeclaration was invalid.
  11767. bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
  11768. QualType EnumUnderlyingTy, bool IsFixed,
  11769. const EnumDecl *Prev) {
  11770. if (IsScoped != Prev->isScoped()) {
  11771. Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
  11772. << Prev->isScoped();
  11773. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11774. return true;
  11775. }
  11776. if (IsFixed && Prev->isFixed()) {
  11777. if (!EnumUnderlyingTy->isDependentType() &&
  11778. !Prev->getIntegerType()->isDependentType() &&
  11779. !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
  11780. Prev->getIntegerType())) {
  11781. // TODO: Highlight the underlying type of the redeclaration.
  11782. Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
  11783. << EnumUnderlyingTy << Prev->getIntegerType();
  11784. Diag(Prev->getLocation(), diag::note_previous_declaration)
  11785. << Prev->getIntegerTypeRange();
  11786. return true;
  11787. }
  11788. } else if (IsFixed != Prev->isFixed()) {
  11789. Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
  11790. << Prev->isFixed();
  11791. Diag(Prev->getLocation(), diag::note_previous_declaration);
  11792. return true;
  11793. }
  11794. return false;
  11795. }
  11796. /// Get diagnostic %select index for tag kind for
  11797. /// redeclaration diagnostic message.
  11798. /// WARNING: Indexes apply to particular diagnostics only!
  11799. ///
  11800. /// \returns diagnostic %select index.
  11801. static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
  11802. switch (Tag) {
  11803. case TTK_Struct: return 0;
  11804. case TTK_Interface: return 1;
  11805. case TTK_Class: return 2;
  11806. default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
  11807. }
  11808. }
  11809. /// Determine if tag kind is a class-key compatible with
  11810. /// class for redeclaration (class, struct, or __interface).
  11811. ///
  11812. /// \returns true iff the tag kind is compatible.
  11813. static bool isClassCompatTagKind(TagTypeKind Tag)
  11814. {
  11815. return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
  11816. }
  11817. Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
  11818. TagTypeKind TTK) {
  11819. if (isa<TypedefDecl>(PrevDecl))
  11820. return NTK_Typedef;
  11821. else if (isa<TypeAliasDecl>(PrevDecl))
  11822. return NTK_TypeAlias;
  11823. else if (isa<ClassTemplateDecl>(PrevDecl))
  11824. return NTK_Template;
  11825. else if (isa<TypeAliasTemplateDecl>(PrevDecl))
  11826. return NTK_TypeAliasTemplate;
  11827. else if (isa<TemplateTemplateParmDecl>(PrevDecl))
  11828. return NTK_TemplateTemplateArgument;
  11829. switch (TTK) {
  11830. case TTK_Struct:
  11831. case TTK_Interface:
  11832. case TTK_Class:
  11833. return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
  11834. case TTK_Union:
  11835. return NTK_NonUnion;
  11836. case TTK_Enum:
  11837. return NTK_NonEnum;
  11838. }
  11839. llvm_unreachable("invalid TTK");
  11840. }
  11841. /// Determine whether a tag with a given kind is acceptable
  11842. /// as a redeclaration of the given tag declaration.
  11843. ///
  11844. /// \returns true if the new tag kind is acceptable, false otherwise.
  11845. bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
  11846. TagTypeKind NewTag, bool isDefinition,
  11847. SourceLocation NewTagLoc,
  11848. const IdentifierInfo *Name) {
  11849. // C++ [dcl.type.elab]p3:
  11850. // The class-key or enum keyword present in the
  11851. // elaborated-type-specifier shall agree in kind with the
  11852. // declaration to which the name in the elaborated-type-specifier
  11853. // refers. This rule also applies to the form of
  11854. // elaborated-type-specifier that declares a class-name or
  11855. // friend class since it can be construed as referring to the
  11856. // definition of the class. Thus, in any
  11857. // elaborated-type-specifier, the enum keyword shall be used to
  11858. // refer to an enumeration (7.2), the union class-key shall be
  11859. // used to refer to a union (clause 9), and either the class or
  11860. // struct class-key shall be used to refer to a class (clause 9)
  11861. // declared using the class or struct class-key.
  11862. TagTypeKind OldTag = Previous->getTagKind();
  11863. if (!isDefinition || !isClassCompatTagKind(NewTag))
  11864. if (OldTag == NewTag)
  11865. return true;
  11866. if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
  11867. // Warn about the struct/class tag mismatch.
  11868. bool isTemplate = false;
  11869. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
  11870. isTemplate = Record->getDescribedClassTemplate();
  11871. if (inTemplateInstantiation()) {
  11872. // In a template instantiation, do not offer fix-its for tag mismatches
  11873. // since they usually mess up the template instead of fixing the problem.
  11874. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11875. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11876. << getRedeclDiagFromTagKind(OldTag);
  11877. return true;
  11878. }
  11879. if (isDefinition) {
  11880. // On definitions, check previous tags and issue a fix-it for each
  11881. // one that doesn't match the current tag.
  11882. if (Previous->getDefinition()) {
  11883. // Don't suggest fix-its for redefinitions.
  11884. return true;
  11885. }
  11886. bool previousMismatch = false;
  11887. for (auto I : Previous->redecls()) {
  11888. if (I->getTagKind() != NewTag) {
  11889. if (!previousMismatch) {
  11890. previousMismatch = true;
  11891. Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
  11892. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11893. << getRedeclDiagFromTagKind(I->getTagKind());
  11894. }
  11895. Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
  11896. << getRedeclDiagFromTagKind(NewTag)
  11897. << FixItHint::CreateReplacement(I->getInnerLocStart(),
  11898. TypeWithKeyword::getTagTypeKindName(NewTag));
  11899. }
  11900. }
  11901. return true;
  11902. }
  11903. // Check for a previous definition. If current tag and definition
  11904. // are same type, do nothing. If no definition, but disagree with
  11905. // with previous tag type, give a warning, but no fix-it.
  11906. const TagDecl *Redecl = Previous->getDefinition() ?
  11907. Previous->getDefinition() : Previous;
  11908. if (Redecl->getTagKind() == NewTag) {
  11909. return true;
  11910. }
  11911. Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
  11912. << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
  11913. << getRedeclDiagFromTagKind(OldTag);
  11914. Diag(Redecl->getLocation(), diag::note_previous_use);
  11915. // If there is a previous definition, suggest a fix-it.
  11916. if (Previous->getDefinition()) {
  11917. Diag(NewTagLoc, diag::note_struct_class_suggestion)
  11918. << getRedeclDiagFromTagKind(Redecl->getTagKind())
  11919. << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
  11920. TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
  11921. }
  11922. return true;
  11923. }
  11924. return false;
  11925. }
  11926. /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
  11927. /// from an outer enclosing namespace or file scope inside a friend declaration.
  11928. /// This should provide the commented out code in the following snippet:
  11929. /// namespace N {
  11930. /// struct X;
  11931. /// namespace M {
  11932. /// struct Y { friend struct /*N::*/ X; };
  11933. /// }
  11934. /// }
  11935. static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
  11936. SourceLocation NameLoc) {
  11937. // While the decl is in a namespace, do repeated lookup of that name and see
  11938. // if we get the same namespace back. If we do not, continue until
  11939. // translation unit scope, at which point we have a fully qualified NNS.
  11940. SmallVector<IdentifierInfo *, 4> Namespaces;
  11941. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  11942. for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
  11943. // This tag should be declared in a namespace, which can only be enclosed by
  11944. // other namespaces. Bail if there's an anonymous namespace in the chain.
  11945. NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
  11946. if (!Namespace || Namespace->isAnonymousNamespace())
  11947. return FixItHint();
  11948. IdentifierInfo *II = Namespace->getIdentifier();
  11949. Namespaces.push_back(II);
  11950. NamedDecl *Lookup = SemaRef.LookupSingleName(
  11951. S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
  11952. if (Lookup == Namespace)
  11953. break;
  11954. }
  11955. // Once we have all the namespaces, reverse them to go outermost first, and
  11956. // build an NNS.
  11957. SmallString<64> Insertion;
  11958. llvm::raw_svector_ostream OS(Insertion);
  11959. if (DC->isTranslationUnit())
  11960. OS << "::";
  11961. std::reverse(Namespaces.begin(), Namespaces.end());
  11962. for (auto *II : Namespaces)
  11963. OS << II->getName() << "::";
  11964. return FixItHint::CreateInsertion(NameLoc, Insertion);
  11965. }
  11966. /// Determine whether a tag originally declared in context \p OldDC can
  11967. /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
  11968. /// found a declaration in \p OldDC as a previous decl, perhaps through a
  11969. /// using-declaration).
  11970. static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
  11971. DeclContext *NewDC) {
  11972. OldDC = OldDC->getRedeclContext();
  11973. NewDC = NewDC->getRedeclContext();
  11974. if (OldDC->Equals(NewDC))
  11975. return true;
  11976. // In MSVC mode, we allow a redeclaration if the contexts are related (either
  11977. // encloses the other).
  11978. if (S.getLangOpts().MSVCCompat &&
  11979. (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
  11980. return true;
  11981. return false;
  11982. }
  11983. /// This is invoked when we see 'struct foo' or 'struct {'. In the
  11984. /// former case, Name will be non-null. In the later case, Name will be null.
  11985. /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
  11986. /// reference/declaration/definition of a tag.
  11987. ///
  11988. /// \param IsTypeSpecifier \c true if this is a type-specifier (or
  11989. /// trailing-type-specifier) other than one in an alias-declaration.
  11990. ///
  11991. /// \param SkipBody If non-null, will be set to indicate if the caller should
  11992. /// skip the definition of this tag and treat it as if it were a declaration.
  11993. Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
  11994. SourceLocation KWLoc, CXXScopeSpec &SS,
  11995. IdentifierInfo *Name, SourceLocation NameLoc,
  11996. AttributeList *Attr, AccessSpecifier AS,
  11997. SourceLocation ModulePrivateLoc,
  11998. MultiTemplateParamsArg TemplateParameterLists,
  11999. bool &OwnedDecl, bool &IsDependent,
  12000. SourceLocation ScopedEnumKWLoc,
  12001. bool ScopedEnumUsesClassTag,
  12002. TypeResult UnderlyingType,
  12003. bool IsTypeSpecifier, bool IsTemplateParamOrArg,
  12004. SkipBodyInfo *SkipBody) {
  12005. // If this is not a definition, it must have a name.
  12006. IdentifierInfo *OrigName = Name;
  12007. assert((Name != nullptr || TUK == TUK_Definition) &&
  12008. "Nameless record must be a definition!");
  12009. assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
  12010. OwnedDecl = false;
  12011. TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
  12012. bool ScopedEnum = ScopedEnumKWLoc.isValid();
  12013. // FIXME: Check member specializations more carefully.
  12014. bool isMemberSpecialization = false;
  12015. bool Invalid = false;
  12016. // We only need to do this matching if we have template parameters
  12017. // or a scope specifier, which also conveniently avoids this work
  12018. // for non-C++ cases.
  12019. if (TemplateParameterLists.size() > 0 ||
  12020. (SS.isNotEmpty() && TUK != TUK_Reference)) {
  12021. if (TemplateParameterList *TemplateParams =
  12022. MatchTemplateParametersToScopeSpecifier(
  12023. KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
  12024. TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
  12025. if (Kind == TTK_Enum) {
  12026. Diag(KWLoc, diag::err_enum_template);
  12027. return nullptr;
  12028. }
  12029. if (TemplateParams->size() > 0) {
  12030. // This is a declaration or definition of a class template (which may
  12031. // be a member of another template).
  12032. if (Invalid)
  12033. return nullptr;
  12034. OwnedDecl = false;
  12035. DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
  12036. SS, Name, NameLoc, Attr,
  12037. TemplateParams, AS,
  12038. ModulePrivateLoc,
  12039. /*FriendLoc*/SourceLocation(),
  12040. TemplateParameterLists.size()-1,
  12041. TemplateParameterLists.data(),
  12042. SkipBody);
  12043. return Result.get();
  12044. } else {
  12045. // The "template<>" header is extraneous.
  12046. Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
  12047. << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
  12048. isMemberSpecialization = true;
  12049. }
  12050. }
  12051. }
  12052. // Figure out the underlying type if this a enum declaration. We need to do
  12053. // this early, because it's needed to detect if this is an incompatible
  12054. // redeclaration.
  12055. llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
  12056. bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
  12057. if (Kind == TTK_Enum) {
  12058. if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
  12059. // No underlying type explicitly specified, or we failed to parse the
  12060. // type, default to int.
  12061. EnumUnderlying = Context.IntTy.getTypePtr();
  12062. } else if (UnderlyingType.get()) {
  12063. // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
  12064. // integral type; any cv-qualification is ignored.
  12065. TypeSourceInfo *TI = nullptr;
  12066. GetTypeFromParser(UnderlyingType.get(), &TI);
  12067. EnumUnderlying = TI;
  12068. if (CheckEnumUnderlyingType(TI))
  12069. // Recover by falling back to int.
  12070. EnumUnderlying = Context.IntTy.getTypePtr();
  12071. if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
  12072. UPPC_FixedUnderlyingType))
  12073. EnumUnderlying = Context.IntTy.getTypePtr();
  12074. } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  12075. // For MSVC ABI compatibility, unfixed enums must use an underlying type
  12076. // of 'int'. However, if this is an unfixed forward declaration, don't set
  12077. // the underlying type unless the user enables -fms-compatibility. This
  12078. // makes unfixed forward declared enums incomplete and is more conforming.
  12079. if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
  12080. EnumUnderlying = Context.IntTy.getTypePtr();
  12081. }
  12082. }
  12083. DeclContext *SearchDC = CurContext;
  12084. DeclContext *DC = CurContext;
  12085. bool isStdBadAlloc = false;
  12086. bool isStdAlignValT = false;
  12087. RedeclarationKind Redecl = forRedeclarationInCurContext();
  12088. if (TUK == TUK_Friend || TUK == TUK_Reference)
  12089. Redecl = NotForRedeclaration;
  12090. /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
  12091. /// implemented asks for structural equivalence checking, the returned decl
  12092. /// here is passed back to the parser, allowing the tag body to be parsed.
  12093. auto createTagFromNewDecl = [&]() -> TagDecl * {
  12094. assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
  12095. // If there is an identifier, use the location of the identifier as the
  12096. // location of the decl, otherwise use the location of the struct/union
  12097. // keyword.
  12098. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12099. TagDecl *New = nullptr;
  12100. if (Kind == TTK_Enum) {
  12101. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
  12102. ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
  12103. // If this is an undefined enum, bail.
  12104. if (TUK != TUK_Definition && !Invalid)
  12105. return nullptr;
  12106. if (EnumUnderlying) {
  12107. EnumDecl *ED = cast<EnumDecl>(New);
  12108. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
  12109. ED->setIntegerTypeSourceInfo(TI);
  12110. else
  12111. ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
  12112. ED->setPromotionType(ED->getIntegerType());
  12113. }
  12114. } else { // struct/union
  12115. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12116. nullptr);
  12117. }
  12118. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12119. // Add alignment attributes if necessary; these attributes are checked
  12120. // when the ASTContext lays out the structure.
  12121. //
  12122. // It is important for implementing the correct semantics that this
  12123. // happen here (in ActOnTag). The #pragma pack stack is
  12124. // maintained as a result of parser callbacks which can occur at
  12125. // many points during the parsing of a struct declaration (because
  12126. // the #pragma tokens are effectively skipped over during the
  12127. // parsing of the struct).
  12128. if (TUK == TUK_Definition) {
  12129. AddAlignmentAttributesForRecord(RD);
  12130. AddMsStructLayoutForRecord(RD);
  12131. }
  12132. }
  12133. New->setLexicalDeclContext(CurContext);
  12134. return New;
  12135. };
  12136. LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
  12137. if (Name && SS.isNotEmpty()) {
  12138. // We have a nested-name tag ('struct foo::bar').
  12139. // Check for invalid 'foo::'.
  12140. if (SS.isInvalid()) {
  12141. Name = nullptr;
  12142. goto CreateNewDecl;
  12143. }
  12144. // If this is a friend or a reference to a class in a dependent
  12145. // context, don't try to make a decl for it.
  12146. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12147. DC = computeDeclContext(SS, false);
  12148. if (!DC) {
  12149. IsDependent = true;
  12150. return nullptr;
  12151. }
  12152. } else {
  12153. DC = computeDeclContext(SS, true);
  12154. if (!DC) {
  12155. Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
  12156. << SS.getRange();
  12157. return nullptr;
  12158. }
  12159. }
  12160. if (RequireCompleteDeclContext(SS, DC))
  12161. return nullptr;
  12162. SearchDC = DC;
  12163. // Look-up name inside 'foo::'.
  12164. LookupQualifiedName(Previous, DC);
  12165. if (Previous.isAmbiguous())
  12166. return nullptr;
  12167. if (Previous.empty()) {
  12168. // Name lookup did not find anything. However, if the
  12169. // nested-name-specifier refers to the current instantiation,
  12170. // and that current instantiation has any dependent base
  12171. // classes, we might find something at instantiation time: treat
  12172. // this as a dependent elaborated-type-specifier.
  12173. // But this only makes any sense for reference-like lookups.
  12174. if (Previous.wasNotFoundInCurrentInstantiation() &&
  12175. (TUK == TUK_Reference || TUK == TUK_Friend)) {
  12176. IsDependent = true;
  12177. return nullptr;
  12178. }
  12179. // A tag 'foo::bar' must already exist.
  12180. Diag(NameLoc, diag::err_not_tag_in_scope)
  12181. << Kind << Name << DC << SS.getRange();
  12182. Name = nullptr;
  12183. Invalid = true;
  12184. goto CreateNewDecl;
  12185. }
  12186. } else if (Name) {
  12187. // C++14 [class.mem]p14:
  12188. // If T is the name of a class, then each of the following shall have a
  12189. // name different from T:
  12190. // -- every member of class T that is itself a type
  12191. if (TUK != TUK_Reference && TUK != TUK_Friend &&
  12192. DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
  12193. return nullptr;
  12194. // If this is a named struct, check to see if there was a previous forward
  12195. // declaration or definition.
  12196. // FIXME: We're looking into outer scopes here, even when we
  12197. // shouldn't be. Doing so can result in ambiguities that we
  12198. // shouldn't be diagnosing.
  12199. LookupName(Previous, S);
  12200. // When declaring or defining a tag, ignore ambiguities introduced
  12201. // by types using'ed into this scope.
  12202. if (Previous.isAmbiguous() &&
  12203. (TUK == TUK_Definition || TUK == TUK_Declaration)) {
  12204. LookupResult::Filter F = Previous.makeFilter();
  12205. while (F.hasNext()) {
  12206. NamedDecl *ND = F.next();
  12207. if (!ND->getDeclContext()->getRedeclContext()->Equals(
  12208. SearchDC->getRedeclContext()))
  12209. F.erase();
  12210. }
  12211. F.done();
  12212. }
  12213. // C++11 [namespace.memdef]p3:
  12214. // If the name in a friend declaration is neither qualified nor
  12215. // a template-id and the declaration is a function or an
  12216. // elaborated-type-specifier, the lookup to determine whether
  12217. // the entity has been previously declared shall not consider
  12218. // any scopes outside the innermost enclosing namespace.
  12219. //
  12220. // MSVC doesn't implement the above rule for types, so a friend tag
  12221. // declaration may be a redeclaration of a type declared in an enclosing
  12222. // scope. They do implement this rule for friend functions.
  12223. //
  12224. // Does it matter that this should be by scope instead of by
  12225. // semantic context?
  12226. if (!Previous.empty() && TUK == TUK_Friend) {
  12227. DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
  12228. LookupResult::Filter F = Previous.makeFilter();
  12229. bool FriendSawTagOutsideEnclosingNamespace = false;
  12230. while (F.hasNext()) {
  12231. NamedDecl *ND = F.next();
  12232. DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  12233. if (DC->isFileContext() &&
  12234. !EnclosingNS->Encloses(ND->getDeclContext())) {
  12235. if (getLangOpts().MSVCCompat)
  12236. FriendSawTagOutsideEnclosingNamespace = true;
  12237. else
  12238. F.erase();
  12239. }
  12240. }
  12241. F.done();
  12242. // Diagnose this MSVC extension in the easy case where lookup would have
  12243. // unambiguously found something outside the enclosing namespace.
  12244. if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
  12245. NamedDecl *ND = Previous.getFoundDecl();
  12246. Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
  12247. << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
  12248. }
  12249. }
  12250. // Note: there used to be some attempt at recovery here.
  12251. if (Previous.isAmbiguous())
  12252. return nullptr;
  12253. if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
  12254. // FIXME: This makes sure that we ignore the contexts associated
  12255. // with C structs, unions, and enums when looking for a matching
  12256. // tag declaration or definition. See the similar lookup tweak
  12257. // in Sema::LookupName; is there a better way to deal with this?
  12258. while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
  12259. SearchDC = SearchDC->getParent();
  12260. }
  12261. }
  12262. if (Previous.isSingleResult() &&
  12263. Previous.getFoundDecl()->isTemplateParameter()) {
  12264. // Maybe we will complain about the shadowed template parameter.
  12265. DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
  12266. // Just pretend that we didn't see the previous declaration.
  12267. Previous.clear();
  12268. }
  12269. if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
  12270. DC->Equals(getStdNamespace())) {
  12271. if (Name->isStr("bad_alloc")) {
  12272. // This is a declaration of or a reference to "std::bad_alloc".
  12273. isStdBadAlloc = true;
  12274. // If std::bad_alloc has been implicitly declared (but made invisible to
  12275. // name lookup), fill in this implicit declaration as the previous
  12276. // declaration, so that the declarations get chained appropriately.
  12277. if (Previous.empty() && StdBadAlloc)
  12278. Previous.addDecl(getStdBadAlloc());
  12279. } else if (Name->isStr("align_val_t")) {
  12280. isStdAlignValT = true;
  12281. if (Previous.empty() && StdAlignValT)
  12282. Previous.addDecl(getStdAlignValT());
  12283. }
  12284. }
  12285. // If we didn't find a previous declaration, and this is a reference
  12286. // (or friend reference), move to the correct scope. In C++, we
  12287. // also need to do a redeclaration lookup there, just in case
  12288. // there's a shadow friend decl.
  12289. if (Name && Previous.empty() &&
  12290. (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
  12291. if (Invalid) goto CreateNewDecl;
  12292. assert(SS.isEmpty());
  12293. if (TUK == TUK_Reference || IsTemplateParamOrArg) {
  12294. // C++ [basic.scope.pdecl]p5:
  12295. // -- for an elaborated-type-specifier of the form
  12296. //
  12297. // class-key identifier
  12298. //
  12299. // if the elaborated-type-specifier is used in the
  12300. // decl-specifier-seq or parameter-declaration-clause of a
  12301. // function defined in namespace scope, the identifier is
  12302. // declared as a class-name in the namespace that contains
  12303. // the declaration; otherwise, except as a friend
  12304. // declaration, the identifier is declared in the smallest
  12305. // non-class, non-function-prototype scope that contains the
  12306. // declaration.
  12307. //
  12308. // C99 6.7.2.3p8 has a similar (but not identical!) provision for
  12309. // C structs and unions.
  12310. //
  12311. // It is an error in C++ to declare (rather than define) an enum
  12312. // type, including via an elaborated type specifier. We'll
  12313. // diagnose that later; for now, declare the enum in the same
  12314. // scope as we would have picked for any other tag type.
  12315. //
  12316. // GNU C also supports this behavior as part of its incomplete
  12317. // enum types extension, while GNU C++ does not.
  12318. //
  12319. // Find the context where we'll be declaring the tag.
  12320. // FIXME: We would like to maintain the current DeclContext as the
  12321. // lexical context,
  12322. SearchDC = getTagInjectionContext(SearchDC);
  12323. // Find the scope where we'll be declaring the tag.
  12324. S = getTagInjectionScope(S, getLangOpts());
  12325. } else {
  12326. assert(TUK == TUK_Friend);
  12327. // C++ [namespace.memdef]p3:
  12328. // If a friend declaration in a non-local class first declares a
  12329. // class or function, the friend class or function is a member of
  12330. // the innermost enclosing namespace.
  12331. SearchDC = SearchDC->getEnclosingNamespaceContext();
  12332. }
  12333. // In C++, we need to do a redeclaration lookup to properly
  12334. // diagnose some problems.
  12335. // FIXME: redeclaration lookup is also used (with and without C++) to find a
  12336. // hidden declaration so that we don't get ambiguity errors when using a
  12337. // type declared by an elaborated-type-specifier. In C that is not correct
  12338. // and we should instead merge compatible types found by lookup.
  12339. if (getLangOpts().CPlusPlus) {
  12340. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12341. LookupQualifiedName(Previous, SearchDC);
  12342. } else {
  12343. Previous.setRedeclarationKind(forRedeclarationInCurContext());
  12344. LookupName(Previous, S);
  12345. }
  12346. }
  12347. // If we have a known previous declaration to use, then use it.
  12348. if (Previous.empty() && SkipBody && SkipBody->Previous)
  12349. Previous.addDecl(SkipBody->Previous);
  12350. if (!Previous.empty()) {
  12351. NamedDecl *PrevDecl = Previous.getFoundDecl();
  12352. NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
  12353. // It's okay to have a tag decl in the same scope as a typedef
  12354. // which hides a tag decl in the same scope. Finding this
  12355. // insanity with a redeclaration lookup can only actually happen
  12356. // in C++.
  12357. //
  12358. // This is also okay for elaborated-type-specifiers, which is
  12359. // technically forbidden by the current standard but which is
  12360. // okay according to the likely resolution of an open issue;
  12361. // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
  12362. if (getLangOpts().CPlusPlus) {
  12363. if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12364. if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
  12365. TagDecl *Tag = TT->getDecl();
  12366. if (Tag->getDeclName() == Name &&
  12367. Tag->getDeclContext()->getRedeclContext()
  12368. ->Equals(TD->getDeclContext()->getRedeclContext())) {
  12369. PrevDecl = Tag;
  12370. Previous.clear();
  12371. Previous.addDecl(Tag);
  12372. Previous.resolveKind();
  12373. }
  12374. }
  12375. }
  12376. }
  12377. // If this is a redeclaration of a using shadow declaration, it must
  12378. // declare a tag in the same context. In MSVC mode, we allow a
  12379. // redefinition if either context is within the other.
  12380. if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
  12381. auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
  12382. if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
  12383. isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
  12384. !(OldTag && isAcceptableTagRedeclContext(
  12385. *this, OldTag->getDeclContext(), SearchDC))) {
  12386. Diag(KWLoc, diag::err_using_decl_conflict_reverse);
  12387. Diag(Shadow->getTargetDecl()->getLocation(),
  12388. diag::note_using_decl_target);
  12389. Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
  12390. << 0;
  12391. // Recover by ignoring the old declaration.
  12392. Previous.clear();
  12393. goto CreateNewDecl;
  12394. }
  12395. }
  12396. if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
  12397. // If this is a use of a previous tag, or if the tag is already declared
  12398. // in the same scope (so that the definition/declaration completes or
  12399. // rementions the tag), reuse the decl.
  12400. if (TUK == TUK_Reference || TUK == TUK_Friend ||
  12401. isDeclInScope(DirectPrevDecl, SearchDC, S,
  12402. SS.isNotEmpty() || isMemberSpecialization)) {
  12403. // Make sure that this wasn't declared as an enum and now used as a
  12404. // struct or something similar.
  12405. if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
  12406. TUK == TUK_Definition, KWLoc,
  12407. Name)) {
  12408. bool SafeToContinue
  12409. = (PrevTagDecl->getTagKind() != TTK_Enum &&
  12410. Kind != TTK_Enum);
  12411. if (SafeToContinue)
  12412. Diag(KWLoc, diag::err_use_with_wrong_tag)
  12413. << Name
  12414. << FixItHint::CreateReplacement(SourceRange(KWLoc),
  12415. PrevTagDecl->getKindName());
  12416. else
  12417. Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
  12418. Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
  12419. if (SafeToContinue)
  12420. Kind = PrevTagDecl->getTagKind();
  12421. else {
  12422. // Recover by making this an anonymous redefinition.
  12423. Name = nullptr;
  12424. Previous.clear();
  12425. Invalid = true;
  12426. }
  12427. }
  12428. if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
  12429. const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
  12430. // If this is an elaborated-type-specifier for a scoped enumeration,
  12431. // the 'class' keyword is not necessary and not permitted.
  12432. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12433. if (ScopedEnum)
  12434. Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
  12435. << PrevEnum->isScoped()
  12436. << FixItHint::CreateRemoval(ScopedEnumKWLoc);
  12437. return PrevTagDecl;
  12438. }
  12439. QualType EnumUnderlyingTy;
  12440. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12441. EnumUnderlyingTy = TI->getType().getUnqualifiedType();
  12442. else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
  12443. EnumUnderlyingTy = QualType(T, 0);
  12444. // All conflicts with previous declarations are recovered by
  12445. // returning the previous declaration, unless this is a definition,
  12446. // in which case we want the caller to bail out.
  12447. if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
  12448. ScopedEnum, EnumUnderlyingTy,
  12449. IsFixed, PrevEnum))
  12450. return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
  12451. }
  12452. // C++11 [class.mem]p1:
  12453. // A member shall not be declared twice in the member-specification,
  12454. // except that a nested class or member class template can be declared
  12455. // and then later defined.
  12456. if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
  12457. S->isDeclScope(PrevDecl)) {
  12458. Diag(NameLoc, diag::ext_member_redeclared);
  12459. Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
  12460. }
  12461. if (!Invalid) {
  12462. // If this is a use, just return the declaration we found, unless
  12463. // we have attributes.
  12464. if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12465. if (Attr) {
  12466. // FIXME: Diagnose these attributes. For now, we create a new
  12467. // declaration to hold them.
  12468. } else if (TUK == TUK_Reference &&
  12469. (PrevTagDecl->getFriendObjectKind() ==
  12470. Decl::FOK_Undeclared ||
  12471. PrevDecl->getOwningModule() != getCurrentModule()) &&
  12472. SS.isEmpty()) {
  12473. // This declaration is a reference to an existing entity, but
  12474. // has different visibility from that entity: it either makes
  12475. // a friend visible or it makes a type visible in a new module.
  12476. // In either case, create a new declaration. We only do this if
  12477. // the declaration would have meant the same thing if no prior
  12478. // declaration were found, that is, if it was found in the same
  12479. // scope where we would have injected a declaration.
  12480. if (!getTagInjectionContext(CurContext)->getRedeclContext()
  12481. ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
  12482. return PrevTagDecl;
  12483. // This is in the injected scope, create a new declaration in
  12484. // that scope.
  12485. S = getTagInjectionScope(S, getLangOpts());
  12486. } else {
  12487. return PrevTagDecl;
  12488. }
  12489. }
  12490. // Diagnose attempts to redefine a tag.
  12491. if (TUK == TUK_Definition) {
  12492. if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
  12493. // If we're defining a specialization and the previous definition
  12494. // is from an implicit instantiation, don't emit an error
  12495. // here; we'll catch this in the general case below.
  12496. bool IsExplicitSpecializationAfterInstantiation = false;
  12497. if (isMemberSpecialization) {
  12498. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
  12499. IsExplicitSpecializationAfterInstantiation =
  12500. RD->getTemplateSpecializationKind() !=
  12501. TSK_ExplicitSpecialization;
  12502. else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
  12503. IsExplicitSpecializationAfterInstantiation =
  12504. ED->getTemplateSpecializationKind() !=
  12505. TSK_ExplicitSpecialization;
  12506. }
  12507. // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
  12508. // not keep more that one definition around (merge them). However,
  12509. // ensure the decl passes the structural compatibility check in
  12510. // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
  12511. NamedDecl *Hidden = nullptr;
  12512. if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
  12513. // There is a definition of this tag, but it is not visible. We
  12514. // explicitly make use of C++'s one definition rule here, and
  12515. // assume that this definition is identical to the hidden one
  12516. // we already have. Make the existing definition visible and
  12517. // use it in place of this one.
  12518. if (!getLangOpts().CPlusPlus) {
  12519. // Postpone making the old definition visible until after we
  12520. // complete parsing the new one and do the structural
  12521. // comparison.
  12522. SkipBody->CheckSameAsPrevious = true;
  12523. SkipBody->New = createTagFromNewDecl();
  12524. SkipBody->Previous = Hidden;
  12525. } else {
  12526. SkipBody->ShouldSkip = true;
  12527. makeMergedDefinitionVisible(Hidden);
  12528. }
  12529. return Def;
  12530. } else if (!IsExplicitSpecializationAfterInstantiation) {
  12531. // A redeclaration in function prototype scope in C isn't
  12532. // visible elsewhere, so merely issue a warning.
  12533. if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
  12534. Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
  12535. else
  12536. Diag(NameLoc, diag::err_redefinition) << Name;
  12537. notePreviousDefinition(Def,
  12538. NameLoc.isValid() ? NameLoc : KWLoc);
  12539. // If this is a redefinition, recover by making this
  12540. // struct be anonymous, which will make any later
  12541. // references get the previous definition.
  12542. Name = nullptr;
  12543. Previous.clear();
  12544. Invalid = true;
  12545. }
  12546. } else {
  12547. // If the type is currently being defined, complain
  12548. // about a nested redefinition.
  12549. auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
  12550. if (TD->isBeingDefined()) {
  12551. Diag(NameLoc, diag::err_nested_redefinition) << Name;
  12552. Diag(PrevTagDecl->getLocation(),
  12553. diag::note_previous_definition);
  12554. Name = nullptr;
  12555. Previous.clear();
  12556. Invalid = true;
  12557. }
  12558. }
  12559. // Okay, this is definition of a previously declared or referenced
  12560. // tag. We're going to create a new Decl for it.
  12561. }
  12562. // Okay, we're going to make a redeclaration. If this is some kind
  12563. // of reference, make sure we build the redeclaration in the same DC
  12564. // as the original, and ignore the current access specifier.
  12565. if (TUK == TUK_Friend || TUK == TUK_Reference) {
  12566. SearchDC = PrevTagDecl->getDeclContext();
  12567. AS = AS_none;
  12568. }
  12569. }
  12570. // If we get here we have (another) forward declaration or we
  12571. // have a definition. Just create a new decl.
  12572. } else {
  12573. // If we get here, this is a definition of a new tag type in a nested
  12574. // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
  12575. // new decl/type. We set PrevDecl to NULL so that the entities
  12576. // have distinct types.
  12577. Previous.clear();
  12578. }
  12579. // If we get here, we're going to create a new Decl. If PrevDecl
  12580. // is non-NULL, it's a definition of the tag declared by
  12581. // PrevDecl. If it's NULL, we have a new definition.
  12582. // Otherwise, PrevDecl is not a tag, but was found with tag
  12583. // lookup. This is only actually possible in C++, where a few
  12584. // things like templates still live in the tag namespace.
  12585. } else {
  12586. // Use a better diagnostic if an elaborated-type-specifier
  12587. // found the wrong kind of type on the first
  12588. // (non-redeclaration) lookup.
  12589. if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
  12590. !Previous.isForRedeclaration()) {
  12591. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12592. Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
  12593. << Kind;
  12594. Diag(PrevDecl->getLocation(), diag::note_declared_at);
  12595. Invalid = true;
  12596. // Otherwise, only diagnose if the declaration is in scope.
  12597. } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
  12598. SS.isNotEmpty() || isMemberSpecialization)) {
  12599. // do nothing
  12600. // Diagnose implicit declarations introduced by elaborated types.
  12601. } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
  12602. NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
  12603. Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
  12604. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12605. Invalid = true;
  12606. // Otherwise it's a declaration. Call out a particularly common
  12607. // case here.
  12608. } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
  12609. unsigned Kind = 0;
  12610. if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
  12611. Diag(NameLoc, diag::err_tag_definition_of_typedef)
  12612. << Name << Kind << TND->getUnderlyingType();
  12613. Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
  12614. Invalid = true;
  12615. // Otherwise, diagnose.
  12616. } else {
  12617. // The tag name clashes with something else in the target scope,
  12618. // issue an error and recover by making this tag be anonymous.
  12619. Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
  12620. notePreviousDefinition(PrevDecl, NameLoc);
  12621. Name = nullptr;
  12622. Invalid = true;
  12623. }
  12624. // The existing declaration isn't relevant to us; we're in a
  12625. // new scope, so clear out the previous declaration.
  12626. Previous.clear();
  12627. }
  12628. }
  12629. CreateNewDecl:
  12630. TagDecl *PrevDecl = nullptr;
  12631. if (Previous.isSingleResult())
  12632. PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
  12633. // If there is an identifier, use the location of the identifier as the
  12634. // location of the decl, otherwise use the location of the struct/union
  12635. // keyword.
  12636. SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
  12637. // Otherwise, create a new declaration. If there is a previous
  12638. // declaration of the same entity, the two will be linked via
  12639. // PrevDecl.
  12640. TagDecl *New;
  12641. bool IsForwardReference = false;
  12642. if (Kind == TTK_Enum) {
  12643. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12644. // enum X { A, B, C } D; D should chain to X.
  12645. New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
  12646. cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
  12647. ScopedEnumUsesClassTag, IsFixed);
  12648. if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
  12649. StdAlignValT = cast<EnumDecl>(New);
  12650. // If this is an undefined enum, warn.
  12651. if (TUK != TUK_Definition && !Invalid) {
  12652. TagDecl *Def;
  12653. if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
  12654. cast<EnumDecl>(New)->isFixed()) {
  12655. // C++0x: 7.2p2: opaque-enum-declaration.
  12656. // Conflicts are diagnosed above. Do nothing.
  12657. }
  12658. else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
  12659. Diag(Loc, diag::ext_forward_ref_enum_def)
  12660. << New;
  12661. Diag(Def->getLocation(), diag::note_previous_definition);
  12662. } else {
  12663. unsigned DiagID = diag::ext_forward_ref_enum;
  12664. if (getLangOpts().MSVCCompat)
  12665. DiagID = diag::ext_ms_forward_ref_enum;
  12666. else if (getLangOpts().CPlusPlus)
  12667. DiagID = diag::err_forward_ref_enum;
  12668. Diag(Loc, DiagID);
  12669. // If this is a forward-declared reference to an enumeration, make a
  12670. // note of it; we won't actually be introducing the declaration into
  12671. // the declaration context.
  12672. if (TUK == TUK_Reference)
  12673. IsForwardReference = true;
  12674. }
  12675. }
  12676. if (EnumUnderlying) {
  12677. EnumDecl *ED = cast<EnumDecl>(New);
  12678. if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
  12679. ED->setIntegerTypeSourceInfo(TI);
  12680. else
  12681. ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
  12682. ED->setPromotionType(ED->getIntegerType());
  12683. assert(ED->isComplete() && "enum with type should be complete");
  12684. }
  12685. } else {
  12686. // struct/union/class
  12687. // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
  12688. // struct X { int A; } D; D should chain to X.
  12689. if (getLangOpts().CPlusPlus) {
  12690. // FIXME: Look for a way to use RecordDecl for simple structs.
  12691. New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12692. cast_or_null<CXXRecordDecl>(PrevDecl));
  12693. if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
  12694. StdBadAlloc = cast<CXXRecordDecl>(New);
  12695. } else
  12696. New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
  12697. cast_or_null<RecordDecl>(PrevDecl));
  12698. }
  12699. // C++11 [dcl.type]p3:
  12700. // A type-specifier-seq shall not define a class or enumeration [...].
  12701. if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
  12702. TUK == TUK_Definition) {
  12703. Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
  12704. << Context.getTagDeclType(New);
  12705. Invalid = true;
  12706. }
  12707. if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
  12708. DC->getDeclKind() == Decl::Enum) {
  12709. Diag(New->getLocation(), diag::err_type_defined_in_enum)
  12710. << Context.getTagDeclType(New);
  12711. Invalid = true;
  12712. }
  12713. // Maybe add qualifier info.
  12714. if (SS.isNotEmpty()) {
  12715. if (SS.isSet()) {
  12716. // If this is either a declaration or a definition, check the
  12717. // nested-name-specifier against the current context.
  12718. if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
  12719. diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
  12720. isMemberSpecialization))
  12721. Invalid = true;
  12722. New->setQualifierInfo(SS.getWithLocInContext(Context));
  12723. if (TemplateParameterLists.size() > 0) {
  12724. New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
  12725. }
  12726. }
  12727. else
  12728. Invalid = true;
  12729. }
  12730. if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
  12731. // Add alignment attributes if necessary; these attributes are checked when
  12732. // the ASTContext lays out the structure.
  12733. //
  12734. // It is important for implementing the correct semantics that this
  12735. // happen here (in ActOnTag). The #pragma pack stack is
  12736. // maintained as a result of parser callbacks which can occur at
  12737. // many points during the parsing of a struct declaration (because
  12738. // the #pragma tokens are effectively skipped over during the
  12739. // parsing of the struct).
  12740. if (TUK == TUK_Definition) {
  12741. AddAlignmentAttributesForRecord(RD);
  12742. AddMsStructLayoutForRecord(RD);
  12743. }
  12744. }
  12745. if (ModulePrivateLoc.isValid()) {
  12746. if (isMemberSpecialization)
  12747. Diag(New->getLocation(), diag::err_module_private_specialization)
  12748. << 2
  12749. << FixItHint::CreateRemoval(ModulePrivateLoc);
  12750. // __module_private__ does not apply to local classes. However, we only
  12751. // diagnose this as an error when the declaration specifiers are
  12752. // freestanding. Here, we just ignore the __module_private__.
  12753. else if (!SearchDC->isFunctionOrMethod())
  12754. New->setModulePrivate();
  12755. }
  12756. // If this is a specialization of a member class (of a class template),
  12757. // check the specialization.
  12758. if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
  12759. Invalid = true;
  12760. // If we're declaring or defining a tag in function prototype scope in C,
  12761. // note that this type can only be used within the function and add it to
  12762. // the list of decls to inject into the function definition scope.
  12763. if ((Name || Kind == TTK_Enum) &&
  12764. getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
  12765. if (getLangOpts().CPlusPlus) {
  12766. // C++ [dcl.fct]p6:
  12767. // Types shall not be defined in return or parameter types.
  12768. if (TUK == TUK_Definition && !IsTypeSpecifier) {
  12769. Diag(Loc, diag::err_type_defined_in_param_type)
  12770. << Name;
  12771. Invalid = true;
  12772. }
  12773. } else if (!PrevDecl) {
  12774. Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
  12775. }
  12776. }
  12777. if (Invalid)
  12778. New->setInvalidDecl();
  12779. // Set the lexical context. If the tag has a C++ scope specifier, the
  12780. // lexical context will be different from the semantic context.
  12781. New->setLexicalDeclContext(CurContext);
  12782. // Mark this as a friend decl if applicable.
  12783. // In Microsoft mode, a friend declaration also acts as a forward
  12784. // declaration so we always pass true to setObjectOfFriendDecl to make
  12785. // the tag name visible.
  12786. if (TUK == TUK_Friend)
  12787. New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
  12788. // Set the access specifier.
  12789. if (!Invalid && SearchDC->isRecord())
  12790. SetMemberAccessSpecifier(New, PrevDecl, AS);
  12791. if (PrevDecl)
  12792. CheckRedeclarationModuleOwnership(New, PrevDecl);
  12793. if (TUK == TUK_Definition)
  12794. New->startDefinition();
  12795. if (Attr)
  12796. ProcessDeclAttributeList(S, New, Attr);
  12797. AddPragmaAttributes(S, New);
  12798. // If this has an identifier, add it to the scope stack.
  12799. if (TUK == TUK_Friend) {
  12800. // We might be replacing an existing declaration in the lookup tables;
  12801. // if so, borrow its access specifier.
  12802. if (PrevDecl)
  12803. New->setAccess(PrevDecl->getAccess());
  12804. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  12805. DC->makeDeclVisibleInContext(New);
  12806. if (Name) // can be null along some error paths
  12807. if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
  12808. PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
  12809. } else if (Name) {
  12810. S = getNonFieldDeclScope(S);
  12811. PushOnScopeChains(New, S, !IsForwardReference);
  12812. if (IsForwardReference)
  12813. SearchDC->makeDeclVisibleInContext(New);
  12814. } else {
  12815. CurContext->addDecl(New);
  12816. }
  12817. // If this is the C FILE type, notify the AST context.
  12818. if (IdentifierInfo *II = New->getIdentifier())
  12819. if (!New->isInvalidDecl() &&
  12820. New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
  12821. II->isStr("FILE"))
  12822. Context.setFILEDecl(New);
  12823. if (PrevDecl)
  12824. mergeDeclAttributes(New, PrevDecl);
  12825. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12826. // record.
  12827. AddPushedVisibilityAttribute(New);
  12828. if (isMemberSpecialization && !New->isInvalidDecl())
  12829. CompleteMemberSpecialization(New, Previous);
  12830. OwnedDecl = true;
  12831. // In C++, don't return an invalid declaration. We can't recover well from
  12832. // the cases where we make the type anonymous.
  12833. if (Invalid && getLangOpts().CPlusPlus) {
  12834. if (New->isBeingDefined())
  12835. if (auto RD = dyn_cast<RecordDecl>(New))
  12836. RD->completeDefinition();
  12837. return nullptr;
  12838. } else {
  12839. return New;
  12840. }
  12841. }
  12842. void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
  12843. AdjustDeclIfTemplate(TagD);
  12844. TagDecl *Tag = cast<TagDecl>(TagD);
  12845. // Enter the tag context.
  12846. PushDeclContext(S, Tag);
  12847. ActOnDocumentableDecl(TagD);
  12848. // If there's a #pragma GCC visibility in scope, set the visibility of this
  12849. // record.
  12850. AddPushedVisibilityAttribute(Tag);
  12851. }
  12852. bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
  12853. SkipBodyInfo &SkipBody) {
  12854. if (!hasStructuralCompatLayout(Prev, SkipBody.New))
  12855. return false;
  12856. // Make the previous decl visible.
  12857. makeMergedDefinitionVisible(SkipBody.Previous);
  12858. return true;
  12859. }
  12860. Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
  12861. assert(isa<ObjCContainerDecl>(IDecl) &&
  12862. "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
  12863. DeclContext *OCD = cast<DeclContext>(IDecl);
  12864. assert(getContainingDC(OCD) == CurContext &&
  12865. "The next DeclContext should be lexically contained in the current one.");
  12866. CurContext = OCD;
  12867. return IDecl;
  12868. }
  12869. void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
  12870. SourceLocation FinalLoc,
  12871. bool IsFinalSpelledSealed,
  12872. SourceLocation LBraceLoc) {
  12873. AdjustDeclIfTemplate(TagD);
  12874. CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
  12875. FieldCollector->StartClass();
  12876. if (!Record->getIdentifier())
  12877. return;
  12878. if (FinalLoc.isValid())
  12879. Record->addAttr(new (Context)
  12880. FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
  12881. // C++ [class]p2:
  12882. // [...] The class-name is also inserted into the scope of the
  12883. // class itself; this is known as the injected-class-name. For
  12884. // purposes of access checking, the injected-class-name is treated
  12885. // as if it were a public member name.
  12886. CXXRecordDecl *InjectedClassName
  12887. = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
  12888. Record->getLocStart(), Record->getLocation(),
  12889. Record->getIdentifier(),
  12890. /*PrevDecl=*/nullptr,
  12891. /*DelayTypeCreation=*/true);
  12892. Context.getTypeDeclType(InjectedClassName, Record);
  12893. InjectedClassName->setImplicit();
  12894. InjectedClassName->setAccess(AS_public);
  12895. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
  12896. InjectedClassName->setDescribedClassTemplate(Template);
  12897. PushOnScopeChains(InjectedClassName, S);
  12898. assert(InjectedClassName->isInjectedClassName() &&
  12899. "Broken injected-class-name");
  12900. }
  12901. void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
  12902. SourceRange BraceRange) {
  12903. AdjustDeclIfTemplate(TagD);
  12904. TagDecl *Tag = cast<TagDecl>(TagD);
  12905. Tag->setBraceRange(BraceRange);
  12906. // Make sure we "complete" the definition even it is invalid.
  12907. if (Tag->isBeingDefined()) {
  12908. assert(Tag->isInvalidDecl() && "We should already have completed it");
  12909. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12910. RD->completeDefinition();
  12911. }
  12912. if (isa<CXXRecordDecl>(Tag)) {
  12913. FieldCollector->FinishClass();
  12914. }
  12915. // Exit this scope of this tag's definition.
  12916. PopDeclContext();
  12917. if (getCurLexicalContext()->isObjCContainer() &&
  12918. Tag->getDeclContext()->isFileContext())
  12919. Tag->setTopLevelDeclInObjCContainer();
  12920. // Notify the consumer that we've defined a tag.
  12921. if (!Tag->isInvalidDecl())
  12922. Consumer.HandleTagDeclDefinition(Tag);
  12923. }
  12924. void Sema::ActOnObjCContainerFinishDefinition() {
  12925. // Exit this scope of this interface definition.
  12926. PopDeclContext();
  12927. }
  12928. void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
  12929. assert(DC == CurContext && "Mismatch of container contexts");
  12930. OriginalLexicalContext = DC;
  12931. ActOnObjCContainerFinishDefinition();
  12932. }
  12933. void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
  12934. ActOnObjCContainerStartDefinition(cast<Decl>(DC));
  12935. OriginalLexicalContext = nullptr;
  12936. }
  12937. void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
  12938. AdjustDeclIfTemplate(TagD);
  12939. TagDecl *Tag = cast<TagDecl>(TagD);
  12940. Tag->setInvalidDecl();
  12941. // Make sure we "complete" the definition even it is invalid.
  12942. if (Tag->isBeingDefined()) {
  12943. if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
  12944. RD->completeDefinition();
  12945. }
  12946. // We're undoing ActOnTagStartDefinition here, not
  12947. // ActOnStartCXXMemberDeclarations, so we don't have to mess with
  12948. // the FieldCollector.
  12949. PopDeclContext();
  12950. }
  12951. // Note that FieldName may be null for anonymous bitfields.
  12952. ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
  12953. IdentifierInfo *FieldName,
  12954. QualType FieldTy, bool IsMsStruct,
  12955. Expr *BitWidth, bool *ZeroWidth) {
  12956. // Default to true; that shouldn't confuse checks for emptiness
  12957. if (ZeroWidth)
  12958. *ZeroWidth = true;
  12959. // C99 6.7.2.1p4 - verify the field type.
  12960. // C++ 9.6p3: A bit-field shall have integral or enumeration type.
  12961. if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
  12962. // Handle incomplete types with specific error.
  12963. if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
  12964. return ExprError();
  12965. if (FieldName)
  12966. return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
  12967. << FieldName << FieldTy << BitWidth->getSourceRange();
  12968. return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
  12969. << FieldTy << BitWidth->getSourceRange();
  12970. } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
  12971. UPPC_BitFieldWidth))
  12972. return ExprError();
  12973. // If the bit-width is type- or value-dependent, don't try to check
  12974. // it now.
  12975. if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
  12976. return BitWidth;
  12977. llvm::APSInt Value;
  12978. ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
  12979. if (ICE.isInvalid())
  12980. return ICE;
  12981. BitWidth = ICE.get();
  12982. if (Value != 0 && ZeroWidth)
  12983. *ZeroWidth = false;
  12984. // Zero-width bitfield is ok for anonymous field.
  12985. if (Value == 0 && FieldName)
  12986. return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
  12987. if (Value.isSigned() && Value.isNegative()) {
  12988. if (FieldName)
  12989. return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
  12990. << FieldName << Value.toString(10);
  12991. return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
  12992. << Value.toString(10);
  12993. }
  12994. if (!FieldTy->isDependentType()) {
  12995. uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
  12996. uint64_t TypeWidth = Context.getIntWidth(FieldTy);
  12997. bool BitfieldIsOverwide = Value.ugt(TypeWidth);
  12998. // Over-wide bitfields are an error in C or when using the MSVC bitfield
  12999. // ABI.
  13000. bool CStdConstraintViolation =
  13001. BitfieldIsOverwide && !getLangOpts().CPlusPlus;
  13002. bool MSBitfieldViolation =
  13003. Value.ugt(TypeStorageSize) &&
  13004. (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
  13005. if (CStdConstraintViolation || MSBitfieldViolation) {
  13006. unsigned DiagWidth =
  13007. CStdConstraintViolation ? TypeWidth : TypeStorageSize;
  13008. if (FieldName)
  13009. return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
  13010. << FieldName << (unsigned)Value.getZExtValue()
  13011. << !CStdConstraintViolation << DiagWidth;
  13012. return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
  13013. << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
  13014. << DiagWidth;
  13015. }
  13016. // Warn on types where the user might conceivably expect to get all
  13017. // specified bits as value bits: that's all integral types other than
  13018. // 'bool'.
  13019. if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
  13020. if (FieldName)
  13021. Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
  13022. << FieldName << (unsigned)Value.getZExtValue()
  13023. << (unsigned)TypeWidth;
  13024. else
  13025. Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
  13026. << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
  13027. }
  13028. }
  13029. return BitWidth;
  13030. }
  13031. /// ActOnField - Each field of a C struct/union is passed into this in order
  13032. /// to create a FieldDecl object for it.
  13033. Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
  13034. Declarator &D, Expr *BitfieldWidth) {
  13035. FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
  13036. DeclStart, D, static_cast<Expr*>(BitfieldWidth),
  13037. /*InitStyle=*/ICIS_NoInit, AS_public);
  13038. return Res;
  13039. }
  13040. /// HandleField - Analyze a field of a C struct or a C++ data member.
  13041. ///
  13042. FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
  13043. SourceLocation DeclStart,
  13044. Declarator &D, Expr *BitWidth,
  13045. InClassInitStyle InitStyle,
  13046. AccessSpecifier AS) {
  13047. if (D.isDecompositionDeclarator()) {
  13048. const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
  13049. Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
  13050. << Decomp.getSourceRange();
  13051. return nullptr;
  13052. }
  13053. IdentifierInfo *II = D.getIdentifier();
  13054. SourceLocation Loc = DeclStart;
  13055. if (II) Loc = D.getIdentifierLoc();
  13056. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13057. QualType T = TInfo->getType();
  13058. if (getLangOpts().CPlusPlus) {
  13059. CheckExtraCXXDefaultArguments(D);
  13060. if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
  13061. UPPC_DataMemberType)) {
  13062. D.setInvalidType();
  13063. T = Context.IntTy;
  13064. TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  13065. }
  13066. }
  13067. // TR 18037 does not allow fields to be declared with address spaces.
  13068. if (T.getQualifiers().hasAddressSpace() ||
  13069. T->isDependentAddressSpaceType() ||
  13070. T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
  13071. Diag(Loc, diag::err_field_with_address_space);
  13072. D.setInvalidType();
  13073. }
  13074. // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
  13075. // used as structure or union field: image, sampler, event or block types.
  13076. if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
  13077. T->isSamplerT() || T->isBlockPointerType())) {
  13078. Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
  13079. D.setInvalidType();
  13080. }
  13081. DiagnoseFunctionSpecifiers(D.getDeclSpec());
  13082. if (D.getDeclSpec().isInlineSpecified())
  13083. Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
  13084. << getLangOpts().CPlusPlus17;
  13085. if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
  13086. Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
  13087. diag::err_invalid_thread)
  13088. << DeclSpec::getSpecifierName(TSCS);
  13089. // Check to see if this name was declared as a member previously
  13090. NamedDecl *PrevDecl = nullptr;
  13091. LookupResult Previous(*this, II, Loc, LookupMemberName,
  13092. ForVisibleRedeclaration);
  13093. LookupName(Previous, S);
  13094. switch (Previous.getResultKind()) {
  13095. case LookupResult::Found:
  13096. case LookupResult::FoundUnresolvedValue:
  13097. PrevDecl = Previous.getAsSingle<NamedDecl>();
  13098. break;
  13099. case LookupResult::FoundOverloaded:
  13100. PrevDecl = Previous.getRepresentativeDecl();
  13101. break;
  13102. case LookupResult::NotFound:
  13103. case LookupResult::NotFoundInCurrentInstantiation:
  13104. case LookupResult::Ambiguous:
  13105. break;
  13106. }
  13107. Previous.suppressDiagnostics();
  13108. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  13109. // Maybe we will complain about the shadowed template parameter.
  13110. DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
  13111. // Just pretend that we didn't see the previous declaration.
  13112. PrevDecl = nullptr;
  13113. }
  13114. if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
  13115. PrevDecl = nullptr;
  13116. bool Mutable
  13117. = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
  13118. SourceLocation TSSL = D.getLocStart();
  13119. FieldDecl *NewFD
  13120. = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
  13121. TSSL, AS, PrevDecl, &D);
  13122. if (NewFD->isInvalidDecl())
  13123. Record->setInvalidDecl();
  13124. if (D.getDeclSpec().isModulePrivateSpecified())
  13125. NewFD->setModulePrivate();
  13126. if (NewFD->isInvalidDecl() && PrevDecl) {
  13127. // Don't introduce NewFD into scope; there's already something
  13128. // with the same name in the same scope.
  13129. } else if (II) {
  13130. PushOnScopeChains(NewFD, S);
  13131. } else
  13132. Record->addDecl(NewFD);
  13133. return NewFD;
  13134. }
  13135. /// Build a new FieldDecl and check its well-formedness.
  13136. ///
  13137. /// This routine builds a new FieldDecl given the fields name, type,
  13138. /// record, etc. \p PrevDecl should refer to any previous declaration
  13139. /// with the same name and in the same scope as the field to be
  13140. /// created.
  13141. ///
  13142. /// \returns a new FieldDecl.
  13143. ///
  13144. /// \todo The Declarator argument is a hack. It will be removed once
  13145. FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
  13146. TypeSourceInfo *TInfo,
  13147. RecordDecl *Record, SourceLocation Loc,
  13148. bool Mutable, Expr *BitWidth,
  13149. InClassInitStyle InitStyle,
  13150. SourceLocation TSSL,
  13151. AccessSpecifier AS, NamedDecl *PrevDecl,
  13152. Declarator *D) {
  13153. IdentifierInfo *II = Name.getAsIdentifierInfo();
  13154. bool InvalidDecl = false;
  13155. if (D) InvalidDecl = D->isInvalidType();
  13156. // If we receive a broken type, recover by assuming 'int' and
  13157. // marking this declaration as invalid.
  13158. if (T.isNull()) {
  13159. InvalidDecl = true;
  13160. T = Context.IntTy;
  13161. }
  13162. QualType EltTy = Context.getBaseElementType(T);
  13163. if (!EltTy->isDependentType()) {
  13164. if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
  13165. // Fields of incomplete type force their record to be invalid.
  13166. Record->setInvalidDecl();
  13167. InvalidDecl = true;
  13168. } else {
  13169. NamedDecl *Def;
  13170. EltTy->isIncompleteType(&Def);
  13171. if (Def && Def->isInvalidDecl()) {
  13172. Record->setInvalidDecl();
  13173. InvalidDecl = true;
  13174. }
  13175. }
  13176. }
  13177. // OpenCL v1.2 s6.9.c: bitfields are not supported.
  13178. if (BitWidth && getLangOpts().OpenCL) {
  13179. Diag(Loc, diag::err_opencl_bitfields);
  13180. InvalidDecl = true;
  13181. }
  13182. // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
  13183. if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
  13184. T.hasQualifiers()) {
  13185. InvalidDecl = true;
  13186. Diag(Loc, diag::err_anon_bitfield_qualifiers);
  13187. }
  13188. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13189. // than a variably modified type.
  13190. if (!InvalidDecl && T->isVariablyModifiedType()) {
  13191. bool SizeIsNegative;
  13192. llvm::APSInt Oversized;
  13193. TypeSourceInfo *FixedTInfo =
  13194. TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
  13195. SizeIsNegative,
  13196. Oversized);
  13197. if (FixedTInfo) {
  13198. Diag(Loc, diag::warn_illegal_constant_array_size);
  13199. TInfo = FixedTInfo;
  13200. T = FixedTInfo->getType();
  13201. } else {
  13202. if (SizeIsNegative)
  13203. Diag(Loc, diag::err_typecheck_negative_array_size);
  13204. else if (Oversized.getBoolValue())
  13205. Diag(Loc, diag::err_array_too_large)
  13206. << Oversized.toString(10);
  13207. else
  13208. Diag(Loc, diag::err_typecheck_field_variable_size);
  13209. InvalidDecl = true;
  13210. }
  13211. }
  13212. // Fields can not have abstract class types
  13213. if (!InvalidDecl && RequireNonAbstractType(Loc, T,
  13214. diag::err_abstract_type_in_decl,
  13215. AbstractFieldType))
  13216. InvalidDecl = true;
  13217. bool ZeroWidth = false;
  13218. if (InvalidDecl)
  13219. BitWidth = nullptr;
  13220. // If this is declared as a bit-field, check the bit-field.
  13221. if (BitWidth) {
  13222. BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
  13223. &ZeroWidth).get();
  13224. if (!BitWidth) {
  13225. InvalidDecl = true;
  13226. BitWidth = nullptr;
  13227. ZeroWidth = false;
  13228. }
  13229. }
  13230. // Check that 'mutable' is consistent with the type of the declaration.
  13231. if (!InvalidDecl && Mutable) {
  13232. unsigned DiagID = 0;
  13233. if (T->isReferenceType())
  13234. DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
  13235. : diag::err_mutable_reference;
  13236. else if (T.isConstQualified())
  13237. DiagID = diag::err_mutable_const;
  13238. if (DiagID) {
  13239. SourceLocation ErrLoc = Loc;
  13240. if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
  13241. ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
  13242. Diag(ErrLoc, DiagID);
  13243. if (DiagID != diag::ext_mutable_reference) {
  13244. Mutable = false;
  13245. InvalidDecl = true;
  13246. }
  13247. }
  13248. }
  13249. // C++11 [class.union]p8 (DR1460):
  13250. // At most one variant member of a union may have a
  13251. // brace-or-equal-initializer.
  13252. if (InitStyle != ICIS_NoInit)
  13253. checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
  13254. FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
  13255. BitWidth, Mutable, InitStyle);
  13256. if (InvalidDecl)
  13257. NewFD->setInvalidDecl();
  13258. if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
  13259. Diag(Loc, diag::err_duplicate_member) << II;
  13260. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13261. NewFD->setInvalidDecl();
  13262. }
  13263. if (!InvalidDecl && getLangOpts().CPlusPlus) {
  13264. if (Record->isUnion()) {
  13265. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13266. CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13267. if (RDecl->getDefinition()) {
  13268. // C++ [class.union]p1: An object of a class with a non-trivial
  13269. // constructor, a non-trivial copy constructor, a non-trivial
  13270. // destructor, or a non-trivial copy assignment operator
  13271. // cannot be a member of a union, nor can an array of such
  13272. // objects.
  13273. if (CheckNontrivialField(NewFD))
  13274. NewFD->setInvalidDecl();
  13275. }
  13276. }
  13277. // C++ [class.union]p1: If a union contains a member of reference type,
  13278. // the program is ill-formed, except when compiling with MSVC extensions
  13279. // enabled.
  13280. if (EltTy->isReferenceType()) {
  13281. Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
  13282. diag::ext_union_member_of_reference_type :
  13283. diag::err_union_member_of_reference_type)
  13284. << NewFD->getDeclName() << EltTy;
  13285. if (!getLangOpts().MicrosoftExt)
  13286. NewFD->setInvalidDecl();
  13287. }
  13288. }
  13289. }
  13290. // FIXME: We need to pass in the attributes given an AST
  13291. // representation, not a parser representation.
  13292. if (D) {
  13293. // FIXME: The current scope is almost... but not entirely... correct here.
  13294. ProcessDeclAttributes(getCurScope(), NewFD, *D);
  13295. if (NewFD->hasAttrs())
  13296. CheckAlignasUnderalignment(NewFD);
  13297. }
  13298. // In auto-retain/release, infer strong retension for fields of
  13299. // retainable type.
  13300. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
  13301. NewFD->setInvalidDecl();
  13302. if (T.isObjCGCWeak())
  13303. Diag(Loc, diag::warn_attribute_weak_on_field);
  13304. NewFD->setAccess(AS);
  13305. return NewFD;
  13306. }
  13307. bool Sema::CheckNontrivialField(FieldDecl *FD) {
  13308. assert(FD);
  13309. assert(getLangOpts().CPlusPlus && "valid check only for C++");
  13310. if (FD->isInvalidDecl() || FD->getType()->isDependentType())
  13311. return false;
  13312. QualType EltTy = Context.getBaseElementType(FD->getType());
  13313. if (const RecordType *RT = EltTy->getAs<RecordType>()) {
  13314. CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
  13315. if (RDecl->getDefinition()) {
  13316. // We check for copy constructors before constructors
  13317. // because otherwise we'll never get complaints about
  13318. // copy constructors.
  13319. CXXSpecialMember member = CXXInvalid;
  13320. // We're required to check for any non-trivial constructors. Since the
  13321. // implicit default constructor is suppressed if there are any
  13322. // user-declared constructors, we just need to check that there is a
  13323. // trivial default constructor and a trivial copy constructor. (We don't
  13324. // worry about move constructors here, since this is a C++98 check.)
  13325. if (RDecl->hasNonTrivialCopyConstructor())
  13326. member = CXXCopyConstructor;
  13327. else if (!RDecl->hasTrivialDefaultConstructor())
  13328. member = CXXDefaultConstructor;
  13329. else if (RDecl->hasNonTrivialCopyAssignment())
  13330. member = CXXCopyAssignment;
  13331. else if (RDecl->hasNonTrivialDestructor())
  13332. member = CXXDestructor;
  13333. if (member != CXXInvalid) {
  13334. if (!getLangOpts().CPlusPlus11 &&
  13335. getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
  13336. // Objective-C++ ARC: it is an error to have a non-trivial field of
  13337. // a union. However, system headers in Objective-C programs
  13338. // occasionally have Objective-C lifetime objects within unions,
  13339. // and rather than cause the program to fail, we make those
  13340. // members unavailable.
  13341. SourceLocation Loc = FD->getLocation();
  13342. if (getSourceManager().isInSystemHeader(Loc)) {
  13343. if (!FD->hasAttr<UnavailableAttr>())
  13344. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13345. UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
  13346. return false;
  13347. }
  13348. }
  13349. Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
  13350. diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
  13351. diag::err_illegal_union_or_anon_struct_member)
  13352. << FD->getParent()->isUnion() << FD->getDeclName() << member;
  13353. DiagnoseNontrivial(RDecl, member);
  13354. return !getLangOpts().CPlusPlus11;
  13355. }
  13356. }
  13357. }
  13358. return false;
  13359. }
  13360. /// TranslateIvarVisibility - Translate visibility from a token ID to an
  13361. /// AST enum value.
  13362. static ObjCIvarDecl::AccessControl
  13363. TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
  13364. switch (ivarVisibility) {
  13365. default: llvm_unreachable("Unknown visitibility kind");
  13366. case tok::objc_private: return ObjCIvarDecl::Private;
  13367. case tok::objc_public: return ObjCIvarDecl::Public;
  13368. case tok::objc_protected: return ObjCIvarDecl::Protected;
  13369. case tok::objc_package: return ObjCIvarDecl::Package;
  13370. }
  13371. }
  13372. /// ActOnIvar - Each ivar field of an objective-c class is passed into this
  13373. /// in order to create an IvarDecl object for it.
  13374. Decl *Sema::ActOnIvar(Scope *S,
  13375. SourceLocation DeclStart,
  13376. Declarator &D, Expr *BitfieldWidth,
  13377. tok::ObjCKeywordKind Visibility) {
  13378. IdentifierInfo *II = D.getIdentifier();
  13379. Expr *BitWidth = (Expr*)BitfieldWidth;
  13380. SourceLocation Loc = DeclStart;
  13381. if (II) Loc = D.getIdentifierLoc();
  13382. // FIXME: Unnamed fields can be handled in various different ways, for
  13383. // example, unnamed unions inject all members into the struct namespace!
  13384. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  13385. QualType T = TInfo->getType();
  13386. if (BitWidth) {
  13387. // 6.7.2.1p3, 6.7.2.1p4
  13388. BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
  13389. if (!BitWidth)
  13390. D.setInvalidType();
  13391. } else {
  13392. // Not a bitfield.
  13393. // validate II.
  13394. }
  13395. if (T->isReferenceType()) {
  13396. Diag(Loc, diag::err_ivar_reference_type);
  13397. D.setInvalidType();
  13398. }
  13399. // C99 6.7.2.1p8: A member of a structure or union may have any type other
  13400. // than a variably modified type.
  13401. else if (T->isVariablyModifiedType()) {
  13402. Diag(Loc, diag::err_typecheck_ivar_variable_size);
  13403. D.setInvalidType();
  13404. }
  13405. // Get the visibility (access control) for this ivar.
  13406. ObjCIvarDecl::AccessControl ac =
  13407. Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
  13408. : ObjCIvarDecl::None;
  13409. // Must set ivar's DeclContext to its enclosing interface.
  13410. ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
  13411. if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
  13412. return nullptr;
  13413. ObjCContainerDecl *EnclosingContext;
  13414. if (ObjCImplementationDecl *IMPDecl =
  13415. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13416. if (LangOpts.ObjCRuntime.isFragile()) {
  13417. // Case of ivar declared in an implementation. Context is that of its class.
  13418. EnclosingContext = IMPDecl->getClassInterface();
  13419. assert(EnclosingContext && "Implementation has no class interface!");
  13420. }
  13421. else
  13422. EnclosingContext = EnclosingDecl;
  13423. } else {
  13424. if (ObjCCategoryDecl *CDecl =
  13425. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13426. if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
  13427. Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
  13428. return nullptr;
  13429. }
  13430. }
  13431. EnclosingContext = EnclosingDecl;
  13432. }
  13433. // Construct the decl.
  13434. ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
  13435. DeclStart, Loc, II, T,
  13436. TInfo, ac, (Expr *)BitfieldWidth);
  13437. if (II) {
  13438. NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
  13439. ForVisibleRedeclaration);
  13440. if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
  13441. && !isa<TagDecl>(PrevDecl)) {
  13442. Diag(Loc, diag::err_duplicate_member) << II;
  13443. Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
  13444. NewID->setInvalidDecl();
  13445. }
  13446. }
  13447. // Process attributes attached to the ivar.
  13448. ProcessDeclAttributes(S, NewID, D);
  13449. if (D.isInvalidType())
  13450. NewID->setInvalidDecl();
  13451. // In ARC, infer 'retaining' for ivars of retainable type.
  13452. if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
  13453. NewID->setInvalidDecl();
  13454. if (D.getDeclSpec().isModulePrivateSpecified())
  13455. NewID->setModulePrivate();
  13456. if (II) {
  13457. // FIXME: When interfaces are DeclContexts, we'll need to add
  13458. // these to the interface.
  13459. S->AddDecl(NewID);
  13460. IdResolver.AddDecl(NewID);
  13461. }
  13462. if (LangOpts.ObjCRuntime.isNonFragile() &&
  13463. !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
  13464. Diag(Loc, diag::warn_ivars_in_interface);
  13465. return NewID;
  13466. }
  13467. /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
  13468. /// class and class extensions. For every class \@interface and class
  13469. /// extension \@interface, if the last ivar is a bitfield of any type,
  13470. /// then add an implicit `char :0` ivar to the end of that interface.
  13471. void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
  13472. SmallVectorImpl<Decl *> &AllIvarDecls) {
  13473. if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
  13474. return;
  13475. Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
  13476. ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
  13477. if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
  13478. return;
  13479. ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
  13480. if (!ID) {
  13481. if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
  13482. if (!CD->IsClassExtension())
  13483. return;
  13484. }
  13485. // No need to add this to end of @implementation.
  13486. else
  13487. return;
  13488. }
  13489. // All conditions are met. Add a new bitfield to the tail end of ivars.
  13490. llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
  13491. Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
  13492. Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
  13493. DeclLoc, DeclLoc, nullptr,
  13494. Context.CharTy,
  13495. Context.getTrivialTypeSourceInfo(Context.CharTy,
  13496. DeclLoc),
  13497. ObjCIvarDecl::Private, BW,
  13498. true);
  13499. AllIvarDecls.push_back(Ivar);
  13500. }
  13501. void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
  13502. ArrayRef<Decl *> Fields, SourceLocation LBrac,
  13503. SourceLocation RBrac, AttributeList *Attr) {
  13504. assert(EnclosingDecl && "missing record or interface decl");
  13505. // If this is an Objective-C @implementation or category and we have
  13506. // new fields here we should reset the layout of the interface since
  13507. // it will now change.
  13508. if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
  13509. ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
  13510. switch (DC->getKind()) {
  13511. default: break;
  13512. case Decl::ObjCCategory:
  13513. Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
  13514. break;
  13515. case Decl::ObjCImplementation:
  13516. Context.
  13517. ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
  13518. break;
  13519. }
  13520. }
  13521. RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
  13522. // Start counting up the number of named members; make sure to include
  13523. // members of anonymous structs and unions in the total.
  13524. unsigned NumNamedMembers = 0;
  13525. if (Record) {
  13526. for (const auto *I : Record->decls()) {
  13527. if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
  13528. if (IFD->getDeclName())
  13529. ++NumNamedMembers;
  13530. }
  13531. }
  13532. // Verify that all the fields are okay.
  13533. SmallVector<FieldDecl*, 32> RecFields;
  13534. bool ObjCFieldLifetimeErrReported = false;
  13535. for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
  13536. i != end; ++i) {
  13537. FieldDecl *FD = cast<FieldDecl>(*i);
  13538. // Get the type for the field.
  13539. const Type *FDTy = FD->getType().getTypePtr();
  13540. if (!FD->isAnonymousStructOrUnion()) {
  13541. // Remember all fields written by the user.
  13542. RecFields.push_back(FD);
  13543. }
  13544. // If the field is already invalid for some reason, don't emit more
  13545. // diagnostics about it.
  13546. if (FD->isInvalidDecl()) {
  13547. EnclosingDecl->setInvalidDecl();
  13548. continue;
  13549. }
  13550. // C99 6.7.2.1p2:
  13551. // A structure or union shall not contain a member with
  13552. // incomplete or function type (hence, a structure shall not
  13553. // contain an instance of itself, but may contain a pointer to
  13554. // an instance of itself), except that the last member of a
  13555. // structure with more than one named member may have incomplete
  13556. // array type; such a structure (and any union containing,
  13557. // possibly recursively, a member that is such a structure)
  13558. // shall not be a member of a structure or an element of an
  13559. // array.
  13560. bool IsLastField = (i + 1 == Fields.end());
  13561. if (FDTy->isFunctionType()) {
  13562. // Field declared as a function.
  13563. Diag(FD->getLocation(), diag::err_field_declared_as_function)
  13564. << FD->getDeclName();
  13565. FD->setInvalidDecl();
  13566. EnclosingDecl->setInvalidDecl();
  13567. continue;
  13568. } else if (FDTy->isIncompleteArrayType() &&
  13569. (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
  13570. if (Record) {
  13571. // Flexible array member.
  13572. // Microsoft and g++ is more permissive regarding flexible array.
  13573. // It will accept flexible array in union and also
  13574. // as the sole element of a struct/class.
  13575. unsigned DiagID = 0;
  13576. if (!Record->isUnion() && !IsLastField) {
  13577. Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
  13578. << FD->getDeclName() << FD->getType() << Record->getTagKind();
  13579. Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
  13580. FD->setInvalidDecl();
  13581. EnclosingDecl->setInvalidDecl();
  13582. continue;
  13583. } else if (Record->isUnion())
  13584. DiagID = getLangOpts().MicrosoftExt
  13585. ? diag::ext_flexible_array_union_ms
  13586. : getLangOpts().CPlusPlus
  13587. ? diag::ext_flexible_array_union_gnu
  13588. : diag::err_flexible_array_union;
  13589. else if (NumNamedMembers < 1)
  13590. DiagID = getLangOpts().MicrosoftExt
  13591. ? diag::ext_flexible_array_empty_aggregate_ms
  13592. : getLangOpts().CPlusPlus
  13593. ? diag::ext_flexible_array_empty_aggregate_gnu
  13594. : diag::err_flexible_array_empty_aggregate;
  13595. if (DiagID)
  13596. Diag(FD->getLocation(), DiagID) << FD->getDeclName()
  13597. << Record->getTagKind();
  13598. // While the layout of types that contain virtual bases is not specified
  13599. // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
  13600. // virtual bases after the derived members. This would make a flexible
  13601. // array member declared at the end of an object not adjacent to the end
  13602. // of the type.
  13603. if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
  13604. if (RD->getNumVBases() != 0)
  13605. Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
  13606. << FD->getDeclName() << Record->getTagKind();
  13607. if (!getLangOpts().C99)
  13608. Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
  13609. << FD->getDeclName() << Record->getTagKind();
  13610. // If the element type has a non-trivial destructor, we would not
  13611. // implicitly destroy the elements, so disallow it for now.
  13612. //
  13613. // FIXME: GCC allows this. We should probably either implicitly delete
  13614. // the destructor of the containing class, or just allow this.
  13615. QualType BaseElem = Context.getBaseElementType(FD->getType());
  13616. if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
  13617. Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
  13618. << FD->getDeclName() << FD->getType();
  13619. FD->setInvalidDecl();
  13620. EnclosingDecl->setInvalidDecl();
  13621. continue;
  13622. }
  13623. // Okay, we have a legal flexible array member at the end of the struct.
  13624. Record->setHasFlexibleArrayMember(true);
  13625. } else {
  13626. // In ObjCContainerDecl ivars with incomplete array type are accepted,
  13627. // unless they are followed by another ivar. That check is done
  13628. // elsewhere, after synthesized ivars are known.
  13629. }
  13630. } else if (!FDTy->isDependentType() &&
  13631. RequireCompleteType(FD->getLocation(), FD->getType(),
  13632. diag::err_field_incomplete)) {
  13633. // Incomplete type
  13634. FD->setInvalidDecl();
  13635. EnclosingDecl->setInvalidDecl();
  13636. continue;
  13637. } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
  13638. if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
  13639. // A type which contains a flexible array member is considered to be a
  13640. // flexible array member.
  13641. Record->setHasFlexibleArrayMember(true);
  13642. if (!Record->isUnion()) {
  13643. // If this is a struct/class and this is not the last element, reject
  13644. // it. Note that GCC supports variable sized arrays in the middle of
  13645. // structures.
  13646. if (!IsLastField)
  13647. Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
  13648. << FD->getDeclName() << FD->getType();
  13649. else {
  13650. // We support flexible arrays at the end of structs in
  13651. // other structs as an extension.
  13652. Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
  13653. << FD->getDeclName();
  13654. }
  13655. }
  13656. }
  13657. if (isa<ObjCContainerDecl>(EnclosingDecl) &&
  13658. RequireNonAbstractType(FD->getLocation(), FD->getType(),
  13659. diag::err_abstract_type_in_decl,
  13660. AbstractIvarType)) {
  13661. // Ivars can not have abstract class types
  13662. FD->setInvalidDecl();
  13663. }
  13664. if (Record && FDTTy->getDecl()->hasObjectMember())
  13665. Record->setHasObjectMember(true);
  13666. if (Record && FDTTy->getDecl()->hasVolatileMember())
  13667. Record->setHasVolatileMember(true);
  13668. } else if (FDTy->isObjCObjectType()) {
  13669. /// A field cannot be an Objective-c object
  13670. Diag(FD->getLocation(), diag::err_statically_allocated_object)
  13671. << FixItHint::CreateInsertion(FD->getLocation(), "*");
  13672. QualType T = Context.getObjCObjectPointerType(FD->getType());
  13673. FD->setType(T);
  13674. } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
  13675. Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
  13676. // It's an error in ARC or Weak if a field has lifetime.
  13677. // We don't want to report this in a system header, though,
  13678. // so we just make the field unavailable.
  13679. // FIXME: that's really not sufficient; we need to make the type
  13680. // itself invalid to, say, initialize or copy.
  13681. QualType T = FD->getType();
  13682. if (T.hasNonTrivialObjCLifetime()) {
  13683. SourceLocation loc = FD->getLocation();
  13684. if (getSourceManager().isInSystemHeader(loc)) {
  13685. if (!FD->hasAttr<UnavailableAttr>()) {
  13686. FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
  13687. UnavailableAttr::IR_ARCFieldWithOwnership, loc));
  13688. }
  13689. } else {
  13690. Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
  13691. << T->isBlockPointerType() << Record->getTagKind();
  13692. }
  13693. ObjCFieldLifetimeErrReported = true;
  13694. }
  13695. } else if (getLangOpts().ObjC1 &&
  13696. getLangOpts().getGC() != LangOptions::NonGC &&
  13697. Record && !Record->hasObjectMember()) {
  13698. if (FD->getType()->isObjCObjectPointerType() ||
  13699. FD->getType().isObjCGCStrong())
  13700. Record->setHasObjectMember(true);
  13701. else if (Context.getAsArrayType(FD->getType())) {
  13702. QualType BaseType = Context.getBaseElementType(FD->getType());
  13703. if (BaseType->isRecordType() &&
  13704. BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
  13705. Record->setHasObjectMember(true);
  13706. else if (BaseType->isObjCObjectPointerType() ||
  13707. BaseType.isObjCGCStrong())
  13708. Record->setHasObjectMember(true);
  13709. }
  13710. }
  13711. if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
  13712. QualType FT = FD->getType();
  13713. if (FT.isNonTrivialToPrimitiveDefaultInitialize())
  13714. Record->setNonTrivialToPrimitiveDefaultInitialize(true);
  13715. QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
  13716. if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
  13717. Record->setNonTrivialToPrimitiveCopy(true);
  13718. if (FT.isDestructedType()) {
  13719. Record->setNonTrivialToPrimitiveDestroy(true);
  13720. Record->setParamDestroyedInCallee(true);
  13721. }
  13722. if (const auto *RT = FT->getAs<RecordType>()) {
  13723. if (RT->getDecl()->getArgPassingRestrictions() ==
  13724. RecordDecl::APK_CanNeverPassInRegs)
  13725. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  13726. } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
  13727. Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
  13728. }
  13729. if (Record && FD->getType().isVolatileQualified())
  13730. Record->setHasVolatileMember(true);
  13731. // Keep track of the number of named members.
  13732. if (FD->getIdentifier())
  13733. ++NumNamedMembers;
  13734. }
  13735. // Okay, we successfully defined 'Record'.
  13736. if (Record) {
  13737. bool Completed = false;
  13738. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13739. if (!CXXRecord->isInvalidDecl()) {
  13740. // Set access bits correctly on the directly-declared conversions.
  13741. for (CXXRecordDecl::conversion_iterator
  13742. I = CXXRecord->conversion_begin(),
  13743. E = CXXRecord->conversion_end(); I != E; ++I)
  13744. I.setAccess((*I)->getAccess());
  13745. }
  13746. if (!CXXRecord->isDependentType()) {
  13747. if (CXXRecord->hasUserDeclaredDestructor()) {
  13748. // Adjust user-defined destructor exception spec.
  13749. if (getLangOpts().CPlusPlus11)
  13750. AdjustDestructorExceptionSpec(CXXRecord,
  13751. CXXRecord->getDestructor());
  13752. }
  13753. // Add any implicitly-declared members to this class.
  13754. AddImplicitlyDeclaredMembersToClass(CXXRecord);
  13755. if (!CXXRecord->isInvalidDecl()) {
  13756. // If we have virtual base classes, we may end up finding multiple
  13757. // final overriders for a given virtual function. Check for this
  13758. // problem now.
  13759. if (CXXRecord->getNumVBases()) {
  13760. CXXFinalOverriderMap FinalOverriders;
  13761. CXXRecord->getFinalOverriders(FinalOverriders);
  13762. for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
  13763. MEnd = FinalOverriders.end();
  13764. M != MEnd; ++M) {
  13765. for (OverridingMethods::iterator SO = M->second.begin(),
  13766. SOEnd = M->second.end();
  13767. SO != SOEnd; ++SO) {
  13768. assert(SO->second.size() > 0 &&
  13769. "Virtual function without overriding functions?");
  13770. if (SO->second.size() == 1)
  13771. continue;
  13772. // C++ [class.virtual]p2:
  13773. // In a derived class, if a virtual member function of a base
  13774. // class subobject has more than one final overrider the
  13775. // program is ill-formed.
  13776. Diag(Record->getLocation(), diag::err_multiple_final_overriders)
  13777. << (const NamedDecl *)M->first << Record;
  13778. Diag(M->first->getLocation(),
  13779. diag::note_overridden_virtual_function);
  13780. for (OverridingMethods::overriding_iterator
  13781. OM = SO->second.begin(),
  13782. OMEnd = SO->second.end();
  13783. OM != OMEnd; ++OM)
  13784. Diag(OM->Method->getLocation(), diag::note_final_overrider)
  13785. << (const NamedDecl *)M->first << OM->Method->getParent();
  13786. Record->setInvalidDecl();
  13787. }
  13788. }
  13789. CXXRecord->completeDefinition(&FinalOverriders);
  13790. Completed = true;
  13791. }
  13792. }
  13793. }
  13794. }
  13795. if (!Completed)
  13796. Record->completeDefinition();
  13797. // We may have deferred checking for a deleted destructor. Check now.
  13798. if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  13799. auto *Dtor = CXXRecord->getDestructor();
  13800. if (Dtor && Dtor->isImplicit() &&
  13801. ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
  13802. CXXRecord->setImplicitDestructorIsDeleted();
  13803. SetDeclDeleted(Dtor, CXXRecord->getLocation());
  13804. }
  13805. }
  13806. if (Record->hasAttrs()) {
  13807. CheckAlignasUnderalignment(Record);
  13808. if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
  13809. checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
  13810. IA->getRange(), IA->getBestCase(),
  13811. IA->getSemanticSpelling());
  13812. }
  13813. // Check if the structure/union declaration is a type that can have zero
  13814. // size in C. For C this is a language extension, for C++ it may cause
  13815. // compatibility problems.
  13816. bool CheckForZeroSize;
  13817. if (!getLangOpts().CPlusPlus) {
  13818. CheckForZeroSize = true;
  13819. } else {
  13820. // For C++ filter out types that cannot be referenced in C code.
  13821. CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
  13822. CheckForZeroSize =
  13823. CXXRecord->getLexicalDeclContext()->isExternCContext() &&
  13824. !CXXRecord->isDependentType() &&
  13825. CXXRecord->isCLike();
  13826. }
  13827. if (CheckForZeroSize) {
  13828. bool ZeroSize = true;
  13829. bool IsEmpty = true;
  13830. unsigned NonBitFields = 0;
  13831. for (RecordDecl::field_iterator I = Record->field_begin(),
  13832. E = Record->field_end();
  13833. (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
  13834. IsEmpty = false;
  13835. if (I->isUnnamedBitfield()) {
  13836. if (!I->isZeroLengthBitField(Context))
  13837. ZeroSize = false;
  13838. } else {
  13839. ++NonBitFields;
  13840. QualType FieldType = I->getType();
  13841. if (FieldType->isIncompleteType() ||
  13842. !Context.getTypeSizeInChars(FieldType).isZero())
  13843. ZeroSize = false;
  13844. }
  13845. }
  13846. // Empty structs are an extension in C (C99 6.7.2.1p7). They are
  13847. // allowed in C++, but warn if its declaration is inside
  13848. // extern "C" block.
  13849. if (ZeroSize) {
  13850. Diag(RecLoc, getLangOpts().CPlusPlus ?
  13851. diag::warn_zero_size_struct_union_in_extern_c :
  13852. diag::warn_zero_size_struct_union_compat)
  13853. << IsEmpty << Record->isUnion() << (NonBitFields > 1);
  13854. }
  13855. // Structs without named members are extension in C (C99 6.7.2.1p7),
  13856. // but are accepted by GCC.
  13857. if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
  13858. Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
  13859. diag::ext_no_named_members_in_struct_union)
  13860. << Record->isUnion();
  13861. }
  13862. }
  13863. } else {
  13864. ObjCIvarDecl **ClsFields =
  13865. reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
  13866. if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
  13867. ID->setEndOfDefinitionLoc(RBrac);
  13868. // Add ivar's to class's DeclContext.
  13869. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13870. ClsFields[i]->setLexicalDeclContext(ID);
  13871. ID->addDecl(ClsFields[i]);
  13872. }
  13873. // Must enforce the rule that ivars in the base classes may not be
  13874. // duplicates.
  13875. if (ID->getSuperClass())
  13876. DiagnoseDuplicateIvars(ID, ID->getSuperClass());
  13877. } else if (ObjCImplementationDecl *IMPDecl =
  13878. dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
  13879. assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
  13880. for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
  13881. // Ivar declared in @implementation never belongs to the implementation.
  13882. // Only it is in implementation's lexical context.
  13883. ClsFields[I]->setLexicalDeclContext(IMPDecl);
  13884. CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
  13885. IMPDecl->setIvarLBraceLoc(LBrac);
  13886. IMPDecl->setIvarRBraceLoc(RBrac);
  13887. } else if (ObjCCategoryDecl *CDecl =
  13888. dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
  13889. // case of ivars in class extension; all other cases have been
  13890. // reported as errors elsewhere.
  13891. // FIXME. Class extension does not have a LocEnd field.
  13892. // CDecl->setLocEnd(RBrac);
  13893. // Add ivar's to class extension's DeclContext.
  13894. // Diagnose redeclaration of private ivars.
  13895. ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
  13896. for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
  13897. if (IDecl) {
  13898. if (const ObjCIvarDecl *ClsIvar =
  13899. IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13900. Diag(ClsFields[i]->getLocation(),
  13901. diag::err_duplicate_ivar_declaration);
  13902. Diag(ClsIvar->getLocation(), diag::note_previous_definition);
  13903. continue;
  13904. }
  13905. for (const auto *Ext : IDecl->known_extensions()) {
  13906. if (const ObjCIvarDecl *ClsExtIvar
  13907. = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
  13908. Diag(ClsFields[i]->getLocation(),
  13909. diag::err_duplicate_ivar_declaration);
  13910. Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
  13911. continue;
  13912. }
  13913. }
  13914. }
  13915. ClsFields[i]->setLexicalDeclContext(CDecl);
  13916. CDecl->addDecl(ClsFields[i]);
  13917. }
  13918. CDecl->setIvarLBraceLoc(LBrac);
  13919. CDecl->setIvarRBraceLoc(RBrac);
  13920. }
  13921. }
  13922. if (Attr)
  13923. ProcessDeclAttributeList(S, Record, Attr);
  13924. }
  13925. /// Determine whether the given integral value is representable within
  13926. /// the given type T.
  13927. static bool isRepresentableIntegerValue(ASTContext &Context,
  13928. llvm::APSInt &Value,
  13929. QualType T) {
  13930. assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
  13931. "Integral type required!");
  13932. unsigned BitWidth = Context.getIntWidth(T);
  13933. if (Value.isUnsigned() || Value.isNonNegative()) {
  13934. if (T->isSignedIntegerOrEnumerationType())
  13935. --BitWidth;
  13936. return Value.getActiveBits() <= BitWidth;
  13937. }
  13938. return Value.getMinSignedBits() <= BitWidth;
  13939. }
  13940. // Given an integral type, return the next larger integral type
  13941. // (or a NULL type of no such type exists).
  13942. static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
  13943. // FIXME: Int128/UInt128 support, which also needs to be introduced into
  13944. // enum checking below.
  13945. assert((T->isIntegralType(Context) ||
  13946. T->isEnumeralType()) && "Integral type required!");
  13947. const unsigned NumTypes = 4;
  13948. QualType SignedIntegralTypes[NumTypes] = {
  13949. Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
  13950. };
  13951. QualType UnsignedIntegralTypes[NumTypes] = {
  13952. Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
  13953. Context.UnsignedLongLongTy
  13954. };
  13955. unsigned BitWidth = Context.getTypeSize(T);
  13956. QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
  13957. : UnsignedIntegralTypes;
  13958. for (unsigned I = 0; I != NumTypes; ++I)
  13959. if (Context.getTypeSize(Types[I]) > BitWidth)
  13960. return Types[I];
  13961. return QualType();
  13962. }
  13963. EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
  13964. EnumConstantDecl *LastEnumConst,
  13965. SourceLocation IdLoc,
  13966. IdentifierInfo *Id,
  13967. Expr *Val) {
  13968. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  13969. llvm::APSInt EnumVal(IntWidth);
  13970. QualType EltTy;
  13971. if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
  13972. Val = nullptr;
  13973. if (Val)
  13974. Val = DefaultLvalueConversion(Val).get();
  13975. if (Val) {
  13976. if (Enum->isDependentType() || Val->isTypeDependent())
  13977. EltTy = Context.DependentTy;
  13978. else {
  13979. if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
  13980. !getLangOpts().MSVCCompat) {
  13981. // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
  13982. // constant-expression in the enumerator-definition shall be a converted
  13983. // constant expression of the underlying type.
  13984. EltTy = Enum->getIntegerType();
  13985. ExprResult Converted =
  13986. CheckConvertedConstantExpression(Val, EltTy, EnumVal,
  13987. CCEK_Enumerator);
  13988. if (Converted.isInvalid())
  13989. Val = nullptr;
  13990. else
  13991. Val = Converted.get();
  13992. } else if (!Val->isValueDependent() &&
  13993. !(Val = VerifyIntegerConstantExpression(Val,
  13994. &EnumVal).get())) {
  13995. // C99 6.7.2.2p2: Make sure we have an integer constant expression.
  13996. } else {
  13997. if (Enum->isComplete()) {
  13998. EltTy = Enum->getIntegerType();
  13999. // In Obj-C and Microsoft mode, require the enumeration value to be
  14000. // representable in the underlying type of the enumeration. In C++11,
  14001. // we perform a non-narrowing conversion as part of converted constant
  14002. // expression checking.
  14003. if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14004. if (getLangOpts().MSVCCompat) {
  14005. Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
  14006. Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
  14007. } else
  14008. Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
  14009. } else
  14010. Val = ImpCastExprToType(Val, EltTy,
  14011. EltTy->isBooleanType() ?
  14012. CK_IntegralToBoolean : CK_IntegralCast)
  14013. .get();
  14014. } else if (getLangOpts().CPlusPlus) {
  14015. // C++11 [dcl.enum]p5:
  14016. // If the underlying type is not fixed, the type of each enumerator
  14017. // is the type of its initializing value:
  14018. // - If an initializer is specified for an enumerator, the
  14019. // initializing value has the same type as the expression.
  14020. EltTy = Val->getType();
  14021. } else {
  14022. // C99 6.7.2.2p2:
  14023. // The expression that defines the value of an enumeration constant
  14024. // shall be an integer constant expression that has a value
  14025. // representable as an int.
  14026. // Complain if the value is not representable in an int.
  14027. if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
  14028. Diag(IdLoc, diag::ext_enum_value_not_int)
  14029. << EnumVal.toString(10) << Val->getSourceRange()
  14030. << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
  14031. else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
  14032. // Force the type of the expression to 'int'.
  14033. Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
  14034. }
  14035. EltTy = Val->getType();
  14036. }
  14037. }
  14038. }
  14039. }
  14040. if (!Val) {
  14041. if (Enum->isDependentType())
  14042. EltTy = Context.DependentTy;
  14043. else if (!LastEnumConst) {
  14044. // C++0x [dcl.enum]p5:
  14045. // If the underlying type is not fixed, the type of each enumerator
  14046. // is the type of its initializing value:
  14047. // - If no initializer is specified for the first enumerator, the
  14048. // initializing value has an unspecified integral type.
  14049. //
  14050. // GCC uses 'int' for its unspecified integral type, as does
  14051. // C99 6.7.2.2p3.
  14052. if (Enum->isFixed()) {
  14053. EltTy = Enum->getIntegerType();
  14054. }
  14055. else {
  14056. EltTy = Context.IntTy;
  14057. }
  14058. } else {
  14059. // Assign the last value + 1.
  14060. EnumVal = LastEnumConst->getInitVal();
  14061. ++EnumVal;
  14062. EltTy = LastEnumConst->getType();
  14063. // Check for overflow on increment.
  14064. if (EnumVal < LastEnumConst->getInitVal()) {
  14065. // C++0x [dcl.enum]p5:
  14066. // If the underlying type is not fixed, the type of each enumerator
  14067. // is the type of its initializing value:
  14068. //
  14069. // - Otherwise the type of the initializing value is the same as
  14070. // the type of the initializing value of the preceding enumerator
  14071. // unless the incremented value is not representable in that type,
  14072. // in which case the type is an unspecified integral type
  14073. // sufficient to contain the incremented value. If no such type
  14074. // exists, the program is ill-formed.
  14075. QualType T = getNextLargerIntegralType(Context, EltTy);
  14076. if (T.isNull() || Enum->isFixed()) {
  14077. // There is no integral type larger enough to represent this
  14078. // value. Complain, then allow the value to wrap around.
  14079. EnumVal = LastEnumConst->getInitVal();
  14080. EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
  14081. ++EnumVal;
  14082. if (Enum->isFixed())
  14083. // When the underlying type is fixed, this is ill-formed.
  14084. Diag(IdLoc, diag::err_enumerator_wrapped)
  14085. << EnumVal.toString(10)
  14086. << EltTy;
  14087. else
  14088. Diag(IdLoc, diag::ext_enumerator_increment_too_large)
  14089. << EnumVal.toString(10);
  14090. } else {
  14091. EltTy = T;
  14092. }
  14093. // Retrieve the last enumerator's value, extent that type to the
  14094. // type that is supposed to be large enough to represent the incremented
  14095. // value, then increment.
  14096. EnumVal = LastEnumConst->getInitVal();
  14097. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14098. EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
  14099. ++EnumVal;
  14100. // If we're not in C++, diagnose the overflow of enumerator values,
  14101. // which in C99 means that the enumerator value is not representable in
  14102. // an int (C99 6.7.2.2p2). However, we support GCC's extension that
  14103. // permits enumerator values that are representable in some larger
  14104. // integral type.
  14105. if (!getLangOpts().CPlusPlus && !T.isNull())
  14106. Diag(IdLoc, diag::warn_enum_value_overflow);
  14107. } else if (!getLangOpts().CPlusPlus &&
  14108. !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
  14109. // Enforce C99 6.7.2.2p2 even when we compute the next value.
  14110. Diag(IdLoc, diag::ext_enum_value_not_int)
  14111. << EnumVal.toString(10) << 1;
  14112. }
  14113. }
  14114. }
  14115. if (!EltTy->isDependentType()) {
  14116. // Make the enumerator value match the signedness and size of the
  14117. // enumerator's type.
  14118. EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
  14119. EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
  14120. }
  14121. return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
  14122. Val, EnumVal);
  14123. }
  14124. Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
  14125. SourceLocation IILoc) {
  14126. if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
  14127. !getLangOpts().CPlusPlus)
  14128. return SkipBodyInfo();
  14129. // We have an anonymous enum definition. Look up the first enumerator to
  14130. // determine if we should merge the definition with an existing one and
  14131. // skip the body.
  14132. NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
  14133. forRedeclarationInCurContext());
  14134. auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
  14135. if (!PrevECD)
  14136. return SkipBodyInfo();
  14137. EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
  14138. NamedDecl *Hidden;
  14139. if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
  14140. SkipBodyInfo Skip;
  14141. Skip.Previous = Hidden;
  14142. return Skip;
  14143. }
  14144. return SkipBodyInfo();
  14145. }
  14146. Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
  14147. SourceLocation IdLoc, IdentifierInfo *Id,
  14148. AttributeList *Attr,
  14149. SourceLocation EqualLoc, Expr *Val) {
  14150. EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
  14151. EnumConstantDecl *LastEnumConst =
  14152. cast_or_null<EnumConstantDecl>(lastEnumConst);
  14153. // The scope passed in may not be a decl scope. Zip up the scope tree until
  14154. // we find one that is.
  14155. S = getNonFieldDeclScope(S);
  14156. // Verify that there isn't already something declared with this name in this
  14157. // scope.
  14158. NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
  14159. ForVisibleRedeclaration);
  14160. if (PrevDecl && PrevDecl->isTemplateParameter()) {
  14161. // Maybe we will complain about the shadowed template parameter.
  14162. DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
  14163. // Just pretend that we didn't see the previous declaration.
  14164. PrevDecl = nullptr;
  14165. }
  14166. // C++ [class.mem]p15:
  14167. // If T is the name of a class, then each of the following shall have a name
  14168. // different from T:
  14169. // - every enumerator of every member of class T that is an unscoped
  14170. // enumerated type
  14171. if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
  14172. DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
  14173. DeclarationNameInfo(Id, IdLoc));
  14174. EnumConstantDecl *New =
  14175. CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
  14176. if (!New)
  14177. return nullptr;
  14178. if (PrevDecl) {
  14179. // When in C++, we may get a TagDecl with the same name; in this case the
  14180. // enum constant will 'hide' the tag.
  14181. assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
  14182. "Received TagDecl when not in C++!");
  14183. if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
  14184. if (isa<EnumConstantDecl>(PrevDecl))
  14185. Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
  14186. else
  14187. Diag(IdLoc, diag::err_redefinition) << Id;
  14188. notePreviousDefinition(PrevDecl, IdLoc);
  14189. return nullptr;
  14190. }
  14191. }
  14192. // Process attributes.
  14193. if (Attr) ProcessDeclAttributeList(S, New, Attr);
  14194. AddPragmaAttributes(S, New);
  14195. // Register this decl in the current scope stack.
  14196. New->setAccess(TheEnumDecl->getAccess());
  14197. PushOnScopeChains(New, S);
  14198. ActOnDocumentableDecl(New);
  14199. return New;
  14200. }
  14201. // Returns true when the enum initial expression does not trigger the
  14202. // duplicate enum warning. A few common cases are exempted as follows:
  14203. // Element2 = Element1
  14204. // Element2 = Element1 + 1
  14205. // Element2 = Element1 - 1
  14206. // Where Element2 and Element1 are from the same enum.
  14207. static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
  14208. Expr *InitExpr = ECD->getInitExpr();
  14209. if (!InitExpr)
  14210. return true;
  14211. InitExpr = InitExpr->IgnoreImpCasts();
  14212. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
  14213. if (!BO->isAdditiveOp())
  14214. return true;
  14215. IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
  14216. if (!IL)
  14217. return true;
  14218. if (IL->getValue() != 1)
  14219. return true;
  14220. InitExpr = BO->getLHS();
  14221. }
  14222. // This checks if the elements are from the same enum.
  14223. DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
  14224. if (!DRE)
  14225. return true;
  14226. EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
  14227. if (!EnumConstant)
  14228. return true;
  14229. if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
  14230. Enum)
  14231. return true;
  14232. return false;
  14233. }
  14234. // Emits a warning when an element is implicitly set a value that
  14235. // a previous element has already been set to.
  14236. static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
  14237. EnumDecl *Enum, QualType EnumType) {
  14238. // Avoid anonymous enums
  14239. if (!Enum->getIdentifier())
  14240. return;
  14241. // Only check for small enums.
  14242. if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
  14243. return;
  14244. if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
  14245. return;
  14246. typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
  14247. typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
  14248. typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
  14249. typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
  14250. // Use int64_t as a key to avoid needing special handling for DenseMap keys.
  14251. auto EnumConstantToKey = [](const EnumConstantDecl *D) {
  14252. llvm::APSInt Val = D->getInitVal();
  14253. return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
  14254. };
  14255. DuplicatesVector DupVector;
  14256. ValueToVectorMap EnumMap;
  14257. // Populate the EnumMap with all values represented by enum constants without
  14258. // an initializer.
  14259. for (auto *Element : Elements) {
  14260. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
  14261. // Null EnumConstantDecl means a previous diagnostic has been emitted for
  14262. // this constant. Skip this enum since it may be ill-formed.
  14263. if (!ECD) {
  14264. return;
  14265. }
  14266. // Constants with initalizers are handled in the next loop.
  14267. if (ECD->getInitExpr())
  14268. continue;
  14269. // Duplicate values are handled in the next loop.
  14270. EnumMap.insert({EnumConstantToKey(ECD), ECD});
  14271. }
  14272. if (EnumMap.size() == 0)
  14273. return;
  14274. // Create vectors for any values that has duplicates.
  14275. for (auto *Element : Elements) {
  14276. // The last loop returned if any constant was null.
  14277. EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
  14278. if (!ValidDuplicateEnum(ECD, Enum))
  14279. continue;
  14280. auto Iter = EnumMap.find(EnumConstantToKey(ECD));
  14281. if (Iter == EnumMap.end())
  14282. continue;
  14283. DeclOrVector& Entry = Iter->second;
  14284. if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
  14285. // Ensure constants are different.
  14286. if (D == ECD)
  14287. continue;
  14288. // Create new vector and push values onto it.
  14289. auto Vec = llvm::make_unique<ECDVector>();
  14290. Vec->push_back(D);
  14291. Vec->push_back(ECD);
  14292. // Update entry to point to the duplicates vector.
  14293. Entry = Vec.get();
  14294. // Store the vector somewhere we can consult later for quick emission of
  14295. // diagnostics.
  14296. DupVector.emplace_back(std::move(Vec));
  14297. continue;
  14298. }
  14299. ECDVector *Vec = Entry.get<ECDVector*>();
  14300. // Make sure constants are not added more than once.
  14301. if (*Vec->begin() == ECD)
  14302. continue;
  14303. Vec->push_back(ECD);
  14304. }
  14305. // Emit diagnostics.
  14306. for (const auto &Vec : DupVector) {
  14307. assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
  14308. // Emit warning for one enum constant.
  14309. auto *FirstECD = Vec->front();
  14310. S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
  14311. << FirstECD << FirstECD->getInitVal().toString(10)
  14312. << FirstECD->getSourceRange();
  14313. // Emit one note for each of the remaining enum constants with
  14314. // the same value.
  14315. for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
  14316. S.Diag(ECD->getLocation(), diag::note_duplicate_element)
  14317. << ECD << ECD->getInitVal().toString(10)
  14318. << ECD->getSourceRange();
  14319. }
  14320. }
  14321. bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
  14322. bool AllowMask) const {
  14323. assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
  14324. assert(ED->isCompleteDefinition() && "expected enum definition");
  14325. auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
  14326. llvm::APInt &FlagBits = R.first->second;
  14327. if (R.second) {
  14328. for (auto *E : ED->enumerators()) {
  14329. const auto &EVal = E->getInitVal();
  14330. // Only single-bit enumerators introduce new flag values.
  14331. if (EVal.isPowerOf2())
  14332. FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
  14333. }
  14334. }
  14335. // A value is in a flag enum if either its bits are a subset of the enum's
  14336. // flag bits (the first condition) or we are allowing masks and the same is
  14337. // true of its complement (the second condition). When masks are allowed, we
  14338. // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
  14339. //
  14340. // While it's true that any value could be used as a mask, the assumption is
  14341. // that a mask will have all of the insignificant bits set. Anything else is
  14342. // likely a logic error.
  14343. llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
  14344. return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
  14345. }
  14346. void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
  14347. Decl *EnumDeclX,
  14348. ArrayRef<Decl *> Elements,
  14349. Scope *S, AttributeList *Attr) {
  14350. EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
  14351. QualType EnumType = Context.getTypeDeclType(Enum);
  14352. if (Attr)
  14353. ProcessDeclAttributeList(S, Enum, Attr);
  14354. if (Enum->isDependentType()) {
  14355. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14356. EnumConstantDecl *ECD =
  14357. cast_or_null<EnumConstantDecl>(Elements[i]);
  14358. if (!ECD) continue;
  14359. ECD->setType(EnumType);
  14360. }
  14361. Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
  14362. return;
  14363. }
  14364. // TODO: If the result value doesn't fit in an int, it must be a long or long
  14365. // long value. ISO C does not support this, but GCC does as an extension,
  14366. // emit a warning.
  14367. unsigned IntWidth = Context.getTargetInfo().getIntWidth();
  14368. unsigned CharWidth = Context.getTargetInfo().getCharWidth();
  14369. unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
  14370. // Verify that all the values are okay, compute the size of the values, and
  14371. // reverse the list.
  14372. unsigned NumNegativeBits = 0;
  14373. unsigned NumPositiveBits = 0;
  14374. // Keep track of whether all elements have type int.
  14375. bool AllElementsInt = true;
  14376. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  14377. EnumConstantDecl *ECD =
  14378. cast_or_null<EnumConstantDecl>(Elements[i]);
  14379. if (!ECD) continue; // Already issued a diagnostic.
  14380. const llvm::APSInt &InitVal = ECD->getInitVal();
  14381. // Keep track of the size of positive and negative values.
  14382. if (InitVal.isUnsigned() || InitVal.isNonNegative())
  14383. NumPositiveBits = std::max(NumPositiveBits,
  14384. (unsigned)InitVal.getActiveBits());
  14385. else
  14386. NumNegativeBits = std::max(NumNegativeBits,
  14387. (unsigned)InitVal.getMinSignedBits());
  14388. // Keep track of whether every enum element has type int (very commmon).
  14389. if (AllElementsInt)
  14390. AllElementsInt = ECD->getType() == Context.IntTy;
  14391. }
  14392. // Figure out the type that should be used for this enum.
  14393. QualType BestType;
  14394. unsigned BestWidth;
  14395. // C++0x N3000 [conv.prom]p3:
  14396. // An rvalue of an unscoped enumeration type whose underlying
  14397. // type is not fixed can be converted to an rvalue of the first
  14398. // of the following types that can represent all the values of
  14399. // the enumeration: int, unsigned int, long int, unsigned long
  14400. // int, long long int, or unsigned long long int.
  14401. // C99 6.4.4.3p2:
  14402. // An identifier declared as an enumeration constant has type int.
  14403. // The C99 rule is modified by a gcc extension
  14404. QualType BestPromotionType;
  14405. bool Packed = Enum->hasAttr<PackedAttr>();
  14406. // -fshort-enums is the equivalent to specifying the packed attribute on all
  14407. // enum definitions.
  14408. if (LangOpts.ShortEnums)
  14409. Packed = true;
  14410. // If the enum already has a type because it is fixed or dictated by the
  14411. // target, promote that type instead of analyzing the enumerators.
  14412. if (Enum->isComplete()) {
  14413. BestType = Enum->getIntegerType();
  14414. if (BestType->isPromotableIntegerType())
  14415. BestPromotionType = Context.getPromotedIntegerType(BestType);
  14416. else
  14417. BestPromotionType = BestType;
  14418. BestWidth = Context.getIntWidth(BestType);
  14419. }
  14420. else if (NumNegativeBits) {
  14421. // If there is a negative value, figure out the smallest integer type (of
  14422. // int/long/longlong) that fits.
  14423. // If it's packed, check also if it fits a char or a short.
  14424. if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
  14425. BestType = Context.SignedCharTy;
  14426. BestWidth = CharWidth;
  14427. } else if (Packed && NumNegativeBits <= ShortWidth &&
  14428. NumPositiveBits < ShortWidth) {
  14429. BestType = Context.ShortTy;
  14430. BestWidth = ShortWidth;
  14431. } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
  14432. BestType = Context.IntTy;
  14433. BestWidth = IntWidth;
  14434. } else {
  14435. BestWidth = Context.getTargetInfo().getLongWidth();
  14436. if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
  14437. BestType = Context.LongTy;
  14438. } else {
  14439. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14440. if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
  14441. Diag(Enum->getLocation(), diag::ext_enum_too_large);
  14442. BestType = Context.LongLongTy;
  14443. }
  14444. }
  14445. BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
  14446. } else {
  14447. // If there is no negative value, figure out the smallest type that fits
  14448. // all of the enumerator values.
  14449. // If it's packed, check also if it fits a char or a short.
  14450. if (Packed && NumPositiveBits <= CharWidth) {
  14451. BestType = Context.UnsignedCharTy;
  14452. BestPromotionType = Context.IntTy;
  14453. BestWidth = CharWidth;
  14454. } else if (Packed && NumPositiveBits <= ShortWidth) {
  14455. BestType = Context.UnsignedShortTy;
  14456. BestPromotionType = Context.IntTy;
  14457. BestWidth = ShortWidth;
  14458. } else if (NumPositiveBits <= IntWidth) {
  14459. BestType = Context.UnsignedIntTy;
  14460. BestWidth = IntWidth;
  14461. BestPromotionType
  14462. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14463. ? Context.UnsignedIntTy : Context.IntTy;
  14464. } else if (NumPositiveBits <=
  14465. (BestWidth = Context.getTargetInfo().getLongWidth())) {
  14466. BestType = Context.UnsignedLongTy;
  14467. BestPromotionType
  14468. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14469. ? Context.UnsignedLongTy : Context.LongTy;
  14470. } else {
  14471. BestWidth = Context.getTargetInfo().getLongLongWidth();
  14472. assert(NumPositiveBits <= BestWidth &&
  14473. "How could an initializer get larger than ULL?");
  14474. BestType = Context.UnsignedLongLongTy;
  14475. BestPromotionType
  14476. = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
  14477. ? Context.UnsignedLongLongTy : Context.LongLongTy;
  14478. }
  14479. }
  14480. // Loop over all of the enumerator constants, changing their types to match
  14481. // the type of the enum if needed.
  14482. for (auto *D : Elements) {
  14483. auto *ECD = cast_or_null<EnumConstantDecl>(D);
  14484. if (!ECD) continue; // Already issued a diagnostic.
  14485. // Standard C says the enumerators have int type, but we allow, as an
  14486. // extension, the enumerators to be larger than int size. If each
  14487. // enumerator value fits in an int, type it as an int, otherwise type it the
  14488. // same as the enumerator decl itself. This means that in "enum { X = 1U }"
  14489. // that X has type 'int', not 'unsigned'.
  14490. // Determine whether the value fits into an int.
  14491. llvm::APSInt InitVal = ECD->getInitVal();
  14492. // If it fits into an integer type, force it. Otherwise force it to match
  14493. // the enum decl type.
  14494. QualType NewTy;
  14495. unsigned NewWidth;
  14496. bool NewSign;
  14497. if (!getLangOpts().CPlusPlus &&
  14498. !Enum->isFixed() &&
  14499. isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
  14500. NewTy = Context.IntTy;
  14501. NewWidth = IntWidth;
  14502. NewSign = true;
  14503. } else if (ECD->getType() == BestType) {
  14504. // Already the right type!
  14505. if (getLangOpts().CPlusPlus)
  14506. // C++ [dcl.enum]p4: Following the closing brace of an
  14507. // enum-specifier, each enumerator has the type of its
  14508. // enumeration.
  14509. ECD->setType(EnumType);
  14510. continue;
  14511. } else {
  14512. NewTy = BestType;
  14513. NewWidth = BestWidth;
  14514. NewSign = BestType->isSignedIntegerOrEnumerationType();
  14515. }
  14516. // Adjust the APSInt value.
  14517. InitVal = InitVal.extOrTrunc(NewWidth);
  14518. InitVal.setIsSigned(NewSign);
  14519. ECD->setInitVal(InitVal);
  14520. // Adjust the Expr initializer and type.
  14521. if (ECD->getInitExpr() &&
  14522. !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
  14523. ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
  14524. CK_IntegralCast,
  14525. ECD->getInitExpr(),
  14526. /*base paths*/ nullptr,
  14527. VK_RValue));
  14528. if (getLangOpts().CPlusPlus)
  14529. // C++ [dcl.enum]p4: Following the closing brace of an
  14530. // enum-specifier, each enumerator has the type of its
  14531. // enumeration.
  14532. ECD->setType(EnumType);
  14533. else
  14534. ECD->setType(NewTy);
  14535. }
  14536. Enum->completeDefinition(BestType, BestPromotionType,
  14537. NumPositiveBits, NumNegativeBits);
  14538. CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
  14539. if (Enum->isClosedFlag()) {
  14540. for (Decl *D : Elements) {
  14541. EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
  14542. if (!ECD) continue; // Already issued a diagnostic.
  14543. llvm::APSInt InitVal = ECD->getInitVal();
  14544. if (InitVal != 0 && !InitVal.isPowerOf2() &&
  14545. !IsValueInFlagEnum(Enum, InitVal, true))
  14546. Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
  14547. << ECD << Enum;
  14548. }
  14549. }
  14550. // Now that the enum type is defined, ensure it's not been underaligned.
  14551. if (Enum->hasAttrs())
  14552. CheckAlignasUnderalignment(Enum);
  14553. }
  14554. Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
  14555. SourceLocation StartLoc,
  14556. SourceLocation EndLoc) {
  14557. StringLiteral *AsmString = cast<StringLiteral>(expr);
  14558. FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
  14559. AsmString, StartLoc,
  14560. EndLoc);
  14561. CurContext->addDecl(New);
  14562. return New;
  14563. }
  14564. static void checkModuleImportContext(Sema &S, Module *M,
  14565. SourceLocation ImportLoc, DeclContext *DC,
  14566. bool FromInclude = false) {
  14567. SourceLocation ExternCLoc;
  14568. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  14569. switch (LSD->getLanguage()) {
  14570. case LinkageSpecDecl::lang_c:
  14571. if (ExternCLoc.isInvalid())
  14572. ExternCLoc = LSD->getLocStart();
  14573. break;
  14574. case LinkageSpecDecl::lang_cxx:
  14575. break;
  14576. }
  14577. DC = LSD->getParent();
  14578. }
  14579. while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
  14580. DC = DC->getParent();
  14581. if (!isa<TranslationUnitDecl>(DC)) {
  14582. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  14583. ? diag::ext_module_import_not_at_top_level_noop
  14584. : diag::err_module_import_not_at_top_level_fatal)
  14585. << M->getFullModuleName() << DC;
  14586. S.Diag(cast<Decl>(DC)->getLocStart(),
  14587. diag::note_module_import_not_at_top_level) << DC;
  14588. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  14589. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  14590. << M->getFullModuleName();
  14591. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  14592. }
  14593. }
  14594. Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
  14595. SourceLocation ModuleLoc,
  14596. ModuleDeclKind MDK,
  14597. ModuleIdPath Path) {
  14598. assert(getLangOpts().ModulesTS &&
  14599. "should only have module decl in modules TS");
  14600. // A module implementation unit requires that we are not compiling a module
  14601. // of any kind. A module interface unit requires that we are not compiling a
  14602. // module map.
  14603. switch (getLangOpts().getCompilingModule()) {
  14604. case LangOptions::CMK_None:
  14605. // It's OK to compile a module interface as a normal translation unit.
  14606. break;
  14607. case LangOptions::CMK_ModuleInterface:
  14608. if (MDK != ModuleDeclKind::Implementation)
  14609. break;
  14610. // We were asked to compile a module interface unit but this is a module
  14611. // implementation unit. That indicates the 'export' is missing.
  14612. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  14613. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  14614. MDK = ModuleDeclKind::Interface;
  14615. break;
  14616. case LangOptions::CMK_ModuleMap:
  14617. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  14618. return nullptr;
  14619. }
  14620. assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
  14621. // FIXME: Most of this work should be done by the preprocessor rather than
  14622. // here, in order to support macro import.
  14623. // Only one module-declaration is permitted per source file.
  14624. if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
  14625. Diag(ModuleLoc, diag::err_module_redeclaration);
  14626. Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
  14627. diag::note_prev_module_declaration);
  14628. return nullptr;
  14629. }
  14630. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  14631. // modules, the dots here are just another character that can appear in a
  14632. // module name.
  14633. std::string ModuleName;
  14634. for (auto &Piece : Path) {
  14635. if (!ModuleName.empty())
  14636. ModuleName += ".";
  14637. ModuleName += Piece.first->getName();
  14638. }
  14639. // If a module name was explicitly specified on the command line, it must be
  14640. // correct.
  14641. if (!getLangOpts().CurrentModule.empty() &&
  14642. getLangOpts().CurrentModule != ModuleName) {
  14643. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  14644. << SourceRange(Path.front().second, Path.back().second)
  14645. << getLangOpts().CurrentModule;
  14646. return nullptr;
  14647. }
  14648. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  14649. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  14650. Module *Mod;
  14651. switch (MDK) {
  14652. case ModuleDeclKind::Interface: {
  14653. // We can't have parsed or imported a definition of this module or parsed a
  14654. // module map defining it already.
  14655. if (auto *M = Map.findModule(ModuleName)) {
  14656. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  14657. if (M->DefinitionLoc.isValid())
  14658. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  14659. else if (const auto *FE = M->getASTFile())
  14660. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  14661. << FE->getName();
  14662. Mod = M;
  14663. break;
  14664. }
  14665. // Create a Module for the module that we're defining.
  14666. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14667. ModuleScopes.front().Module);
  14668. assert(Mod && "module creation should not fail");
  14669. break;
  14670. }
  14671. case ModuleDeclKind::Partition:
  14672. // FIXME: Check we are in a submodule of the named module.
  14673. return nullptr;
  14674. case ModuleDeclKind::Implementation:
  14675. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  14676. PP.getIdentifierInfo(ModuleName), Path[0].second);
  14677. Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
  14678. /*IsIncludeDirective=*/false);
  14679. if (!Mod) {
  14680. Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
  14681. // Create an empty module interface unit for error recovery.
  14682. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  14683. ModuleScopes.front().Module);
  14684. }
  14685. break;
  14686. }
  14687. // Switch from the global module to the named module.
  14688. ModuleScopes.back().Module = Mod;
  14689. ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
  14690. VisibleModules.setVisible(Mod, ModuleLoc);
  14691. // From now on, we have an owning module for all declarations we see.
  14692. // However, those declarations are module-private unless explicitly
  14693. // exported.
  14694. auto *TU = Context.getTranslationUnitDecl();
  14695. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  14696. TU->setLocalOwningModule(Mod);
  14697. // FIXME: Create a ModuleDecl.
  14698. return nullptr;
  14699. }
  14700. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  14701. SourceLocation ImportLoc,
  14702. ModuleIdPath Path) {
  14703. Module *Mod =
  14704. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  14705. /*IsIncludeDirective=*/false);
  14706. if (!Mod)
  14707. return true;
  14708. VisibleModules.setVisible(Mod, ImportLoc);
  14709. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  14710. // FIXME: we should support importing a submodule within a different submodule
  14711. // of the same top-level module. Until we do, make it an error rather than
  14712. // silently ignoring the import.
  14713. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  14714. // warn on a redundant import of the current module?
  14715. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  14716. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
  14717. Diag(ImportLoc, getLangOpts().isCompilingModule()
  14718. ? diag::err_module_self_import
  14719. : diag::err_module_import_in_implementation)
  14720. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  14721. SmallVector<SourceLocation, 2> IdentifierLocs;
  14722. Module *ModCheck = Mod;
  14723. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  14724. // If we've run out of module parents, just drop the remaining identifiers.
  14725. // We need the length to be consistent.
  14726. if (!ModCheck)
  14727. break;
  14728. ModCheck = ModCheck->Parent;
  14729. IdentifierLocs.push_back(Path[I].second);
  14730. }
  14731. ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
  14732. Mod, IdentifierLocs);
  14733. if (!ModuleScopes.empty())
  14734. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  14735. CurContext->addDecl(Import);
  14736. // Re-export the module if needed.
  14737. if (Import->isExported() &&
  14738. !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
  14739. getCurrentModule()->Exports.emplace_back(Mod, false);
  14740. return Import;
  14741. }
  14742. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14743. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14744. BuildModuleInclude(DirectiveLoc, Mod);
  14745. }
  14746. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  14747. // Determine whether we're in the #include buffer for a module. The #includes
  14748. // in that buffer do not qualify as module imports; they're just an
  14749. // implementation detail of us building the module.
  14750. //
  14751. // FIXME: Should we even get ActOnModuleInclude calls for those?
  14752. bool IsInModuleIncludes =
  14753. TUKind == TU_Module &&
  14754. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  14755. bool ShouldAddImport = !IsInModuleIncludes;
  14756. // If this module import was due to an inclusion directive, create an
  14757. // implicit import declaration to capture it in the AST.
  14758. if (ShouldAddImport) {
  14759. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14760. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14761. DirectiveLoc, Mod,
  14762. DirectiveLoc);
  14763. if (!ModuleScopes.empty())
  14764. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  14765. TU->addDecl(ImportD);
  14766. Consumer.HandleImplicitImportDecl(ImportD);
  14767. }
  14768. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  14769. VisibleModules.setVisible(Mod, DirectiveLoc);
  14770. }
  14771. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  14772. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  14773. ModuleScopes.push_back({});
  14774. ModuleScopes.back().Module = Mod;
  14775. if (getLangOpts().ModulesLocalVisibility)
  14776. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  14777. VisibleModules.setVisible(Mod, DirectiveLoc);
  14778. // The enclosing context is now part of this module.
  14779. // FIXME: Consider creating a child DeclContext to hold the entities
  14780. // lexically within the module.
  14781. if (getLangOpts().trackLocalOwningModule()) {
  14782. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14783. cast<Decl>(DC)->setModuleOwnershipKind(
  14784. getLangOpts().ModulesLocalVisibility
  14785. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  14786. : Decl::ModuleOwnershipKind::Visible);
  14787. cast<Decl>(DC)->setLocalOwningModule(Mod);
  14788. }
  14789. }
  14790. }
  14791. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  14792. if (getLangOpts().ModulesLocalVisibility) {
  14793. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  14794. // Leaving a module hides namespace names, so our visible namespace cache
  14795. // is now out of date.
  14796. VisibleNamespaceCache.clear();
  14797. }
  14798. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  14799. "left the wrong module scope");
  14800. ModuleScopes.pop_back();
  14801. // We got to the end of processing a local module. Create an
  14802. // ImportDecl as we would for an imported module.
  14803. FileID File = getSourceManager().getFileID(EomLoc);
  14804. SourceLocation DirectiveLoc;
  14805. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  14806. // We reached the end of a #included module header. Use the #include loc.
  14807. assert(File != getSourceManager().getMainFileID() &&
  14808. "end of submodule in main source file");
  14809. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  14810. } else {
  14811. // We reached an EOM pragma. Use the pragma location.
  14812. DirectiveLoc = EomLoc;
  14813. }
  14814. BuildModuleInclude(DirectiveLoc, Mod);
  14815. // Any further declarations are in whatever module we returned to.
  14816. if (getLangOpts().trackLocalOwningModule()) {
  14817. // The parser guarantees that this is the same context that we entered
  14818. // the module within.
  14819. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  14820. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  14821. if (!getCurrentModule())
  14822. cast<Decl>(DC)->setModuleOwnershipKind(
  14823. Decl::ModuleOwnershipKind::Unowned);
  14824. }
  14825. }
  14826. }
  14827. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  14828. Module *Mod) {
  14829. // Bail if we're not allowed to implicitly import a module here.
  14830. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  14831. VisibleModules.isVisible(Mod))
  14832. return;
  14833. // Create the implicit import declaration.
  14834. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  14835. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  14836. Loc, Mod, Loc);
  14837. TU->addDecl(ImportD);
  14838. Consumer.HandleImplicitImportDecl(ImportD);
  14839. // Make the module visible.
  14840. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  14841. VisibleModules.setVisible(Mod, Loc);
  14842. }
  14843. /// We have parsed the start of an export declaration, including the '{'
  14844. /// (if present).
  14845. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  14846. SourceLocation LBraceLoc) {
  14847. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  14848. // C++ Modules TS draft:
  14849. // An export-declaration shall appear in the purview of a module other than
  14850. // the global module.
  14851. if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
  14852. Diag(ExportLoc, diag::err_export_not_in_module_interface);
  14853. // An export-declaration [...] shall not contain more than one
  14854. // export keyword.
  14855. //
  14856. // The intent here is that an export-declaration cannot appear within another
  14857. // export-declaration.
  14858. if (D->isExported())
  14859. Diag(ExportLoc, diag::err_export_within_export);
  14860. CurContext->addDecl(D);
  14861. PushDeclContext(S, D);
  14862. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  14863. return D;
  14864. }
  14865. /// Complete the definition of an export declaration.
  14866. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  14867. auto *ED = cast<ExportDecl>(D);
  14868. if (RBraceLoc.isValid())
  14869. ED->setRBraceLoc(RBraceLoc);
  14870. // FIXME: Diagnose export of internal-linkage declaration (including
  14871. // anonymous namespace).
  14872. PopDeclContext();
  14873. return D;
  14874. }
  14875. void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
  14876. IdentifierInfo* AliasName,
  14877. SourceLocation PragmaLoc,
  14878. SourceLocation NameLoc,
  14879. SourceLocation AliasNameLoc) {
  14880. NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
  14881. LookupOrdinaryName);
  14882. AsmLabelAttr *Attr =
  14883. AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
  14884. // If a declaration that:
  14885. // 1) declares a function or a variable
  14886. // 2) has external linkage
  14887. // already exists, add a label attribute to it.
  14888. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14889. if (isDeclExternC(PrevDecl))
  14890. PrevDecl->addAttr(Attr);
  14891. else
  14892. Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
  14893. << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
  14894. // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
  14895. } else
  14896. (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
  14897. }
  14898. void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
  14899. SourceLocation PragmaLoc,
  14900. SourceLocation NameLoc) {
  14901. Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
  14902. if (PrevDecl) {
  14903. PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
  14904. } else {
  14905. (void)WeakUndeclaredIdentifiers.insert(
  14906. std::pair<IdentifierInfo*,WeakInfo>
  14907. (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
  14908. }
  14909. }
  14910. void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
  14911. IdentifierInfo* AliasName,
  14912. SourceLocation PragmaLoc,
  14913. SourceLocation NameLoc,
  14914. SourceLocation AliasNameLoc) {
  14915. Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
  14916. LookupOrdinaryName);
  14917. WeakInfo W = WeakInfo(Name, NameLoc);
  14918. if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
  14919. if (!PrevDecl->hasAttr<AliasAttr>())
  14920. if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
  14921. DeclApplyPragmaWeak(TUScope, ND, W);
  14922. } else {
  14923. (void)WeakUndeclaredIdentifiers.insert(
  14924. std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
  14925. }
  14926. }
  14927. Decl *Sema::getObjCDeclContext() const {
  14928. return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
  14929. }