SemaType.cpp 317 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461
  1. //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements type-related semantic analysis.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TypeLocBuilder.h"
  13. #include "clang/AST/ASTConsumer.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/ASTStructuralEquivalence.h"
  17. #include "clang/AST/CXXInheritance.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/TypeLoc.h"
  22. #include "clang/AST/TypeLocVisitor.h"
  23. #include "clang/Basic/PartialDiagnostic.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Sema/DeclSpec.h"
  27. #include "clang/Sema/DelayedDiagnostic.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/ScopeInfo.h"
  30. #include "clang/Sema/SemaInternal.h"
  31. #include "clang/Sema/Template.h"
  32. #include "clang/Sema/TemplateInstCallback.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/StringSwitch.h"
  36. #include "llvm/Support/ErrorHandling.h"
  37. using namespace clang;
  38. enum TypeDiagSelector {
  39. TDS_Function,
  40. TDS_Pointer,
  41. TDS_ObjCObjOrBlock
  42. };
  43. /// isOmittedBlockReturnType - Return true if this declarator is missing a
  44. /// return type because this is a omitted return type on a block literal.
  45. static bool isOmittedBlockReturnType(const Declarator &D) {
  46. if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
  47. D.getDeclSpec().hasTypeSpecifier())
  48. return false;
  49. if (D.getNumTypeObjects() == 0)
  50. return true; // ^{ ... }
  51. if (D.getNumTypeObjects() == 1 &&
  52. D.getTypeObject(0).Kind == DeclaratorChunk::Function)
  53. return true; // ^(int X, float Y) { ... }
  54. return false;
  55. }
  56. /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
  57. /// doesn't apply to the given type.
  58. static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
  59. QualType type) {
  60. TypeDiagSelector WhichType;
  61. bool useExpansionLoc = true;
  62. switch (attr.getKind()) {
  63. case ParsedAttr::AT_ObjCGC:
  64. WhichType = TDS_Pointer;
  65. break;
  66. case ParsedAttr::AT_ObjCOwnership:
  67. WhichType = TDS_ObjCObjOrBlock;
  68. break;
  69. default:
  70. // Assume everything else was a function attribute.
  71. WhichType = TDS_Function;
  72. useExpansionLoc = false;
  73. break;
  74. }
  75. SourceLocation loc = attr.getLoc();
  76. StringRef name = attr.getAttrName()->getName();
  77. // The GC attributes are usually written with macros; special-case them.
  78. IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
  79. : nullptr;
  80. if (useExpansionLoc && loc.isMacroID() && II) {
  81. if (II->isStr("strong")) {
  82. if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
  83. } else if (II->isStr("weak")) {
  84. if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
  85. }
  86. }
  87. S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
  88. << type;
  89. }
  90. // objc_gc applies to Objective-C pointers or, otherwise, to the
  91. // smallest available pointer type (i.e. 'void*' in 'void**').
  92. #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
  93. case ParsedAttr::AT_ObjCGC: \
  94. case ParsedAttr::AT_ObjCOwnership
  95. // Calling convention attributes.
  96. #define CALLING_CONV_ATTRS_CASELIST \
  97. case ParsedAttr::AT_CDecl: \
  98. case ParsedAttr::AT_FastCall: \
  99. case ParsedAttr::AT_StdCall: \
  100. case ParsedAttr::AT_ThisCall: \
  101. case ParsedAttr::AT_RegCall: \
  102. case ParsedAttr::AT_Pascal: \
  103. case ParsedAttr::AT_SwiftCall: \
  104. case ParsedAttr::AT_VectorCall: \
  105. case ParsedAttr::AT_AArch64VectorPcs: \
  106. case ParsedAttr::AT_MSABI: \
  107. case ParsedAttr::AT_SysVABI: \
  108. case ParsedAttr::AT_Pcs: \
  109. case ParsedAttr::AT_IntelOclBicc: \
  110. case ParsedAttr::AT_PreserveMost: \
  111. case ParsedAttr::AT_PreserveAll
  112. // Function type attributes.
  113. #define FUNCTION_TYPE_ATTRS_CASELIST \
  114. case ParsedAttr::AT_NSReturnsRetained: \
  115. case ParsedAttr::AT_NoReturn: \
  116. case ParsedAttr::AT_Regparm: \
  117. case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
  118. case ParsedAttr::AT_AnyX86NoCfCheck: \
  119. CALLING_CONV_ATTRS_CASELIST
  120. // Microsoft-specific type qualifiers.
  121. #define MS_TYPE_ATTRS_CASELIST \
  122. case ParsedAttr::AT_Ptr32: \
  123. case ParsedAttr::AT_Ptr64: \
  124. case ParsedAttr::AT_SPtr: \
  125. case ParsedAttr::AT_UPtr
  126. // Nullability qualifiers.
  127. #define NULLABILITY_TYPE_ATTRS_CASELIST \
  128. case ParsedAttr::AT_TypeNonNull: \
  129. case ParsedAttr::AT_TypeNullable: \
  130. case ParsedAttr::AT_TypeNullUnspecified
  131. namespace {
  132. /// An object which stores processing state for the entire
  133. /// GetTypeForDeclarator process.
  134. class TypeProcessingState {
  135. Sema &sema;
  136. /// The declarator being processed.
  137. Declarator &declarator;
  138. /// The index of the declarator chunk we're currently processing.
  139. /// May be the total number of valid chunks, indicating the
  140. /// DeclSpec.
  141. unsigned chunkIndex;
  142. /// Whether there are non-trivial modifications to the decl spec.
  143. bool trivial;
  144. /// Whether we saved the attributes in the decl spec.
  145. bool hasSavedAttrs;
  146. /// The original set of attributes on the DeclSpec.
  147. SmallVector<ParsedAttr *, 2> savedAttrs;
  148. /// A list of attributes to diagnose the uselessness of when the
  149. /// processing is complete.
  150. SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
  151. /// Attributes corresponding to AttributedTypeLocs that we have not yet
  152. /// populated.
  153. // FIXME: The two-phase mechanism by which we construct Types and fill
  154. // their TypeLocs makes it hard to correctly assign these. We keep the
  155. // attributes in creation order as an attempt to make them line up
  156. // properly.
  157. using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
  158. SmallVector<TypeAttrPair, 8> AttrsForTypes;
  159. bool AttrsForTypesSorted = true;
  160. /// MacroQualifiedTypes mapping to macro expansion locations that will be
  161. /// stored in a MacroQualifiedTypeLoc.
  162. llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
  163. /// Flag to indicate we parsed a noderef attribute. This is used for
  164. /// validating that noderef was used on a pointer or array.
  165. bool parsedNoDeref;
  166. public:
  167. TypeProcessingState(Sema &sema, Declarator &declarator)
  168. : sema(sema), declarator(declarator),
  169. chunkIndex(declarator.getNumTypeObjects()), trivial(true),
  170. hasSavedAttrs(false), parsedNoDeref(false) {}
  171. Sema &getSema() const {
  172. return sema;
  173. }
  174. Declarator &getDeclarator() const {
  175. return declarator;
  176. }
  177. bool isProcessingDeclSpec() const {
  178. return chunkIndex == declarator.getNumTypeObjects();
  179. }
  180. unsigned getCurrentChunkIndex() const {
  181. return chunkIndex;
  182. }
  183. void setCurrentChunkIndex(unsigned idx) {
  184. assert(idx <= declarator.getNumTypeObjects());
  185. chunkIndex = idx;
  186. }
  187. ParsedAttributesView &getCurrentAttributes() const {
  188. if (isProcessingDeclSpec())
  189. return getMutableDeclSpec().getAttributes();
  190. return declarator.getTypeObject(chunkIndex).getAttrs();
  191. }
  192. /// Save the current set of attributes on the DeclSpec.
  193. void saveDeclSpecAttrs() {
  194. // Don't try to save them multiple times.
  195. if (hasSavedAttrs) return;
  196. DeclSpec &spec = getMutableDeclSpec();
  197. for (ParsedAttr &AL : spec.getAttributes())
  198. savedAttrs.push_back(&AL);
  199. trivial &= savedAttrs.empty();
  200. hasSavedAttrs = true;
  201. }
  202. /// Record that we had nowhere to put the given type attribute.
  203. /// We will diagnose such attributes later.
  204. void addIgnoredTypeAttr(ParsedAttr &attr) {
  205. ignoredTypeAttrs.push_back(&attr);
  206. }
  207. /// Diagnose all the ignored type attributes, given that the
  208. /// declarator worked out to the given type.
  209. void diagnoseIgnoredTypeAttrs(QualType type) const {
  210. for (auto *Attr : ignoredTypeAttrs)
  211. diagnoseBadTypeAttribute(getSema(), *Attr, type);
  212. }
  213. /// Get an attributed type for the given attribute, and remember the Attr
  214. /// object so that we can attach it to the AttributedTypeLoc.
  215. QualType getAttributedType(Attr *A, QualType ModifiedType,
  216. QualType EquivType) {
  217. QualType T =
  218. sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
  219. AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
  220. AttrsForTypesSorted = false;
  221. return T;
  222. }
  223. /// Completely replace the \c auto in \p TypeWithAuto by
  224. /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
  225. /// necessary.
  226. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
  227. QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
  228. if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
  229. // Attributed type still should be an attributed type after replacement.
  230. auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
  231. for (TypeAttrPair &A : AttrsForTypes) {
  232. if (A.first == AttrTy)
  233. A.first = NewAttrTy;
  234. }
  235. AttrsForTypesSorted = false;
  236. }
  237. return T;
  238. }
  239. /// Extract and remove the Attr* for a given attributed type.
  240. const Attr *takeAttrForAttributedType(const AttributedType *AT) {
  241. if (!AttrsForTypesSorted) {
  242. llvm::stable_sort(AttrsForTypes, llvm::less_first());
  243. AttrsForTypesSorted = true;
  244. }
  245. // FIXME: This is quadratic if we have lots of reuses of the same
  246. // attributed type.
  247. for (auto It = std::partition_point(
  248. AttrsForTypes.begin(), AttrsForTypes.end(),
  249. [=](const TypeAttrPair &A) { return A.first < AT; });
  250. It != AttrsForTypes.end() && It->first == AT; ++It) {
  251. if (It->second) {
  252. const Attr *Result = It->second;
  253. It->second = nullptr;
  254. return Result;
  255. }
  256. }
  257. llvm_unreachable("no Attr* for AttributedType*");
  258. }
  259. SourceLocation
  260. getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
  261. auto FoundLoc = LocsForMacros.find(MQT);
  262. assert(FoundLoc != LocsForMacros.end() &&
  263. "Unable to find macro expansion location for MacroQualifedType");
  264. return FoundLoc->second;
  265. }
  266. void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
  267. SourceLocation Loc) {
  268. LocsForMacros[MQT] = Loc;
  269. }
  270. void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
  271. bool didParseNoDeref() const { return parsedNoDeref; }
  272. ~TypeProcessingState() {
  273. if (trivial) return;
  274. restoreDeclSpecAttrs();
  275. }
  276. private:
  277. DeclSpec &getMutableDeclSpec() const {
  278. return const_cast<DeclSpec&>(declarator.getDeclSpec());
  279. }
  280. void restoreDeclSpecAttrs() {
  281. assert(hasSavedAttrs);
  282. getMutableDeclSpec().getAttributes().clearListOnly();
  283. for (ParsedAttr *AL : savedAttrs)
  284. getMutableDeclSpec().getAttributes().addAtEnd(AL);
  285. }
  286. };
  287. } // end anonymous namespace
  288. static void moveAttrFromListToList(ParsedAttr &attr,
  289. ParsedAttributesView &fromList,
  290. ParsedAttributesView &toList) {
  291. fromList.remove(&attr);
  292. toList.addAtEnd(&attr);
  293. }
  294. /// The location of a type attribute.
  295. enum TypeAttrLocation {
  296. /// The attribute is in the decl-specifier-seq.
  297. TAL_DeclSpec,
  298. /// The attribute is part of a DeclaratorChunk.
  299. TAL_DeclChunk,
  300. /// The attribute is immediately after the declaration's name.
  301. TAL_DeclName
  302. };
  303. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  304. TypeAttrLocation TAL, ParsedAttributesView &attrs);
  305. static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  306. QualType &type);
  307. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
  308. ParsedAttr &attr, QualType &type);
  309. static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  310. QualType &type);
  311. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  312. ParsedAttr &attr, QualType &type);
  313. static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
  314. ParsedAttr &attr, QualType &type) {
  315. if (attr.getKind() == ParsedAttr::AT_ObjCGC)
  316. return handleObjCGCTypeAttr(state, attr, type);
  317. assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
  318. return handleObjCOwnershipTypeAttr(state, attr, type);
  319. }
  320. /// Given the index of a declarator chunk, check whether that chunk
  321. /// directly specifies the return type of a function and, if so, find
  322. /// an appropriate place for it.
  323. ///
  324. /// \param i - a notional index which the search will start
  325. /// immediately inside
  326. ///
  327. /// \param onlyBlockPointers Whether we should only look into block
  328. /// pointer types (vs. all pointer types).
  329. static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
  330. unsigned i,
  331. bool onlyBlockPointers) {
  332. assert(i <= declarator.getNumTypeObjects());
  333. DeclaratorChunk *result = nullptr;
  334. // First, look inwards past parens for a function declarator.
  335. for (; i != 0; --i) {
  336. DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
  337. switch (fnChunk.Kind) {
  338. case DeclaratorChunk::Paren:
  339. continue;
  340. // If we find anything except a function, bail out.
  341. case DeclaratorChunk::Pointer:
  342. case DeclaratorChunk::BlockPointer:
  343. case DeclaratorChunk::Array:
  344. case DeclaratorChunk::Reference:
  345. case DeclaratorChunk::MemberPointer:
  346. case DeclaratorChunk::Pipe:
  347. return result;
  348. // If we do find a function declarator, scan inwards from that,
  349. // looking for a (block-)pointer declarator.
  350. case DeclaratorChunk::Function:
  351. for (--i; i != 0; --i) {
  352. DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
  353. switch (ptrChunk.Kind) {
  354. case DeclaratorChunk::Paren:
  355. case DeclaratorChunk::Array:
  356. case DeclaratorChunk::Function:
  357. case DeclaratorChunk::Reference:
  358. case DeclaratorChunk::Pipe:
  359. continue;
  360. case DeclaratorChunk::MemberPointer:
  361. case DeclaratorChunk::Pointer:
  362. if (onlyBlockPointers)
  363. continue;
  364. LLVM_FALLTHROUGH;
  365. case DeclaratorChunk::BlockPointer:
  366. result = &ptrChunk;
  367. goto continue_outer;
  368. }
  369. llvm_unreachable("bad declarator chunk kind");
  370. }
  371. // If we run out of declarators doing that, we're done.
  372. return result;
  373. }
  374. llvm_unreachable("bad declarator chunk kind");
  375. // Okay, reconsider from our new point.
  376. continue_outer: ;
  377. }
  378. // Ran out of chunks, bail out.
  379. return result;
  380. }
  381. /// Given that an objc_gc attribute was written somewhere on a
  382. /// declaration *other* than on the declarator itself (for which, use
  383. /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
  384. /// didn't apply in whatever position it was written in, try to move
  385. /// it to a more appropriate position.
  386. static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
  387. ParsedAttr &attr, QualType type) {
  388. Declarator &declarator = state.getDeclarator();
  389. // Move it to the outermost normal or block pointer declarator.
  390. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  391. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  392. switch (chunk.Kind) {
  393. case DeclaratorChunk::Pointer:
  394. case DeclaratorChunk::BlockPointer: {
  395. // But don't move an ARC ownership attribute to the return type
  396. // of a block.
  397. DeclaratorChunk *destChunk = nullptr;
  398. if (state.isProcessingDeclSpec() &&
  399. attr.getKind() == ParsedAttr::AT_ObjCOwnership)
  400. destChunk = maybeMovePastReturnType(declarator, i - 1,
  401. /*onlyBlockPointers=*/true);
  402. if (!destChunk) destChunk = &chunk;
  403. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  404. destChunk->getAttrs());
  405. return;
  406. }
  407. case DeclaratorChunk::Paren:
  408. case DeclaratorChunk::Array:
  409. continue;
  410. // We may be starting at the return type of a block.
  411. case DeclaratorChunk::Function:
  412. if (state.isProcessingDeclSpec() &&
  413. attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
  414. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  415. declarator, i,
  416. /*onlyBlockPointers=*/true)) {
  417. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  418. dest->getAttrs());
  419. return;
  420. }
  421. }
  422. goto error;
  423. // Don't walk through these.
  424. case DeclaratorChunk::Reference:
  425. case DeclaratorChunk::MemberPointer:
  426. case DeclaratorChunk::Pipe:
  427. goto error;
  428. }
  429. }
  430. error:
  431. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  432. }
  433. /// Distribute an objc_gc type attribute that was written on the
  434. /// declarator.
  435. static void distributeObjCPointerTypeAttrFromDeclarator(
  436. TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
  437. Declarator &declarator = state.getDeclarator();
  438. // objc_gc goes on the innermost pointer to something that's not a
  439. // pointer.
  440. unsigned innermost = -1U;
  441. bool considerDeclSpec = true;
  442. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  443. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  444. switch (chunk.Kind) {
  445. case DeclaratorChunk::Pointer:
  446. case DeclaratorChunk::BlockPointer:
  447. innermost = i;
  448. continue;
  449. case DeclaratorChunk::Reference:
  450. case DeclaratorChunk::MemberPointer:
  451. case DeclaratorChunk::Paren:
  452. case DeclaratorChunk::Array:
  453. case DeclaratorChunk::Pipe:
  454. continue;
  455. case DeclaratorChunk::Function:
  456. considerDeclSpec = false;
  457. goto done;
  458. }
  459. }
  460. done:
  461. // That might actually be the decl spec if we weren't blocked by
  462. // anything in the declarator.
  463. if (considerDeclSpec) {
  464. if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
  465. // Splice the attribute into the decl spec. Prevents the
  466. // attribute from being applied multiple times and gives
  467. // the source-location-filler something to work with.
  468. state.saveDeclSpecAttrs();
  469. declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
  470. declarator.getAttributes(), &attr);
  471. return;
  472. }
  473. }
  474. // Otherwise, if we found an appropriate chunk, splice the attribute
  475. // into it.
  476. if (innermost != -1U) {
  477. moveAttrFromListToList(attr, declarator.getAttributes(),
  478. declarator.getTypeObject(innermost).getAttrs());
  479. return;
  480. }
  481. // Otherwise, diagnose when we're done building the type.
  482. declarator.getAttributes().remove(&attr);
  483. state.addIgnoredTypeAttr(attr);
  484. }
  485. /// A function type attribute was written somewhere in a declaration
  486. /// *other* than on the declarator itself or in the decl spec. Given
  487. /// that it didn't apply in whatever position it was written in, try
  488. /// to move it to a more appropriate position.
  489. static void distributeFunctionTypeAttr(TypeProcessingState &state,
  490. ParsedAttr &attr, QualType type) {
  491. Declarator &declarator = state.getDeclarator();
  492. // Try to push the attribute from the return type of a function to
  493. // the function itself.
  494. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  495. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  496. switch (chunk.Kind) {
  497. case DeclaratorChunk::Function:
  498. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  499. chunk.getAttrs());
  500. return;
  501. case DeclaratorChunk::Paren:
  502. case DeclaratorChunk::Pointer:
  503. case DeclaratorChunk::BlockPointer:
  504. case DeclaratorChunk::Array:
  505. case DeclaratorChunk::Reference:
  506. case DeclaratorChunk::MemberPointer:
  507. case DeclaratorChunk::Pipe:
  508. continue;
  509. }
  510. }
  511. diagnoseBadTypeAttribute(state.getSema(), attr, type);
  512. }
  513. /// Try to distribute a function type attribute to the innermost
  514. /// function chunk or type. Returns true if the attribute was
  515. /// distributed, false if no location was found.
  516. static bool distributeFunctionTypeAttrToInnermost(
  517. TypeProcessingState &state, ParsedAttr &attr,
  518. ParsedAttributesView &attrList, QualType &declSpecType) {
  519. Declarator &declarator = state.getDeclarator();
  520. // Put it on the innermost function chunk, if there is one.
  521. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  522. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  523. if (chunk.Kind != DeclaratorChunk::Function) continue;
  524. moveAttrFromListToList(attr, attrList, chunk.getAttrs());
  525. return true;
  526. }
  527. return handleFunctionTypeAttr(state, attr, declSpecType);
  528. }
  529. /// A function type attribute was written in the decl spec. Try to
  530. /// apply it somewhere.
  531. static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
  532. ParsedAttr &attr,
  533. QualType &declSpecType) {
  534. state.saveDeclSpecAttrs();
  535. // C++11 attributes before the decl specifiers actually appertain to
  536. // the declarators. Move them straight there. We don't support the
  537. // 'put them wherever you like' semantics we allow for GNU attributes.
  538. if (attr.isCXX11Attribute()) {
  539. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  540. state.getDeclarator().getAttributes());
  541. return;
  542. }
  543. // Try to distribute to the innermost.
  544. if (distributeFunctionTypeAttrToInnermost(
  545. state, attr, state.getCurrentAttributes(), declSpecType))
  546. return;
  547. // If that failed, diagnose the bad attribute when the declarator is
  548. // fully built.
  549. state.addIgnoredTypeAttr(attr);
  550. }
  551. /// A function type attribute was written on the declarator. Try to
  552. /// apply it somewhere.
  553. static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
  554. ParsedAttr &attr,
  555. QualType &declSpecType) {
  556. Declarator &declarator = state.getDeclarator();
  557. // Try to distribute to the innermost.
  558. if (distributeFunctionTypeAttrToInnermost(
  559. state, attr, declarator.getAttributes(), declSpecType))
  560. return;
  561. // If that failed, diagnose the bad attribute when the declarator is
  562. // fully built.
  563. declarator.getAttributes().remove(&attr);
  564. state.addIgnoredTypeAttr(attr);
  565. }
  566. /// Given that there are attributes written on the declarator
  567. /// itself, try to distribute any type attributes to the appropriate
  568. /// declarator chunk.
  569. ///
  570. /// These are attributes like the following:
  571. /// int f ATTR;
  572. /// int (f ATTR)();
  573. /// but not necessarily this:
  574. /// int f() ATTR;
  575. static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
  576. QualType &declSpecType) {
  577. // Collect all the type attributes from the declarator itself.
  578. assert(!state.getDeclarator().getAttributes().empty() &&
  579. "declarator has no attrs!");
  580. // The called functions in this loop actually remove things from the current
  581. // list, so iterating over the existing list isn't possible. Instead, make a
  582. // non-owning copy and iterate over that.
  583. ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
  584. for (ParsedAttr &attr : AttrsCopy) {
  585. // Do not distribute C++11 attributes. They have strict rules for what
  586. // they appertain to.
  587. if (attr.isCXX11Attribute())
  588. continue;
  589. switch (attr.getKind()) {
  590. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  591. distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
  592. break;
  593. FUNCTION_TYPE_ATTRS_CASELIST:
  594. distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
  595. break;
  596. MS_TYPE_ATTRS_CASELIST:
  597. // Microsoft type attributes cannot go after the declarator-id.
  598. continue;
  599. NULLABILITY_TYPE_ATTRS_CASELIST:
  600. // Nullability specifiers cannot go after the declarator-id.
  601. // Objective-C __kindof does not get distributed.
  602. case ParsedAttr::AT_ObjCKindOf:
  603. continue;
  604. default:
  605. break;
  606. }
  607. }
  608. }
  609. /// Add a synthetic '()' to a block-literal declarator if it is
  610. /// required, given the return type.
  611. static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
  612. QualType declSpecType) {
  613. Declarator &declarator = state.getDeclarator();
  614. // First, check whether the declarator would produce a function,
  615. // i.e. whether the innermost semantic chunk is a function.
  616. if (declarator.isFunctionDeclarator()) {
  617. // If so, make that declarator a prototyped declarator.
  618. declarator.getFunctionTypeInfo().hasPrototype = true;
  619. return;
  620. }
  621. // If there are any type objects, the type as written won't name a
  622. // function, regardless of the decl spec type. This is because a
  623. // block signature declarator is always an abstract-declarator, and
  624. // abstract-declarators can't just be parentheses chunks. Therefore
  625. // we need to build a function chunk unless there are no type
  626. // objects and the decl spec type is a function.
  627. if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
  628. return;
  629. // Note that there *are* cases with invalid declarators where
  630. // declarators consist solely of parentheses. In general, these
  631. // occur only in failed efforts to make function declarators, so
  632. // faking up the function chunk is still the right thing to do.
  633. // Otherwise, we need to fake up a function declarator.
  634. SourceLocation loc = declarator.getBeginLoc();
  635. // ...and *prepend* it to the declarator.
  636. SourceLocation NoLoc;
  637. declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
  638. /*HasProto=*/true,
  639. /*IsAmbiguous=*/false,
  640. /*LParenLoc=*/NoLoc,
  641. /*ArgInfo=*/nullptr,
  642. /*NumParams=*/0,
  643. /*EllipsisLoc=*/NoLoc,
  644. /*RParenLoc=*/NoLoc,
  645. /*RefQualifierIsLvalueRef=*/true,
  646. /*RefQualifierLoc=*/NoLoc,
  647. /*MutableLoc=*/NoLoc, EST_None,
  648. /*ESpecRange=*/SourceRange(),
  649. /*Exceptions=*/nullptr,
  650. /*ExceptionRanges=*/nullptr,
  651. /*NumExceptions=*/0,
  652. /*NoexceptExpr=*/nullptr,
  653. /*ExceptionSpecTokens=*/nullptr,
  654. /*DeclsInPrototype=*/None, loc, loc, declarator));
  655. // For consistency, make sure the state still has us as processing
  656. // the decl spec.
  657. assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
  658. state.setCurrentChunkIndex(declarator.getNumTypeObjects());
  659. }
  660. static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
  661. unsigned &TypeQuals,
  662. QualType TypeSoFar,
  663. unsigned RemoveTQs,
  664. unsigned DiagID) {
  665. // If this occurs outside a template instantiation, warn the user about
  666. // it; they probably didn't mean to specify a redundant qualifier.
  667. typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
  668. for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
  669. QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
  670. QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
  671. QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
  672. if (!(RemoveTQs & Qual.first))
  673. continue;
  674. if (!S.inTemplateInstantiation()) {
  675. if (TypeQuals & Qual.first)
  676. S.Diag(Qual.second, DiagID)
  677. << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
  678. << FixItHint::CreateRemoval(Qual.second);
  679. }
  680. TypeQuals &= ~Qual.first;
  681. }
  682. }
  683. /// Return true if this is omitted block return type. Also check type
  684. /// attributes and type qualifiers when returning true.
  685. static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
  686. QualType Result) {
  687. if (!isOmittedBlockReturnType(declarator))
  688. return false;
  689. // Warn if we see type attributes for omitted return type on a block literal.
  690. SmallVector<ParsedAttr *, 2> ToBeRemoved;
  691. for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
  692. if (AL.isInvalid() || !AL.isTypeAttr())
  693. continue;
  694. S.Diag(AL.getLoc(),
  695. diag::warn_block_literal_attributes_on_omitted_return_type)
  696. << AL;
  697. ToBeRemoved.push_back(&AL);
  698. }
  699. // Remove bad attributes from the list.
  700. for (ParsedAttr *AL : ToBeRemoved)
  701. declarator.getMutableDeclSpec().getAttributes().remove(AL);
  702. // Warn if we see type qualifiers for omitted return type on a block literal.
  703. const DeclSpec &DS = declarator.getDeclSpec();
  704. unsigned TypeQuals = DS.getTypeQualifiers();
  705. diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
  706. diag::warn_block_literal_qualifiers_on_omitted_return_type);
  707. declarator.getMutableDeclSpec().ClearTypeQualifiers();
  708. return true;
  709. }
  710. /// Apply Objective-C type arguments to the given type.
  711. static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
  712. ArrayRef<TypeSourceInfo *> typeArgs,
  713. SourceRange typeArgsRange,
  714. bool failOnError = false) {
  715. // We can only apply type arguments to an Objective-C class type.
  716. const auto *objcObjectType = type->getAs<ObjCObjectType>();
  717. if (!objcObjectType || !objcObjectType->getInterface()) {
  718. S.Diag(loc, diag::err_objc_type_args_non_class)
  719. << type
  720. << typeArgsRange;
  721. if (failOnError)
  722. return QualType();
  723. return type;
  724. }
  725. // The class type must be parameterized.
  726. ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
  727. ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
  728. if (!typeParams) {
  729. S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
  730. << objcClass->getDeclName()
  731. << FixItHint::CreateRemoval(typeArgsRange);
  732. if (failOnError)
  733. return QualType();
  734. return type;
  735. }
  736. // The type must not already be specialized.
  737. if (objcObjectType->isSpecialized()) {
  738. S.Diag(loc, diag::err_objc_type_args_specialized_class)
  739. << type
  740. << FixItHint::CreateRemoval(typeArgsRange);
  741. if (failOnError)
  742. return QualType();
  743. return type;
  744. }
  745. // Check the type arguments.
  746. SmallVector<QualType, 4> finalTypeArgs;
  747. unsigned numTypeParams = typeParams->size();
  748. bool anyPackExpansions = false;
  749. for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
  750. TypeSourceInfo *typeArgInfo = typeArgs[i];
  751. QualType typeArg = typeArgInfo->getType();
  752. // Type arguments cannot have explicit qualifiers or nullability.
  753. // We ignore indirect sources of these, e.g. behind typedefs or
  754. // template arguments.
  755. if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
  756. bool diagnosed = false;
  757. SourceRange rangeToRemove;
  758. if (auto attr = qual.getAs<AttributedTypeLoc>()) {
  759. rangeToRemove = attr.getLocalSourceRange();
  760. if (attr.getTypePtr()->getImmediateNullability()) {
  761. typeArg = attr.getTypePtr()->getModifiedType();
  762. S.Diag(attr.getBeginLoc(),
  763. diag::err_objc_type_arg_explicit_nullability)
  764. << typeArg << FixItHint::CreateRemoval(rangeToRemove);
  765. diagnosed = true;
  766. }
  767. }
  768. if (!diagnosed) {
  769. S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
  770. << typeArg << typeArg.getQualifiers().getAsString()
  771. << FixItHint::CreateRemoval(rangeToRemove);
  772. }
  773. }
  774. // Remove qualifiers even if they're non-local.
  775. typeArg = typeArg.getUnqualifiedType();
  776. finalTypeArgs.push_back(typeArg);
  777. if (typeArg->getAs<PackExpansionType>())
  778. anyPackExpansions = true;
  779. // Find the corresponding type parameter, if there is one.
  780. ObjCTypeParamDecl *typeParam = nullptr;
  781. if (!anyPackExpansions) {
  782. if (i < numTypeParams) {
  783. typeParam = typeParams->begin()[i];
  784. } else {
  785. // Too many arguments.
  786. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  787. << false
  788. << objcClass->getDeclName()
  789. << (unsigned)typeArgs.size()
  790. << numTypeParams;
  791. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  792. << objcClass;
  793. if (failOnError)
  794. return QualType();
  795. return type;
  796. }
  797. }
  798. // Objective-C object pointer types must be substitutable for the bounds.
  799. if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
  800. // If we don't have a type parameter to match against, assume
  801. // everything is fine. There was a prior pack expansion that
  802. // means we won't be able to match anything.
  803. if (!typeParam) {
  804. assert(anyPackExpansions && "Too many arguments?");
  805. continue;
  806. }
  807. // Retrieve the bound.
  808. QualType bound = typeParam->getUnderlyingType();
  809. const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
  810. // Determine whether the type argument is substitutable for the bound.
  811. if (typeArgObjC->isObjCIdType()) {
  812. // When the type argument is 'id', the only acceptable type
  813. // parameter bound is 'id'.
  814. if (boundObjC->isObjCIdType())
  815. continue;
  816. } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
  817. // Otherwise, we follow the assignability rules.
  818. continue;
  819. }
  820. // Diagnose the mismatch.
  821. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  822. diag::err_objc_type_arg_does_not_match_bound)
  823. << typeArg << bound << typeParam->getDeclName();
  824. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  825. << typeParam->getDeclName();
  826. if (failOnError)
  827. return QualType();
  828. return type;
  829. }
  830. // Block pointer types are permitted for unqualified 'id' bounds.
  831. if (typeArg->isBlockPointerType()) {
  832. // If we don't have a type parameter to match against, assume
  833. // everything is fine. There was a prior pack expansion that
  834. // means we won't be able to match anything.
  835. if (!typeParam) {
  836. assert(anyPackExpansions && "Too many arguments?");
  837. continue;
  838. }
  839. // Retrieve the bound.
  840. QualType bound = typeParam->getUnderlyingType();
  841. if (bound->isBlockCompatibleObjCPointerType(S.Context))
  842. continue;
  843. // Diagnose the mismatch.
  844. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  845. diag::err_objc_type_arg_does_not_match_bound)
  846. << typeArg << bound << typeParam->getDeclName();
  847. S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
  848. << typeParam->getDeclName();
  849. if (failOnError)
  850. return QualType();
  851. return type;
  852. }
  853. // Dependent types will be checked at instantiation time.
  854. if (typeArg->isDependentType()) {
  855. continue;
  856. }
  857. // Diagnose non-id-compatible type arguments.
  858. S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
  859. diag::err_objc_type_arg_not_id_compatible)
  860. << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
  861. if (failOnError)
  862. return QualType();
  863. return type;
  864. }
  865. // Make sure we didn't have the wrong number of arguments.
  866. if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
  867. S.Diag(loc, diag::err_objc_type_args_wrong_arity)
  868. << (typeArgs.size() < typeParams->size())
  869. << objcClass->getDeclName()
  870. << (unsigned)finalTypeArgs.size()
  871. << (unsigned)numTypeParams;
  872. S.Diag(objcClass->getLocation(), diag::note_previous_decl)
  873. << objcClass;
  874. if (failOnError)
  875. return QualType();
  876. return type;
  877. }
  878. // Success. Form the specialized type.
  879. return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
  880. }
  881. QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  882. SourceLocation ProtocolLAngleLoc,
  883. ArrayRef<ObjCProtocolDecl *> Protocols,
  884. ArrayRef<SourceLocation> ProtocolLocs,
  885. SourceLocation ProtocolRAngleLoc,
  886. bool FailOnError) {
  887. QualType Result = QualType(Decl->getTypeForDecl(), 0);
  888. if (!Protocols.empty()) {
  889. bool HasError;
  890. Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
  891. HasError);
  892. if (HasError) {
  893. Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
  894. << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
  895. if (FailOnError) Result = QualType();
  896. }
  897. if (FailOnError && Result.isNull())
  898. return QualType();
  899. }
  900. return Result;
  901. }
  902. QualType Sema::BuildObjCObjectType(QualType BaseType,
  903. SourceLocation Loc,
  904. SourceLocation TypeArgsLAngleLoc,
  905. ArrayRef<TypeSourceInfo *> TypeArgs,
  906. SourceLocation TypeArgsRAngleLoc,
  907. SourceLocation ProtocolLAngleLoc,
  908. ArrayRef<ObjCProtocolDecl *> Protocols,
  909. ArrayRef<SourceLocation> ProtocolLocs,
  910. SourceLocation ProtocolRAngleLoc,
  911. bool FailOnError) {
  912. QualType Result = BaseType;
  913. if (!TypeArgs.empty()) {
  914. Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
  915. SourceRange(TypeArgsLAngleLoc,
  916. TypeArgsRAngleLoc),
  917. FailOnError);
  918. if (FailOnError && Result.isNull())
  919. return QualType();
  920. }
  921. if (!Protocols.empty()) {
  922. bool HasError;
  923. Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
  924. HasError);
  925. if (HasError) {
  926. Diag(Loc, diag::err_invalid_protocol_qualifiers)
  927. << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
  928. if (FailOnError) Result = QualType();
  929. }
  930. if (FailOnError && Result.isNull())
  931. return QualType();
  932. }
  933. return Result;
  934. }
  935. TypeResult Sema::actOnObjCProtocolQualifierType(
  936. SourceLocation lAngleLoc,
  937. ArrayRef<Decl *> protocols,
  938. ArrayRef<SourceLocation> protocolLocs,
  939. SourceLocation rAngleLoc) {
  940. // Form id<protocol-list>.
  941. QualType Result = Context.getObjCObjectType(
  942. Context.ObjCBuiltinIdTy, { },
  943. llvm::makeArrayRef(
  944. (ObjCProtocolDecl * const *)protocols.data(),
  945. protocols.size()),
  946. false);
  947. Result = Context.getObjCObjectPointerType(Result);
  948. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  949. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  950. auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
  951. ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
  952. auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
  953. .castAs<ObjCObjectTypeLoc>();
  954. ObjCObjectTL.setHasBaseTypeAsWritten(false);
  955. ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
  956. // No type arguments.
  957. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  958. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  959. // Fill in protocol qualifiers.
  960. ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
  961. ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
  962. for (unsigned i = 0, n = protocols.size(); i != n; ++i)
  963. ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
  964. // We're done. Return the completed type to the parser.
  965. return CreateParsedType(Result, ResultTInfo);
  966. }
  967. TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
  968. Scope *S,
  969. SourceLocation Loc,
  970. ParsedType BaseType,
  971. SourceLocation TypeArgsLAngleLoc,
  972. ArrayRef<ParsedType> TypeArgs,
  973. SourceLocation TypeArgsRAngleLoc,
  974. SourceLocation ProtocolLAngleLoc,
  975. ArrayRef<Decl *> Protocols,
  976. ArrayRef<SourceLocation> ProtocolLocs,
  977. SourceLocation ProtocolRAngleLoc) {
  978. TypeSourceInfo *BaseTypeInfo = nullptr;
  979. QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
  980. if (T.isNull())
  981. return true;
  982. // Handle missing type-source info.
  983. if (!BaseTypeInfo)
  984. BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  985. // Extract type arguments.
  986. SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
  987. for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
  988. TypeSourceInfo *TypeArgInfo = nullptr;
  989. QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
  990. if (TypeArg.isNull()) {
  991. ActualTypeArgInfos.clear();
  992. break;
  993. }
  994. assert(TypeArgInfo && "No type source info?");
  995. ActualTypeArgInfos.push_back(TypeArgInfo);
  996. }
  997. // Build the object type.
  998. QualType Result = BuildObjCObjectType(
  999. T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
  1000. TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
  1001. ProtocolLAngleLoc,
  1002. llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
  1003. Protocols.size()),
  1004. ProtocolLocs, ProtocolRAngleLoc,
  1005. /*FailOnError=*/false);
  1006. if (Result == T)
  1007. return BaseType;
  1008. // Create source information for this type.
  1009. TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
  1010. TypeLoc ResultTL = ResultTInfo->getTypeLoc();
  1011. // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
  1012. // object pointer type. Fill in source information for it.
  1013. if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
  1014. // The '*' is implicit.
  1015. ObjCObjectPointerTL.setStarLoc(SourceLocation());
  1016. ResultTL = ObjCObjectPointerTL.getPointeeLoc();
  1017. }
  1018. if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
  1019. // Protocol qualifier information.
  1020. if (OTPTL.getNumProtocols() > 0) {
  1021. assert(OTPTL.getNumProtocols() == Protocols.size());
  1022. OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
  1023. OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
  1024. for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
  1025. OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
  1026. }
  1027. // We're done. Return the completed type to the parser.
  1028. return CreateParsedType(Result, ResultTInfo);
  1029. }
  1030. auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
  1031. // Type argument information.
  1032. if (ObjCObjectTL.getNumTypeArgs() > 0) {
  1033. assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
  1034. ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
  1035. ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
  1036. for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
  1037. ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
  1038. } else {
  1039. ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
  1040. ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
  1041. }
  1042. // Protocol qualifier information.
  1043. if (ObjCObjectTL.getNumProtocols() > 0) {
  1044. assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
  1045. ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
  1046. ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
  1047. for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
  1048. ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
  1049. } else {
  1050. ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
  1051. ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
  1052. }
  1053. // Base type.
  1054. ObjCObjectTL.setHasBaseTypeAsWritten(true);
  1055. if (ObjCObjectTL.getType() == T)
  1056. ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
  1057. else
  1058. ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
  1059. // We're done. Return the completed type to the parser.
  1060. return CreateParsedType(Result, ResultTInfo);
  1061. }
  1062. static OpenCLAccessAttr::Spelling
  1063. getImageAccess(const ParsedAttributesView &Attrs) {
  1064. for (const ParsedAttr &AL : Attrs)
  1065. if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
  1066. return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
  1067. return OpenCLAccessAttr::Keyword_read_only;
  1068. }
  1069. /// Convert the specified declspec to the appropriate type
  1070. /// object.
  1071. /// \param state Specifies the declarator containing the declaration specifier
  1072. /// to be converted, along with other associated processing state.
  1073. /// \returns The type described by the declaration specifiers. This function
  1074. /// never returns null.
  1075. static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
  1076. // FIXME: Should move the logic from DeclSpec::Finish to here for validity
  1077. // checking.
  1078. Sema &S = state.getSema();
  1079. Declarator &declarator = state.getDeclarator();
  1080. DeclSpec &DS = declarator.getMutableDeclSpec();
  1081. SourceLocation DeclLoc = declarator.getIdentifierLoc();
  1082. if (DeclLoc.isInvalid())
  1083. DeclLoc = DS.getBeginLoc();
  1084. ASTContext &Context = S.Context;
  1085. QualType Result;
  1086. switch (DS.getTypeSpecType()) {
  1087. case DeclSpec::TST_void:
  1088. Result = Context.VoidTy;
  1089. break;
  1090. case DeclSpec::TST_char:
  1091. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1092. Result = Context.CharTy;
  1093. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
  1094. Result = Context.SignedCharTy;
  1095. else {
  1096. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1097. "Unknown TSS value");
  1098. Result = Context.UnsignedCharTy;
  1099. }
  1100. break;
  1101. case DeclSpec::TST_wchar:
  1102. if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
  1103. Result = Context.WCharTy;
  1104. else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
  1105. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
  1106. << DS.getSpecifierName(DS.getTypeSpecType(),
  1107. Context.getPrintingPolicy());
  1108. Result = Context.getSignedWCharType();
  1109. } else {
  1110. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
  1111. "Unknown TSS value");
  1112. S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
  1113. << DS.getSpecifierName(DS.getTypeSpecType(),
  1114. Context.getPrintingPolicy());
  1115. Result = Context.getUnsignedWCharType();
  1116. }
  1117. break;
  1118. case DeclSpec::TST_char8:
  1119. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1120. "Unknown TSS value");
  1121. Result = Context.Char8Ty;
  1122. break;
  1123. case DeclSpec::TST_char16:
  1124. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1125. "Unknown TSS value");
  1126. Result = Context.Char16Ty;
  1127. break;
  1128. case DeclSpec::TST_char32:
  1129. assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
  1130. "Unknown TSS value");
  1131. Result = Context.Char32Ty;
  1132. break;
  1133. case DeclSpec::TST_unspecified:
  1134. // If this is a missing declspec in a block literal return context, then it
  1135. // is inferred from the return statements inside the block.
  1136. // The declspec is always missing in a lambda expr context; it is either
  1137. // specified with a trailing return type or inferred.
  1138. if (S.getLangOpts().CPlusPlus14 &&
  1139. declarator.getContext() == DeclaratorContext::LambdaExprContext) {
  1140. // In C++1y, a lambda's implicit return type is 'auto'.
  1141. Result = Context.getAutoDeductType();
  1142. break;
  1143. } else if (declarator.getContext() ==
  1144. DeclaratorContext::LambdaExprContext ||
  1145. checkOmittedBlockReturnType(S, declarator,
  1146. Context.DependentTy)) {
  1147. Result = Context.DependentTy;
  1148. break;
  1149. }
  1150. // Unspecified typespec defaults to int in C90. However, the C90 grammar
  1151. // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
  1152. // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
  1153. // Note that the one exception to this is function definitions, which are
  1154. // allowed to be completely missing a declspec. This is handled in the
  1155. // parser already though by it pretending to have seen an 'int' in this
  1156. // case.
  1157. if (S.getLangOpts().ImplicitInt) {
  1158. // In C89 mode, we only warn if there is a completely missing declspec
  1159. // when one is not allowed.
  1160. if (DS.isEmpty()) {
  1161. S.Diag(DeclLoc, diag::ext_missing_declspec)
  1162. << DS.getSourceRange()
  1163. << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
  1164. }
  1165. } else if (!DS.hasTypeSpecifier()) {
  1166. // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
  1167. // "At least one type specifier shall be given in the declaration
  1168. // specifiers in each declaration, and in the specifier-qualifier list in
  1169. // each struct declaration and type name."
  1170. if (S.getLangOpts().CPlusPlus && !DS.isTypeSpecPipe()) {
  1171. S.Diag(DeclLoc, diag::err_missing_type_specifier)
  1172. << DS.getSourceRange();
  1173. // When this occurs in C++ code, often something is very broken with the
  1174. // value being declared, poison it as invalid so we don't get chains of
  1175. // errors.
  1176. declarator.setInvalidType(true);
  1177. } else if ((S.getLangOpts().OpenCLVersion >= 200 ||
  1178. S.getLangOpts().OpenCLCPlusPlus) &&
  1179. DS.isTypeSpecPipe()) {
  1180. S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
  1181. << DS.getSourceRange();
  1182. declarator.setInvalidType(true);
  1183. } else {
  1184. S.Diag(DeclLoc, diag::ext_missing_type_specifier)
  1185. << DS.getSourceRange();
  1186. }
  1187. }
  1188. LLVM_FALLTHROUGH;
  1189. case DeclSpec::TST_int: {
  1190. if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
  1191. switch (DS.getTypeSpecWidth()) {
  1192. case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
  1193. case DeclSpec::TSW_short: Result = Context.ShortTy; break;
  1194. case DeclSpec::TSW_long: Result = Context.LongTy; break;
  1195. case DeclSpec::TSW_longlong:
  1196. Result = Context.LongLongTy;
  1197. // 'long long' is a C99 or C++11 feature.
  1198. if (!S.getLangOpts().C99) {
  1199. if (S.getLangOpts().CPlusPlus)
  1200. S.Diag(DS.getTypeSpecWidthLoc(),
  1201. S.getLangOpts().CPlusPlus11 ?
  1202. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1203. else
  1204. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1205. }
  1206. break;
  1207. }
  1208. } else {
  1209. switch (DS.getTypeSpecWidth()) {
  1210. case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
  1211. case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
  1212. case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
  1213. case DeclSpec::TSW_longlong:
  1214. Result = Context.UnsignedLongLongTy;
  1215. // 'long long' is a C99 or C++11 feature.
  1216. if (!S.getLangOpts().C99) {
  1217. if (S.getLangOpts().CPlusPlus)
  1218. S.Diag(DS.getTypeSpecWidthLoc(),
  1219. S.getLangOpts().CPlusPlus11 ?
  1220. diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
  1221. else
  1222. S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
  1223. }
  1224. break;
  1225. }
  1226. }
  1227. break;
  1228. }
  1229. case DeclSpec::TST_accum: {
  1230. switch (DS.getTypeSpecWidth()) {
  1231. case DeclSpec::TSW_short:
  1232. Result = Context.ShortAccumTy;
  1233. break;
  1234. case DeclSpec::TSW_unspecified:
  1235. Result = Context.AccumTy;
  1236. break;
  1237. case DeclSpec::TSW_long:
  1238. Result = Context.LongAccumTy;
  1239. break;
  1240. case DeclSpec::TSW_longlong:
  1241. llvm_unreachable("Unable to specify long long as _Accum width");
  1242. }
  1243. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1244. Result = Context.getCorrespondingUnsignedType(Result);
  1245. if (DS.isTypeSpecSat())
  1246. Result = Context.getCorrespondingSaturatedType(Result);
  1247. break;
  1248. }
  1249. case DeclSpec::TST_fract: {
  1250. switch (DS.getTypeSpecWidth()) {
  1251. case DeclSpec::TSW_short:
  1252. Result = Context.ShortFractTy;
  1253. break;
  1254. case DeclSpec::TSW_unspecified:
  1255. Result = Context.FractTy;
  1256. break;
  1257. case DeclSpec::TSW_long:
  1258. Result = Context.LongFractTy;
  1259. break;
  1260. case DeclSpec::TSW_longlong:
  1261. llvm_unreachable("Unable to specify long long as _Fract width");
  1262. }
  1263. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1264. Result = Context.getCorrespondingUnsignedType(Result);
  1265. if (DS.isTypeSpecSat())
  1266. Result = Context.getCorrespondingSaturatedType(Result);
  1267. break;
  1268. }
  1269. case DeclSpec::TST_int128:
  1270. if (!S.Context.getTargetInfo().hasInt128Type() &&
  1271. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1272. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1273. << "__int128";
  1274. if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
  1275. Result = Context.UnsignedInt128Ty;
  1276. else
  1277. Result = Context.Int128Ty;
  1278. break;
  1279. case DeclSpec::TST_float16:
  1280. // CUDA host and device may have different _Float16 support, therefore
  1281. // do not diagnose _Float16 usage to avoid false alarm.
  1282. // ToDo: more precise diagnostics for CUDA.
  1283. if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
  1284. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1285. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1286. << "_Float16";
  1287. Result = Context.Float16Ty;
  1288. break;
  1289. case DeclSpec::TST_half: Result = Context.HalfTy; break;
  1290. case DeclSpec::TST_float: Result = Context.FloatTy; break;
  1291. case DeclSpec::TST_double:
  1292. if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
  1293. Result = Context.LongDoubleTy;
  1294. else
  1295. Result = Context.DoubleTy;
  1296. break;
  1297. case DeclSpec::TST_float128:
  1298. if (!S.Context.getTargetInfo().hasFloat128Type() &&
  1299. !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
  1300. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
  1301. << "__float128";
  1302. Result = Context.Float128Ty;
  1303. break;
  1304. case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
  1305. break;
  1306. case DeclSpec::TST_decimal32: // _Decimal32
  1307. case DeclSpec::TST_decimal64: // _Decimal64
  1308. case DeclSpec::TST_decimal128: // _Decimal128
  1309. S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
  1310. Result = Context.IntTy;
  1311. declarator.setInvalidType(true);
  1312. break;
  1313. case DeclSpec::TST_class:
  1314. case DeclSpec::TST_enum:
  1315. case DeclSpec::TST_union:
  1316. case DeclSpec::TST_struct:
  1317. case DeclSpec::TST_interface: {
  1318. TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
  1319. if (!D) {
  1320. // This can happen in C++ with ambiguous lookups.
  1321. Result = Context.IntTy;
  1322. declarator.setInvalidType(true);
  1323. break;
  1324. }
  1325. // If the type is deprecated or unavailable, diagnose it.
  1326. S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
  1327. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1328. DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
  1329. // TypeQuals handled by caller.
  1330. Result = Context.getTypeDeclType(D);
  1331. // In both C and C++, make an ElaboratedType.
  1332. ElaboratedTypeKeyword Keyword
  1333. = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
  1334. Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
  1335. DS.isTypeSpecOwned() ? D : nullptr);
  1336. break;
  1337. }
  1338. case DeclSpec::TST_typename: {
  1339. assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
  1340. DS.getTypeSpecSign() == 0 &&
  1341. "Can't handle qualifiers on typedef names yet!");
  1342. Result = S.GetTypeFromParser(DS.getRepAsType());
  1343. if (Result.isNull()) {
  1344. declarator.setInvalidType(true);
  1345. }
  1346. // TypeQuals handled by caller.
  1347. break;
  1348. }
  1349. case DeclSpec::TST_typeofType:
  1350. // FIXME: Preserve type source info.
  1351. Result = S.GetTypeFromParser(DS.getRepAsType());
  1352. assert(!Result.isNull() && "Didn't get a type for typeof?");
  1353. if (!Result->isDependentType())
  1354. if (const TagType *TT = Result->getAs<TagType>())
  1355. S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
  1356. // TypeQuals handled by caller.
  1357. Result = Context.getTypeOfType(Result);
  1358. break;
  1359. case DeclSpec::TST_typeofExpr: {
  1360. Expr *E = DS.getRepAsExpr();
  1361. assert(E && "Didn't get an expression for typeof?");
  1362. // TypeQuals handled by caller.
  1363. Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
  1364. if (Result.isNull()) {
  1365. Result = Context.IntTy;
  1366. declarator.setInvalidType(true);
  1367. }
  1368. break;
  1369. }
  1370. case DeclSpec::TST_decltype: {
  1371. Expr *E = DS.getRepAsExpr();
  1372. assert(E && "Didn't get an expression for decltype?");
  1373. // TypeQuals handled by caller.
  1374. Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
  1375. if (Result.isNull()) {
  1376. Result = Context.IntTy;
  1377. declarator.setInvalidType(true);
  1378. }
  1379. break;
  1380. }
  1381. case DeclSpec::TST_underlyingType:
  1382. Result = S.GetTypeFromParser(DS.getRepAsType());
  1383. assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
  1384. Result = S.BuildUnaryTransformType(Result,
  1385. UnaryTransformType::EnumUnderlyingType,
  1386. DS.getTypeSpecTypeLoc());
  1387. if (Result.isNull()) {
  1388. Result = Context.IntTy;
  1389. declarator.setInvalidType(true);
  1390. }
  1391. break;
  1392. case DeclSpec::TST_auto:
  1393. Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
  1394. break;
  1395. case DeclSpec::TST_auto_type:
  1396. Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
  1397. break;
  1398. case DeclSpec::TST_decltype_auto:
  1399. Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
  1400. /*IsDependent*/ false);
  1401. break;
  1402. case DeclSpec::TST_unknown_anytype:
  1403. Result = Context.UnknownAnyTy;
  1404. break;
  1405. case DeclSpec::TST_atomic:
  1406. Result = S.GetTypeFromParser(DS.getRepAsType());
  1407. assert(!Result.isNull() && "Didn't get a type for _Atomic?");
  1408. Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
  1409. if (Result.isNull()) {
  1410. Result = Context.IntTy;
  1411. declarator.setInvalidType(true);
  1412. }
  1413. break;
  1414. #define GENERIC_IMAGE_TYPE(ImgType, Id) \
  1415. case DeclSpec::TST_##ImgType##_t: \
  1416. switch (getImageAccess(DS.getAttributes())) { \
  1417. case OpenCLAccessAttr::Keyword_write_only: \
  1418. Result = Context.Id##WOTy; \
  1419. break; \
  1420. case OpenCLAccessAttr::Keyword_read_write: \
  1421. Result = Context.Id##RWTy; \
  1422. break; \
  1423. case OpenCLAccessAttr::Keyword_read_only: \
  1424. Result = Context.Id##ROTy; \
  1425. break; \
  1426. case OpenCLAccessAttr::SpellingNotCalculated: \
  1427. llvm_unreachable("Spelling not yet calculated"); \
  1428. } \
  1429. break;
  1430. #include "clang/Basic/OpenCLImageTypes.def"
  1431. case DeclSpec::TST_error:
  1432. Result = Context.IntTy;
  1433. declarator.setInvalidType(true);
  1434. break;
  1435. }
  1436. if (S.getLangOpts().OpenCL &&
  1437. S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
  1438. declarator.setInvalidType(true);
  1439. bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
  1440. DS.getTypeSpecType() == DeclSpec::TST_fract;
  1441. // Only fixed point types can be saturated
  1442. if (DS.isTypeSpecSat() && !IsFixedPointType)
  1443. S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
  1444. << DS.getSpecifierName(DS.getTypeSpecType(),
  1445. Context.getPrintingPolicy());
  1446. // Handle complex types.
  1447. if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
  1448. if (S.getLangOpts().Freestanding)
  1449. S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
  1450. Result = Context.getComplexType(Result);
  1451. } else if (DS.isTypeAltiVecVector()) {
  1452. unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
  1453. assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
  1454. VectorType::VectorKind VecKind = VectorType::AltiVecVector;
  1455. if (DS.isTypeAltiVecPixel())
  1456. VecKind = VectorType::AltiVecPixel;
  1457. else if (DS.isTypeAltiVecBool())
  1458. VecKind = VectorType::AltiVecBool;
  1459. Result = Context.getVectorType(Result, 128/typeSize, VecKind);
  1460. }
  1461. // FIXME: Imaginary.
  1462. if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
  1463. S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
  1464. // Before we process any type attributes, synthesize a block literal
  1465. // function declarator if necessary.
  1466. if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
  1467. maybeSynthesizeBlockSignature(state, Result);
  1468. // Apply any type attributes from the decl spec. This may cause the
  1469. // list of type attributes to be temporarily saved while the type
  1470. // attributes are pushed around.
  1471. // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
  1472. if (!DS.isTypeSpecPipe())
  1473. processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
  1474. // Apply const/volatile/restrict qualifiers to T.
  1475. if (unsigned TypeQuals = DS.getTypeQualifiers()) {
  1476. // Warn about CV qualifiers on function types.
  1477. // C99 6.7.3p8:
  1478. // If the specification of a function type includes any type qualifiers,
  1479. // the behavior is undefined.
  1480. // C++11 [dcl.fct]p7:
  1481. // The effect of a cv-qualifier-seq in a function declarator is not the
  1482. // same as adding cv-qualification on top of the function type. In the
  1483. // latter case, the cv-qualifiers are ignored.
  1484. if (TypeQuals && Result->isFunctionType()) {
  1485. diagnoseAndRemoveTypeQualifiers(
  1486. S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
  1487. S.getLangOpts().CPlusPlus
  1488. ? diag::warn_typecheck_function_qualifiers_ignored
  1489. : diag::warn_typecheck_function_qualifiers_unspecified);
  1490. // No diagnostic for 'restrict' or '_Atomic' applied to a
  1491. // function type; we'll diagnose those later, in BuildQualifiedType.
  1492. }
  1493. // C++11 [dcl.ref]p1:
  1494. // Cv-qualified references are ill-formed except when the
  1495. // cv-qualifiers are introduced through the use of a typedef-name
  1496. // or decltype-specifier, in which case the cv-qualifiers are ignored.
  1497. //
  1498. // There don't appear to be any other contexts in which a cv-qualified
  1499. // reference type could be formed, so the 'ill-formed' clause here appears
  1500. // to never happen.
  1501. if (TypeQuals && Result->isReferenceType()) {
  1502. diagnoseAndRemoveTypeQualifiers(
  1503. S, DS, TypeQuals, Result,
  1504. DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
  1505. diag::warn_typecheck_reference_qualifiers);
  1506. }
  1507. // C90 6.5.3 constraints: "The same type qualifier shall not appear more
  1508. // than once in the same specifier-list or qualifier-list, either directly
  1509. // or via one or more typedefs."
  1510. if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
  1511. && TypeQuals & Result.getCVRQualifiers()) {
  1512. if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
  1513. S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
  1514. << "const";
  1515. }
  1516. if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
  1517. S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
  1518. << "volatile";
  1519. }
  1520. // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
  1521. // produce a warning in this case.
  1522. }
  1523. QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
  1524. // If adding qualifiers fails, just use the unqualified type.
  1525. if (Qualified.isNull())
  1526. declarator.setInvalidType(true);
  1527. else
  1528. Result = Qualified;
  1529. }
  1530. assert(!Result.isNull() && "This function should not return a null type");
  1531. return Result;
  1532. }
  1533. static std::string getPrintableNameForEntity(DeclarationName Entity) {
  1534. if (Entity)
  1535. return Entity.getAsString();
  1536. return "type name";
  1537. }
  1538. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1539. Qualifiers Qs, const DeclSpec *DS) {
  1540. if (T.isNull())
  1541. return QualType();
  1542. // Ignore any attempt to form a cv-qualified reference.
  1543. if (T->isReferenceType()) {
  1544. Qs.removeConst();
  1545. Qs.removeVolatile();
  1546. }
  1547. // Enforce C99 6.7.3p2: "Types other than pointer types derived from
  1548. // object or incomplete types shall not be restrict-qualified."
  1549. if (Qs.hasRestrict()) {
  1550. unsigned DiagID = 0;
  1551. QualType ProblemTy;
  1552. if (T->isAnyPointerType() || T->isReferenceType() ||
  1553. T->isMemberPointerType()) {
  1554. QualType EltTy;
  1555. if (T->isObjCObjectPointerType())
  1556. EltTy = T;
  1557. else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
  1558. EltTy = PTy->getPointeeType();
  1559. else
  1560. EltTy = T->getPointeeType();
  1561. // If we have a pointer or reference, the pointee must have an object
  1562. // incomplete type.
  1563. if (!EltTy->isIncompleteOrObjectType()) {
  1564. DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
  1565. ProblemTy = EltTy;
  1566. }
  1567. } else if (!T->isDependentType()) {
  1568. DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
  1569. ProblemTy = T;
  1570. }
  1571. if (DiagID) {
  1572. Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
  1573. Qs.removeRestrict();
  1574. }
  1575. }
  1576. return Context.getQualifiedType(T, Qs);
  1577. }
  1578. QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
  1579. unsigned CVRAU, const DeclSpec *DS) {
  1580. if (T.isNull())
  1581. return QualType();
  1582. // Ignore any attempt to form a cv-qualified reference.
  1583. if (T->isReferenceType())
  1584. CVRAU &=
  1585. ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
  1586. // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
  1587. // TQ_unaligned;
  1588. unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
  1589. // C11 6.7.3/5:
  1590. // If the same qualifier appears more than once in the same
  1591. // specifier-qualifier-list, either directly or via one or more typedefs,
  1592. // the behavior is the same as if it appeared only once.
  1593. //
  1594. // It's not specified what happens when the _Atomic qualifier is applied to
  1595. // a type specified with the _Atomic specifier, but we assume that this
  1596. // should be treated as if the _Atomic qualifier appeared multiple times.
  1597. if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
  1598. // C11 6.7.3/5:
  1599. // If other qualifiers appear along with the _Atomic qualifier in a
  1600. // specifier-qualifier-list, the resulting type is the so-qualified
  1601. // atomic type.
  1602. //
  1603. // Don't need to worry about array types here, since _Atomic can't be
  1604. // applied to such types.
  1605. SplitQualType Split = T.getSplitUnqualifiedType();
  1606. T = BuildAtomicType(QualType(Split.Ty, 0),
  1607. DS ? DS->getAtomicSpecLoc() : Loc);
  1608. if (T.isNull())
  1609. return T;
  1610. Split.Quals.addCVRQualifiers(CVR);
  1611. return BuildQualifiedType(T, Loc, Split.Quals);
  1612. }
  1613. Qualifiers Q = Qualifiers::fromCVRMask(CVR);
  1614. Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
  1615. return BuildQualifiedType(T, Loc, Q, DS);
  1616. }
  1617. /// Build a paren type including \p T.
  1618. QualType Sema::BuildParenType(QualType T) {
  1619. return Context.getParenType(T);
  1620. }
  1621. /// Given that we're building a pointer or reference to the given
  1622. static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
  1623. SourceLocation loc,
  1624. bool isReference) {
  1625. // Bail out if retention is unrequired or already specified.
  1626. if (!type->isObjCLifetimeType() ||
  1627. type.getObjCLifetime() != Qualifiers::OCL_None)
  1628. return type;
  1629. Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
  1630. // If the object type is const-qualified, we can safely use
  1631. // __unsafe_unretained. This is safe (because there are no read
  1632. // barriers), and it'll be safe to coerce anything but __weak* to
  1633. // the resulting type.
  1634. if (type.isConstQualified()) {
  1635. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1636. // Otherwise, check whether the static type does not require
  1637. // retaining. This currently only triggers for Class (possibly
  1638. // protocol-qualifed, and arrays thereof).
  1639. } else if (type->isObjCARCImplicitlyUnretainedType()) {
  1640. implicitLifetime = Qualifiers::OCL_ExplicitNone;
  1641. // If we are in an unevaluated context, like sizeof, skip adding a
  1642. // qualification.
  1643. } else if (S.isUnevaluatedContext()) {
  1644. return type;
  1645. // If that failed, give an error and recover using __strong. __strong
  1646. // is the option most likely to prevent spurious second-order diagnostics,
  1647. // like when binding a reference to a field.
  1648. } else {
  1649. // These types can show up in private ivars in system headers, so
  1650. // we need this to not be an error in those cases. Instead we
  1651. // want to delay.
  1652. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  1653. S.DelayedDiagnostics.add(
  1654. sema::DelayedDiagnostic::makeForbiddenType(loc,
  1655. diag::err_arc_indirect_no_ownership, type, isReference));
  1656. } else {
  1657. S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
  1658. }
  1659. implicitLifetime = Qualifiers::OCL_Strong;
  1660. }
  1661. assert(implicitLifetime && "didn't infer any lifetime!");
  1662. Qualifiers qs;
  1663. qs.addObjCLifetime(implicitLifetime);
  1664. return S.Context.getQualifiedType(type, qs);
  1665. }
  1666. static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
  1667. std::string Quals = FnTy->getMethodQuals().getAsString();
  1668. switch (FnTy->getRefQualifier()) {
  1669. case RQ_None:
  1670. break;
  1671. case RQ_LValue:
  1672. if (!Quals.empty())
  1673. Quals += ' ';
  1674. Quals += '&';
  1675. break;
  1676. case RQ_RValue:
  1677. if (!Quals.empty())
  1678. Quals += ' ';
  1679. Quals += "&&";
  1680. break;
  1681. }
  1682. return Quals;
  1683. }
  1684. namespace {
  1685. /// Kinds of declarator that cannot contain a qualified function type.
  1686. ///
  1687. /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
  1688. /// a function type with a cv-qualifier or a ref-qualifier can only appear
  1689. /// at the topmost level of a type.
  1690. ///
  1691. /// Parens and member pointers are permitted. We don't diagnose array and
  1692. /// function declarators, because they don't allow function types at all.
  1693. ///
  1694. /// The values of this enum are used in diagnostics.
  1695. enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
  1696. } // end anonymous namespace
  1697. /// Check whether the type T is a qualified function type, and if it is,
  1698. /// diagnose that it cannot be contained within the given kind of declarator.
  1699. static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
  1700. QualifiedFunctionKind QFK) {
  1701. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  1702. const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
  1703. if (!FPT ||
  1704. (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
  1705. return false;
  1706. S.Diag(Loc, diag::err_compound_qualified_function_type)
  1707. << QFK << isa<FunctionType>(T.IgnoreParens()) << T
  1708. << getFunctionQualifiersAsString(FPT);
  1709. return true;
  1710. }
  1711. bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
  1712. const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
  1713. if (!FPT ||
  1714. (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
  1715. return false;
  1716. Diag(Loc, diag::err_qualified_function_typeid)
  1717. << T << getFunctionQualifiersAsString(FPT);
  1718. return true;
  1719. }
  1720. /// Build a pointer type.
  1721. ///
  1722. /// \param T The type to which we'll be building a pointer.
  1723. ///
  1724. /// \param Loc The location of the entity whose type involves this
  1725. /// pointer type or, if there is no such entity, the location of the
  1726. /// type that will have pointer type.
  1727. ///
  1728. /// \param Entity The name of the entity that involves the pointer
  1729. /// type, if known.
  1730. ///
  1731. /// \returns A suitable pointer type, if there are no
  1732. /// errors. Otherwise, returns a NULL type.
  1733. QualType Sema::BuildPointerType(QualType T,
  1734. SourceLocation Loc, DeclarationName Entity) {
  1735. if (T->isReferenceType()) {
  1736. // C++ 8.3.2p4: There shall be no ... pointers to references ...
  1737. Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
  1738. << getPrintableNameForEntity(Entity) << T;
  1739. return QualType();
  1740. }
  1741. if (T->isFunctionType() && getLangOpts().OpenCL) {
  1742. Diag(Loc, diag::err_opencl_function_pointer);
  1743. return QualType();
  1744. }
  1745. if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
  1746. return QualType();
  1747. assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
  1748. // In ARC, it is forbidden to build pointers to unqualified pointers.
  1749. if (getLangOpts().ObjCAutoRefCount)
  1750. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
  1751. // Build the pointer type.
  1752. return Context.getPointerType(T);
  1753. }
  1754. /// Build a reference type.
  1755. ///
  1756. /// \param T The type to which we'll be building a reference.
  1757. ///
  1758. /// \param Loc The location of the entity whose type involves this
  1759. /// reference type or, if there is no such entity, the location of the
  1760. /// type that will have reference type.
  1761. ///
  1762. /// \param Entity The name of the entity that involves the reference
  1763. /// type, if known.
  1764. ///
  1765. /// \returns A suitable reference type, if there are no
  1766. /// errors. Otherwise, returns a NULL type.
  1767. QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
  1768. SourceLocation Loc,
  1769. DeclarationName Entity) {
  1770. assert(Context.getCanonicalType(T) != Context.OverloadTy &&
  1771. "Unresolved overloaded function type");
  1772. // C++0x [dcl.ref]p6:
  1773. // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
  1774. // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
  1775. // type T, an attempt to create the type "lvalue reference to cv TR" creates
  1776. // the type "lvalue reference to T", while an attempt to create the type
  1777. // "rvalue reference to cv TR" creates the type TR.
  1778. bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
  1779. // C++ [dcl.ref]p4: There shall be no references to references.
  1780. //
  1781. // According to C++ DR 106, references to references are only
  1782. // diagnosed when they are written directly (e.g., "int & &"),
  1783. // but not when they happen via a typedef:
  1784. //
  1785. // typedef int& intref;
  1786. // typedef intref& intref2;
  1787. //
  1788. // Parser::ParseDeclaratorInternal diagnoses the case where
  1789. // references are written directly; here, we handle the
  1790. // collapsing of references-to-references as described in C++0x.
  1791. // DR 106 and 540 introduce reference-collapsing into C++98/03.
  1792. // C++ [dcl.ref]p1:
  1793. // A declarator that specifies the type "reference to cv void"
  1794. // is ill-formed.
  1795. if (T->isVoidType()) {
  1796. Diag(Loc, diag::err_reference_to_void);
  1797. return QualType();
  1798. }
  1799. if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
  1800. return QualType();
  1801. // In ARC, it is forbidden to build references to unqualified pointers.
  1802. if (getLangOpts().ObjCAutoRefCount)
  1803. T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
  1804. // Handle restrict on references.
  1805. if (LValueRef)
  1806. return Context.getLValueReferenceType(T, SpelledAsLValue);
  1807. return Context.getRValueReferenceType(T);
  1808. }
  1809. /// Build a Read-only Pipe type.
  1810. ///
  1811. /// \param T The type to which we'll be building a Pipe.
  1812. ///
  1813. /// \param Loc We do not use it for now.
  1814. ///
  1815. /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
  1816. /// NULL type.
  1817. QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
  1818. return Context.getReadPipeType(T);
  1819. }
  1820. /// Build a Write-only Pipe type.
  1821. ///
  1822. /// \param T The type to which we'll be building a Pipe.
  1823. ///
  1824. /// \param Loc We do not use it for now.
  1825. ///
  1826. /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
  1827. /// NULL type.
  1828. QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
  1829. return Context.getWritePipeType(T);
  1830. }
  1831. /// Check whether the specified array size makes the array type a VLA. If so,
  1832. /// return true, if not, return the size of the array in SizeVal.
  1833. static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
  1834. // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
  1835. // (like gnu99, but not c99) accept any evaluatable value as an extension.
  1836. class VLADiagnoser : public Sema::VerifyICEDiagnoser {
  1837. public:
  1838. VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
  1839. void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1840. }
  1841. void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
  1842. S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
  1843. }
  1844. } Diagnoser;
  1845. return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
  1846. S.LangOpts.GNUMode ||
  1847. S.LangOpts.OpenCL).isInvalid();
  1848. }
  1849. /// Build an array type.
  1850. ///
  1851. /// \param T The type of each element in the array.
  1852. ///
  1853. /// \param ASM C99 array size modifier (e.g., '*', 'static').
  1854. ///
  1855. /// \param ArraySize Expression describing the size of the array.
  1856. ///
  1857. /// \param Brackets The range from the opening '[' to the closing ']'.
  1858. ///
  1859. /// \param Entity The name of the entity that involves the array
  1860. /// type, if known.
  1861. ///
  1862. /// \returns A suitable array type, if there are no errors. Otherwise,
  1863. /// returns a NULL type.
  1864. QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
  1865. Expr *ArraySize, unsigned Quals,
  1866. SourceRange Brackets, DeclarationName Entity) {
  1867. SourceLocation Loc = Brackets.getBegin();
  1868. if (getLangOpts().CPlusPlus) {
  1869. // C++ [dcl.array]p1:
  1870. // T is called the array element type; this type shall not be a reference
  1871. // type, the (possibly cv-qualified) type void, a function type or an
  1872. // abstract class type.
  1873. //
  1874. // C++ [dcl.array]p3:
  1875. // When several "array of" specifications are adjacent, [...] only the
  1876. // first of the constant expressions that specify the bounds of the arrays
  1877. // may be omitted.
  1878. //
  1879. // Note: function types are handled in the common path with C.
  1880. if (T->isReferenceType()) {
  1881. Diag(Loc, diag::err_illegal_decl_array_of_references)
  1882. << getPrintableNameForEntity(Entity) << T;
  1883. return QualType();
  1884. }
  1885. if (T->isVoidType() || T->isIncompleteArrayType()) {
  1886. Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
  1887. return QualType();
  1888. }
  1889. if (RequireNonAbstractType(Brackets.getBegin(), T,
  1890. diag::err_array_of_abstract_type))
  1891. return QualType();
  1892. // Mentioning a member pointer type for an array type causes us to lock in
  1893. // an inheritance model, even if it's inside an unused typedef.
  1894. if (Context.getTargetInfo().getCXXABI().isMicrosoft())
  1895. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
  1896. if (!MPTy->getClass()->isDependentType())
  1897. (void)isCompleteType(Loc, T);
  1898. } else {
  1899. // C99 6.7.5.2p1: If the element type is an incomplete or function type,
  1900. // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
  1901. if (RequireCompleteType(Loc, T,
  1902. diag::err_illegal_decl_array_incomplete_type))
  1903. return QualType();
  1904. }
  1905. if (T->isFunctionType()) {
  1906. Diag(Loc, diag::err_illegal_decl_array_of_functions)
  1907. << getPrintableNameForEntity(Entity) << T;
  1908. return QualType();
  1909. }
  1910. if (const RecordType *EltTy = T->getAs<RecordType>()) {
  1911. // If the element type is a struct or union that contains a variadic
  1912. // array, accept it as a GNU extension: C99 6.7.2.1p2.
  1913. if (EltTy->getDecl()->hasFlexibleArrayMember())
  1914. Diag(Loc, diag::ext_flexible_array_in_array) << T;
  1915. } else if (T->isObjCObjectType()) {
  1916. Diag(Loc, diag::err_objc_array_of_interfaces) << T;
  1917. return QualType();
  1918. }
  1919. // Do placeholder conversions on the array size expression.
  1920. if (ArraySize && ArraySize->hasPlaceholderType()) {
  1921. ExprResult Result = CheckPlaceholderExpr(ArraySize);
  1922. if (Result.isInvalid()) return QualType();
  1923. ArraySize = Result.get();
  1924. }
  1925. // Do lvalue-to-rvalue conversions on the array size expression.
  1926. if (ArraySize && !ArraySize->isRValue()) {
  1927. ExprResult Result = DefaultLvalueConversion(ArraySize);
  1928. if (Result.isInvalid())
  1929. return QualType();
  1930. ArraySize = Result.get();
  1931. }
  1932. // C99 6.7.5.2p1: The size expression shall have integer type.
  1933. // C++11 allows contextual conversions to such types.
  1934. if (!getLangOpts().CPlusPlus11 &&
  1935. ArraySize && !ArraySize->isTypeDependent() &&
  1936. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1937. Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
  1938. << ArraySize->getType() << ArraySize->getSourceRange();
  1939. return QualType();
  1940. }
  1941. llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
  1942. if (!ArraySize) {
  1943. if (ASM == ArrayType::Star)
  1944. T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
  1945. else
  1946. T = Context.getIncompleteArrayType(T, ASM, Quals);
  1947. } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
  1948. T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
  1949. } else if ((!T->isDependentType() && !T->isIncompleteType() &&
  1950. !T->isConstantSizeType()) ||
  1951. isArraySizeVLA(*this, ArraySize, ConstVal)) {
  1952. // Even in C++11, don't allow contextual conversions in the array bound
  1953. // of a VLA.
  1954. if (getLangOpts().CPlusPlus11 &&
  1955. !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
  1956. Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
  1957. << ArraySize->getType() << ArraySize->getSourceRange();
  1958. return QualType();
  1959. }
  1960. // C99: an array with an element type that has a non-constant-size is a VLA.
  1961. // C99: an array with a non-ICE size is a VLA. We accept any expression
  1962. // that we can fold to a non-zero positive value as an extension.
  1963. T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
  1964. } else {
  1965. // C99 6.7.5.2p1: If the expression is a constant expression, it shall
  1966. // have a value greater than zero.
  1967. if (ConstVal.isSigned() && ConstVal.isNegative()) {
  1968. if (Entity)
  1969. Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
  1970. << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
  1971. else
  1972. Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
  1973. << ArraySize->getSourceRange();
  1974. return QualType();
  1975. }
  1976. if (ConstVal == 0) {
  1977. // GCC accepts zero sized static arrays. We allow them when
  1978. // we're not in a SFINAE context.
  1979. Diag(ArraySize->getBeginLoc(), isSFINAEContext()
  1980. ? diag::err_typecheck_zero_array_size
  1981. : diag::ext_typecheck_zero_array_size)
  1982. << ArraySize->getSourceRange();
  1983. if (ASM == ArrayType::Static) {
  1984. Diag(ArraySize->getBeginLoc(),
  1985. diag::warn_typecheck_zero_static_array_size)
  1986. << ArraySize->getSourceRange();
  1987. ASM = ArrayType::Normal;
  1988. }
  1989. } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
  1990. !T->isIncompleteType() && !T->isUndeducedType()) {
  1991. // Is the array too large?
  1992. unsigned ActiveSizeBits
  1993. = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
  1994. if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
  1995. Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
  1996. << ConstVal.toString(10) << ArraySize->getSourceRange();
  1997. return QualType();
  1998. }
  1999. }
  2000. T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
  2001. }
  2002. // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
  2003. if (getLangOpts().OpenCL && T->isVariableArrayType()) {
  2004. Diag(Loc, diag::err_opencl_vla);
  2005. return QualType();
  2006. }
  2007. if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
  2008. // CUDA device code and some other targets don't support VLAs.
  2009. targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
  2010. ? diag::err_cuda_vla
  2011. : diag::err_vla_unsupported)
  2012. << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
  2013. ? CurrentCUDATarget()
  2014. : CFT_InvalidTarget);
  2015. }
  2016. // If this is not C99, extwarn about VLA's and C99 array size modifiers.
  2017. if (!getLangOpts().C99) {
  2018. if (T->isVariableArrayType()) {
  2019. // Prohibit the use of VLAs during template argument deduction.
  2020. if (isSFINAEContext()) {
  2021. Diag(Loc, diag::err_vla_in_sfinae);
  2022. return QualType();
  2023. }
  2024. // Just extwarn about VLAs.
  2025. else
  2026. Diag(Loc, diag::ext_vla);
  2027. } else if (ASM != ArrayType::Normal || Quals != 0)
  2028. Diag(Loc,
  2029. getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
  2030. : diag::ext_c99_array_usage) << ASM;
  2031. }
  2032. if (T->isVariableArrayType()) {
  2033. // Warn about VLAs for -Wvla.
  2034. Diag(Loc, diag::warn_vla_used);
  2035. }
  2036. // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
  2037. // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
  2038. // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
  2039. if (getLangOpts().OpenCL) {
  2040. const QualType ArrType = Context.getBaseElementType(T);
  2041. if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
  2042. ArrType->isSamplerT() || ArrType->isImageType()) {
  2043. Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
  2044. return QualType();
  2045. }
  2046. }
  2047. return T;
  2048. }
  2049. QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
  2050. SourceLocation AttrLoc) {
  2051. // The base type must be integer (not Boolean or enumeration) or float, and
  2052. // can't already be a vector.
  2053. if (!CurType->isDependentType() &&
  2054. (!CurType->isBuiltinType() || CurType->isBooleanType() ||
  2055. (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
  2056. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
  2057. return QualType();
  2058. }
  2059. if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
  2060. return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
  2061. VectorType::GenericVector);
  2062. llvm::APSInt VecSize(32);
  2063. if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
  2064. Diag(AttrLoc, diag::err_attribute_argument_type)
  2065. << "vector_size" << AANT_ArgumentIntegerConstant
  2066. << SizeExpr->getSourceRange();
  2067. return QualType();
  2068. }
  2069. if (CurType->isDependentType())
  2070. return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
  2071. VectorType::GenericVector);
  2072. unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
  2073. unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
  2074. if (VectorSize == 0) {
  2075. Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
  2076. return QualType();
  2077. }
  2078. // vecSize is specified in bytes - convert to bits.
  2079. if (VectorSize % TypeSize) {
  2080. Diag(AttrLoc, diag::err_attribute_invalid_size)
  2081. << SizeExpr->getSourceRange();
  2082. return QualType();
  2083. }
  2084. if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
  2085. Diag(AttrLoc, diag::err_attribute_size_too_large)
  2086. << SizeExpr->getSourceRange();
  2087. return QualType();
  2088. }
  2089. return Context.getVectorType(CurType, VectorSize / TypeSize,
  2090. VectorType::GenericVector);
  2091. }
  2092. /// Build an ext-vector type.
  2093. ///
  2094. /// Run the required checks for the extended vector type.
  2095. QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
  2096. SourceLocation AttrLoc) {
  2097. // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
  2098. // in conjunction with complex types (pointers, arrays, functions, etc.).
  2099. //
  2100. // Additionally, OpenCL prohibits vectors of booleans (they're considered a
  2101. // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
  2102. // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
  2103. // of bool aren't allowed.
  2104. if ((!T->isDependentType() && !T->isIntegerType() &&
  2105. !T->isRealFloatingType()) ||
  2106. T->isBooleanType()) {
  2107. Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
  2108. return QualType();
  2109. }
  2110. if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
  2111. llvm::APSInt vecSize(32);
  2112. if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
  2113. Diag(AttrLoc, diag::err_attribute_argument_type)
  2114. << "ext_vector_type" << AANT_ArgumentIntegerConstant
  2115. << ArraySize->getSourceRange();
  2116. return QualType();
  2117. }
  2118. // Unlike gcc's vector_size attribute, the size is specified as the
  2119. // number of elements, not the number of bytes.
  2120. unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
  2121. if (vectorSize == 0) {
  2122. Diag(AttrLoc, diag::err_attribute_zero_size)
  2123. << ArraySize->getSourceRange();
  2124. return QualType();
  2125. }
  2126. if (VectorType::isVectorSizeTooLarge(vectorSize)) {
  2127. Diag(AttrLoc, diag::err_attribute_size_too_large)
  2128. << ArraySize->getSourceRange();
  2129. return QualType();
  2130. }
  2131. return Context.getExtVectorType(T, vectorSize);
  2132. }
  2133. return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
  2134. }
  2135. bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
  2136. if (T->isArrayType() || T->isFunctionType()) {
  2137. Diag(Loc, diag::err_func_returning_array_function)
  2138. << T->isFunctionType() << T;
  2139. return true;
  2140. }
  2141. // Functions cannot return half FP.
  2142. if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  2143. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
  2144. FixItHint::CreateInsertion(Loc, "*");
  2145. return true;
  2146. }
  2147. // Methods cannot return interface types. All ObjC objects are
  2148. // passed by reference.
  2149. if (T->isObjCObjectType()) {
  2150. Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
  2151. << 0 << T << FixItHint::CreateInsertion(Loc, "*");
  2152. return true;
  2153. }
  2154. if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
  2155. T.hasNonTrivialToPrimitiveCopyCUnion())
  2156. checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
  2157. NTCUK_Destruct|NTCUK_Copy);
  2158. // C++2a [dcl.fct]p12:
  2159. // A volatile-qualified return type is deprecated
  2160. if (T.isVolatileQualified() && getLangOpts().CPlusPlus2a)
  2161. Diag(Loc, diag::warn_deprecated_volatile_return) << T;
  2162. return false;
  2163. }
  2164. /// Check the extended parameter information. Most of the necessary
  2165. /// checking should occur when applying the parameter attribute; the
  2166. /// only other checks required are positional restrictions.
  2167. static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
  2168. const FunctionProtoType::ExtProtoInfo &EPI,
  2169. llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
  2170. assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
  2171. bool hasCheckedSwiftCall = false;
  2172. auto checkForSwiftCC = [&](unsigned paramIndex) {
  2173. // Only do this once.
  2174. if (hasCheckedSwiftCall) return;
  2175. hasCheckedSwiftCall = true;
  2176. if (EPI.ExtInfo.getCC() == CC_Swift) return;
  2177. S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
  2178. << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
  2179. };
  2180. for (size_t paramIndex = 0, numParams = paramTypes.size();
  2181. paramIndex != numParams; ++paramIndex) {
  2182. switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
  2183. // Nothing interesting to check for orindary-ABI parameters.
  2184. case ParameterABI::Ordinary:
  2185. continue;
  2186. // swift_indirect_result parameters must be a prefix of the function
  2187. // arguments.
  2188. case ParameterABI::SwiftIndirectResult:
  2189. checkForSwiftCC(paramIndex);
  2190. if (paramIndex != 0 &&
  2191. EPI.ExtParameterInfos[paramIndex - 1].getABI()
  2192. != ParameterABI::SwiftIndirectResult) {
  2193. S.Diag(getParamLoc(paramIndex),
  2194. diag::err_swift_indirect_result_not_first);
  2195. }
  2196. continue;
  2197. case ParameterABI::SwiftContext:
  2198. checkForSwiftCC(paramIndex);
  2199. continue;
  2200. // swift_error parameters must be preceded by a swift_context parameter.
  2201. case ParameterABI::SwiftErrorResult:
  2202. checkForSwiftCC(paramIndex);
  2203. if (paramIndex == 0 ||
  2204. EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
  2205. ParameterABI::SwiftContext) {
  2206. S.Diag(getParamLoc(paramIndex),
  2207. diag::err_swift_error_result_not_after_swift_context);
  2208. }
  2209. continue;
  2210. }
  2211. llvm_unreachable("bad ABI kind");
  2212. }
  2213. }
  2214. QualType Sema::BuildFunctionType(QualType T,
  2215. MutableArrayRef<QualType> ParamTypes,
  2216. SourceLocation Loc, DeclarationName Entity,
  2217. const FunctionProtoType::ExtProtoInfo &EPI) {
  2218. bool Invalid = false;
  2219. Invalid |= CheckFunctionReturnType(T, Loc);
  2220. for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
  2221. // FIXME: Loc is too inprecise here, should use proper locations for args.
  2222. QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
  2223. if (ParamType->isVoidType()) {
  2224. Diag(Loc, diag::err_param_with_void_type);
  2225. Invalid = true;
  2226. } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
  2227. // Disallow half FP arguments.
  2228. Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
  2229. FixItHint::CreateInsertion(Loc, "*");
  2230. Invalid = true;
  2231. }
  2232. // C++2a [dcl.fct]p4:
  2233. // A parameter with volatile-qualified type is deprecated
  2234. if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus2a)
  2235. Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
  2236. ParamTypes[Idx] = ParamType;
  2237. }
  2238. if (EPI.ExtParameterInfos) {
  2239. checkExtParameterInfos(*this, ParamTypes, EPI,
  2240. [=](unsigned i) { return Loc; });
  2241. }
  2242. if (EPI.ExtInfo.getProducesResult()) {
  2243. // This is just a warning, so we can't fail to build if we see it.
  2244. checkNSReturnsRetainedReturnType(Loc, T);
  2245. }
  2246. if (Invalid)
  2247. return QualType();
  2248. return Context.getFunctionType(T, ParamTypes, EPI);
  2249. }
  2250. /// Build a member pointer type \c T Class::*.
  2251. ///
  2252. /// \param T the type to which the member pointer refers.
  2253. /// \param Class the class type into which the member pointer points.
  2254. /// \param Loc the location where this type begins
  2255. /// \param Entity the name of the entity that will have this member pointer type
  2256. ///
  2257. /// \returns a member pointer type, if successful, or a NULL type if there was
  2258. /// an error.
  2259. QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
  2260. SourceLocation Loc,
  2261. DeclarationName Entity) {
  2262. // Verify that we're not building a pointer to pointer to function with
  2263. // exception specification.
  2264. if (CheckDistantExceptionSpec(T)) {
  2265. Diag(Loc, diag::err_distant_exception_spec);
  2266. return QualType();
  2267. }
  2268. // C++ 8.3.3p3: A pointer to member shall not point to ... a member
  2269. // with reference type, or "cv void."
  2270. if (T->isReferenceType()) {
  2271. Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
  2272. << getPrintableNameForEntity(Entity) << T;
  2273. return QualType();
  2274. }
  2275. if (T->isVoidType()) {
  2276. Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
  2277. << getPrintableNameForEntity(Entity);
  2278. return QualType();
  2279. }
  2280. if (!Class->isDependentType() && !Class->isRecordType()) {
  2281. Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
  2282. return QualType();
  2283. }
  2284. // Adjust the default free function calling convention to the default method
  2285. // calling convention.
  2286. bool IsCtorOrDtor =
  2287. (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
  2288. (Entity.getNameKind() == DeclarationName::CXXDestructorName);
  2289. if (T->isFunctionType())
  2290. adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
  2291. return Context.getMemberPointerType(T, Class.getTypePtr());
  2292. }
  2293. /// Build a block pointer type.
  2294. ///
  2295. /// \param T The type to which we'll be building a block pointer.
  2296. ///
  2297. /// \param Loc The source location, used for diagnostics.
  2298. ///
  2299. /// \param Entity The name of the entity that involves the block pointer
  2300. /// type, if known.
  2301. ///
  2302. /// \returns A suitable block pointer type, if there are no
  2303. /// errors. Otherwise, returns a NULL type.
  2304. QualType Sema::BuildBlockPointerType(QualType T,
  2305. SourceLocation Loc,
  2306. DeclarationName Entity) {
  2307. if (!T->isFunctionType()) {
  2308. Diag(Loc, diag::err_nonfunction_block_type);
  2309. return QualType();
  2310. }
  2311. if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
  2312. return QualType();
  2313. return Context.getBlockPointerType(T);
  2314. }
  2315. QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
  2316. QualType QT = Ty.get();
  2317. if (QT.isNull()) {
  2318. if (TInfo) *TInfo = nullptr;
  2319. return QualType();
  2320. }
  2321. TypeSourceInfo *DI = nullptr;
  2322. if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
  2323. QT = LIT->getType();
  2324. DI = LIT->getTypeSourceInfo();
  2325. }
  2326. if (TInfo) *TInfo = DI;
  2327. return QT;
  2328. }
  2329. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  2330. Qualifiers::ObjCLifetime ownership,
  2331. unsigned chunkIndex);
  2332. /// Given that this is the declaration of a parameter under ARC,
  2333. /// attempt to infer attributes and such for pointer-to-whatever
  2334. /// types.
  2335. static void inferARCWriteback(TypeProcessingState &state,
  2336. QualType &declSpecType) {
  2337. Sema &S = state.getSema();
  2338. Declarator &declarator = state.getDeclarator();
  2339. // TODO: should we care about decl qualifiers?
  2340. // Check whether the declarator has the expected form. We walk
  2341. // from the inside out in order to make the block logic work.
  2342. unsigned outermostPointerIndex = 0;
  2343. bool isBlockPointer = false;
  2344. unsigned numPointers = 0;
  2345. for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
  2346. unsigned chunkIndex = i;
  2347. DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
  2348. switch (chunk.Kind) {
  2349. case DeclaratorChunk::Paren:
  2350. // Ignore parens.
  2351. break;
  2352. case DeclaratorChunk::Reference:
  2353. case DeclaratorChunk::Pointer:
  2354. // Count the number of pointers. Treat references
  2355. // interchangeably as pointers; if they're mis-ordered, normal
  2356. // type building will discover that.
  2357. outermostPointerIndex = chunkIndex;
  2358. numPointers++;
  2359. break;
  2360. case DeclaratorChunk::BlockPointer:
  2361. // If we have a pointer to block pointer, that's an acceptable
  2362. // indirect reference; anything else is not an application of
  2363. // the rules.
  2364. if (numPointers != 1) return;
  2365. numPointers++;
  2366. outermostPointerIndex = chunkIndex;
  2367. isBlockPointer = true;
  2368. // We don't care about pointer structure in return values here.
  2369. goto done;
  2370. case DeclaratorChunk::Array: // suppress if written (id[])?
  2371. case DeclaratorChunk::Function:
  2372. case DeclaratorChunk::MemberPointer:
  2373. case DeclaratorChunk::Pipe:
  2374. return;
  2375. }
  2376. }
  2377. done:
  2378. // If we have *one* pointer, then we want to throw the qualifier on
  2379. // the declaration-specifiers, which means that it needs to be a
  2380. // retainable object type.
  2381. if (numPointers == 1) {
  2382. // If it's not a retainable object type, the rule doesn't apply.
  2383. if (!declSpecType->isObjCRetainableType()) return;
  2384. // If it already has lifetime, don't do anything.
  2385. if (declSpecType.getObjCLifetime()) return;
  2386. // Otherwise, modify the type in-place.
  2387. Qualifiers qs;
  2388. if (declSpecType->isObjCARCImplicitlyUnretainedType())
  2389. qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
  2390. else
  2391. qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
  2392. declSpecType = S.Context.getQualifiedType(declSpecType, qs);
  2393. // If we have *two* pointers, then we want to throw the qualifier on
  2394. // the outermost pointer.
  2395. } else if (numPointers == 2) {
  2396. // If we don't have a block pointer, we need to check whether the
  2397. // declaration-specifiers gave us something that will turn into a
  2398. // retainable object pointer after we slap the first pointer on it.
  2399. if (!isBlockPointer && !declSpecType->isObjCObjectType())
  2400. return;
  2401. // Look for an explicit lifetime attribute there.
  2402. DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
  2403. if (chunk.Kind != DeclaratorChunk::Pointer &&
  2404. chunk.Kind != DeclaratorChunk::BlockPointer)
  2405. return;
  2406. for (const ParsedAttr &AL : chunk.getAttrs())
  2407. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
  2408. return;
  2409. transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
  2410. outermostPointerIndex);
  2411. // Any other number of pointers/references does not trigger the rule.
  2412. } else return;
  2413. // TODO: mark whether we did this inference?
  2414. }
  2415. void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
  2416. SourceLocation FallbackLoc,
  2417. SourceLocation ConstQualLoc,
  2418. SourceLocation VolatileQualLoc,
  2419. SourceLocation RestrictQualLoc,
  2420. SourceLocation AtomicQualLoc,
  2421. SourceLocation UnalignedQualLoc) {
  2422. if (!Quals)
  2423. return;
  2424. struct Qual {
  2425. const char *Name;
  2426. unsigned Mask;
  2427. SourceLocation Loc;
  2428. } const QualKinds[5] = {
  2429. { "const", DeclSpec::TQ_const, ConstQualLoc },
  2430. { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
  2431. { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
  2432. { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
  2433. { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
  2434. };
  2435. SmallString<32> QualStr;
  2436. unsigned NumQuals = 0;
  2437. SourceLocation Loc;
  2438. FixItHint FixIts[5];
  2439. // Build a string naming the redundant qualifiers.
  2440. for (auto &E : QualKinds) {
  2441. if (Quals & E.Mask) {
  2442. if (!QualStr.empty()) QualStr += ' ';
  2443. QualStr += E.Name;
  2444. // If we have a location for the qualifier, offer a fixit.
  2445. SourceLocation QualLoc = E.Loc;
  2446. if (QualLoc.isValid()) {
  2447. FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
  2448. if (Loc.isInvalid() ||
  2449. getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
  2450. Loc = QualLoc;
  2451. }
  2452. ++NumQuals;
  2453. }
  2454. }
  2455. Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
  2456. << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
  2457. }
  2458. // Diagnose pointless type qualifiers on the return type of a function.
  2459. static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
  2460. Declarator &D,
  2461. unsigned FunctionChunkIndex) {
  2462. if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
  2463. // FIXME: TypeSourceInfo doesn't preserve location information for
  2464. // qualifiers.
  2465. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2466. RetTy.getLocalCVRQualifiers(),
  2467. D.getIdentifierLoc());
  2468. return;
  2469. }
  2470. for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
  2471. End = D.getNumTypeObjects();
  2472. OuterChunkIndex != End; ++OuterChunkIndex) {
  2473. DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
  2474. switch (OuterChunk.Kind) {
  2475. case DeclaratorChunk::Paren:
  2476. continue;
  2477. case DeclaratorChunk::Pointer: {
  2478. DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
  2479. S.diagnoseIgnoredQualifiers(
  2480. diag::warn_qual_return_type,
  2481. PTI.TypeQuals,
  2482. SourceLocation(),
  2483. SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
  2484. SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
  2485. SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
  2486. SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
  2487. SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
  2488. return;
  2489. }
  2490. case DeclaratorChunk::Function:
  2491. case DeclaratorChunk::BlockPointer:
  2492. case DeclaratorChunk::Reference:
  2493. case DeclaratorChunk::Array:
  2494. case DeclaratorChunk::MemberPointer:
  2495. case DeclaratorChunk::Pipe:
  2496. // FIXME: We can't currently provide an accurate source location and a
  2497. // fix-it hint for these.
  2498. unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
  2499. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2500. RetTy.getCVRQualifiers() | AtomicQual,
  2501. D.getIdentifierLoc());
  2502. return;
  2503. }
  2504. llvm_unreachable("unknown declarator chunk kind");
  2505. }
  2506. // If the qualifiers come from a conversion function type, don't diagnose
  2507. // them -- they're not necessarily redundant, since such a conversion
  2508. // operator can be explicitly called as "x.operator const int()".
  2509. if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
  2510. return;
  2511. // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
  2512. // which are present there.
  2513. S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
  2514. D.getDeclSpec().getTypeQualifiers(),
  2515. D.getIdentifierLoc(),
  2516. D.getDeclSpec().getConstSpecLoc(),
  2517. D.getDeclSpec().getVolatileSpecLoc(),
  2518. D.getDeclSpec().getRestrictSpecLoc(),
  2519. D.getDeclSpec().getAtomicSpecLoc(),
  2520. D.getDeclSpec().getUnalignedSpecLoc());
  2521. }
  2522. static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
  2523. TypeSourceInfo *&ReturnTypeInfo) {
  2524. Sema &SemaRef = state.getSema();
  2525. Declarator &D = state.getDeclarator();
  2526. QualType T;
  2527. ReturnTypeInfo = nullptr;
  2528. // The TagDecl owned by the DeclSpec.
  2529. TagDecl *OwnedTagDecl = nullptr;
  2530. switch (D.getName().getKind()) {
  2531. case UnqualifiedIdKind::IK_ImplicitSelfParam:
  2532. case UnqualifiedIdKind::IK_OperatorFunctionId:
  2533. case UnqualifiedIdKind::IK_Identifier:
  2534. case UnqualifiedIdKind::IK_LiteralOperatorId:
  2535. case UnqualifiedIdKind::IK_TemplateId:
  2536. T = ConvertDeclSpecToType(state);
  2537. if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
  2538. OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  2539. // Owned declaration is embedded in declarator.
  2540. OwnedTagDecl->setEmbeddedInDeclarator(true);
  2541. }
  2542. break;
  2543. case UnqualifiedIdKind::IK_ConstructorName:
  2544. case UnqualifiedIdKind::IK_ConstructorTemplateId:
  2545. case UnqualifiedIdKind::IK_DestructorName:
  2546. // Constructors and destructors don't have return types. Use
  2547. // "void" instead.
  2548. T = SemaRef.Context.VoidTy;
  2549. processTypeAttrs(state, T, TAL_DeclSpec,
  2550. D.getMutableDeclSpec().getAttributes());
  2551. break;
  2552. case UnqualifiedIdKind::IK_DeductionGuideName:
  2553. // Deduction guides have a trailing return type and no type in their
  2554. // decl-specifier sequence. Use a placeholder return type for now.
  2555. T = SemaRef.Context.DependentTy;
  2556. break;
  2557. case UnqualifiedIdKind::IK_ConversionFunctionId:
  2558. // The result type of a conversion function is the type that it
  2559. // converts to.
  2560. T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
  2561. &ReturnTypeInfo);
  2562. break;
  2563. }
  2564. if (!D.getAttributes().empty())
  2565. distributeTypeAttrsFromDeclarator(state, T);
  2566. // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
  2567. if (DeducedType *Deduced = T->getContainedDeducedType()) {
  2568. AutoType *Auto = dyn_cast<AutoType>(Deduced);
  2569. int Error = -1;
  2570. // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
  2571. // class template argument deduction)?
  2572. bool IsCXXAutoType =
  2573. (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
  2574. bool IsDeducedReturnType = false;
  2575. switch (D.getContext()) {
  2576. case DeclaratorContext::LambdaExprContext:
  2577. // Declared return type of a lambda-declarator is implicit and is always
  2578. // 'auto'.
  2579. break;
  2580. case DeclaratorContext::ObjCParameterContext:
  2581. case DeclaratorContext::ObjCResultContext:
  2582. case DeclaratorContext::PrototypeContext:
  2583. Error = 0;
  2584. break;
  2585. case DeclaratorContext::LambdaExprParameterContext:
  2586. // In C++14, generic lambdas allow 'auto' in their parameters.
  2587. if (!SemaRef.getLangOpts().CPlusPlus14 ||
  2588. !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
  2589. Error = 16;
  2590. else {
  2591. // If auto is mentioned in a lambda parameter context, convert it to a
  2592. // template parameter type.
  2593. sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
  2594. assert(LSI && "No LambdaScopeInfo on the stack!");
  2595. const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
  2596. const unsigned AutoParameterPosition = LSI->TemplateParams.size();
  2597. const bool IsParameterPack = D.hasEllipsis();
  2598. // Create the TemplateTypeParmDecl here to retrieve the corresponding
  2599. // template parameter type. Template parameters are temporarily added
  2600. // to the TU until the associated TemplateDecl is created.
  2601. TemplateTypeParmDecl *CorrespondingTemplateParam =
  2602. TemplateTypeParmDecl::Create(
  2603. SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
  2604. /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(),
  2605. TemplateParameterDepth, AutoParameterPosition,
  2606. /*Identifier*/ nullptr, false, IsParameterPack);
  2607. CorrespondingTemplateParam->setImplicit();
  2608. LSI->TemplateParams.push_back(CorrespondingTemplateParam);
  2609. // Replace the 'auto' in the function parameter with this invented
  2610. // template type parameter.
  2611. // FIXME: Retain some type sugar to indicate that this was written
  2612. // as 'auto'.
  2613. T = state.ReplaceAutoType(
  2614. T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
  2615. }
  2616. break;
  2617. case DeclaratorContext::MemberContext: {
  2618. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
  2619. D.isFunctionDeclarator())
  2620. break;
  2621. bool Cxx = SemaRef.getLangOpts().CPlusPlus;
  2622. switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
  2623. case TTK_Enum: llvm_unreachable("unhandled tag kind");
  2624. case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
  2625. case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
  2626. case TTK_Class: Error = 5; /* Class member */ break;
  2627. case TTK_Interface: Error = 6; /* Interface member */ break;
  2628. }
  2629. if (D.getDeclSpec().isFriendSpecified())
  2630. Error = 20; // Friend type
  2631. break;
  2632. }
  2633. case DeclaratorContext::CXXCatchContext:
  2634. case DeclaratorContext::ObjCCatchContext:
  2635. Error = 7; // Exception declaration
  2636. break;
  2637. case DeclaratorContext::TemplateParamContext:
  2638. if (isa<DeducedTemplateSpecializationType>(Deduced))
  2639. Error = 19; // Template parameter
  2640. else if (!SemaRef.getLangOpts().CPlusPlus17)
  2641. Error = 8; // Template parameter (until C++17)
  2642. break;
  2643. case DeclaratorContext::BlockLiteralContext:
  2644. Error = 9; // Block literal
  2645. break;
  2646. case DeclaratorContext::TemplateArgContext:
  2647. // Within a template argument list, a deduced template specialization
  2648. // type will be reinterpreted as a template template argument.
  2649. if (isa<DeducedTemplateSpecializationType>(Deduced) &&
  2650. !D.getNumTypeObjects() &&
  2651. D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
  2652. break;
  2653. LLVM_FALLTHROUGH;
  2654. case DeclaratorContext::TemplateTypeArgContext:
  2655. Error = 10; // Template type argument
  2656. break;
  2657. case DeclaratorContext::AliasDeclContext:
  2658. case DeclaratorContext::AliasTemplateContext:
  2659. Error = 12; // Type alias
  2660. break;
  2661. case DeclaratorContext::TrailingReturnContext:
  2662. case DeclaratorContext::TrailingReturnVarContext:
  2663. if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
  2664. Error = 13; // Function return type
  2665. IsDeducedReturnType = true;
  2666. break;
  2667. case DeclaratorContext::ConversionIdContext:
  2668. if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
  2669. Error = 14; // conversion-type-id
  2670. IsDeducedReturnType = true;
  2671. break;
  2672. case DeclaratorContext::FunctionalCastContext:
  2673. if (isa<DeducedTemplateSpecializationType>(Deduced))
  2674. break;
  2675. LLVM_FALLTHROUGH;
  2676. case DeclaratorContext::TypeNameContext:
  2677. Error = 15; // Generic
  2678. break;
  2679. case DeclaratorContext::FileContext:
  2680. case DeclaratorContext::BlockContext:
  2681. case DeclaratorContext::ForContext:
  2682. case DeclaratorContext::InitStmtContext:
  2683. case DeclaratorContext::ConditionContext:
  2684. // FIXME: P0091R3 (erroneously) does not permit class template argument
  2685. // deduction in conditions, for-init-statements, and other declarations
  2686. // that are not simple-declarations.
  2687. break;
  2688. case DeclaratorContext::CXXNewContext:
  2689. // FIXME: P0091R3 does not permit class template argument deduction here,
  2690. // but we follow GCC and allow it anyway.
  2691. if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
  2692. Error = 17; // 'new' type
  2693. break;
  2694. case DeclaratorContext::KNRTypeListContext:
  2695. Error = 18; // K&R function parameter
  2696. break;
  2697. }
  2698. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
  2699. Error = 11;
  2700. // In Objective-C it is an error to use 'auto' on a function declarator
  2701. // (and everywhere for '__auto_type').
  2702. if (D.isFunctionDeclarator() &&
  2703. (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
  2704. Error = 13;
  2705. bool HaveTrailing = false;
  2706. // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
  2707. // contains a trailing return type. That is only legal at the outermost
  2708. // level. Check all declarator chunks (outermost first) anyway, to give
  2709. // better diagnostics.
  2710. // We don't support '__auto_type' with trailing return types.
  2711. // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
  2712. if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
  2713. D.hasTrailingReturnType()) {
  2714. HaveTrailing = true;
  2715. Error = -1;
  2716. }
  2717. SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
  2718. if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
  2719. AutoRange = D.getName().getSourceRange();
  2720. if (Error != -1) {
  2721. unsigned Kind;
  2722. if (Auto) {
  2723. switch (Auto->getKeyword()) {
  2724. case AutoTypeKeyword::Auto: Kind = 0; break;
  2725. case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
  2726. case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
  2727. }
  2728. } else {
  2729. assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
  2730. "unknown auto type");
  2731. Kind = 3;
  2732. }
  2733. auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
  2734. TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
  2735. SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
  2736. << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
  2737. << QualType(Deduced, 0) << AutoRange;
  2738. if (auto *TD = TN.getAsTemplateDecl())
  2739. SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
  2740. T = SemaRef.Context.IntTy;
  2741. D.setInvalidType(true);
  2742. } else if (!HaveTrailing &&
  2743. D.getContext() != DeclaratorContext::LambdaExprContext) {
  2744. // If there was a trailing return type, we already got
  2745. // warn_cxx98_compat_trailing_return_type in the parser.
  2746. SemaRef.Diag(AutoRange.getBegin(),
  2747. D.getContext() ==
  2748. DeclaratorContext::LambdaExprParameterContext
  2749. ? diag::warn_cxx11_compat_generic_lambda
  2750. : IsDeducedReturnType
  2751. ? diag::warn_cxx11_compat_deduced_return_type
  2752. : diag::warn_cxx98_compat_auto_type_specifier)
  2753. << AutoRange;
  2754. }
  2755. }
  2756. if (SemaRef.getLangOpts().CPlusPlus &&
  2757. OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
  2758. // Check the contexts where C++ forbids the declaration of a new class
  2759. // or enumeration in a type-specifier-seq.
  2760. unsigned DiagID = 0;
  2761. switch (D.getContext()) {
  2762. case DeclaratorContext::TrailingReturnContext:
  2763. case DeclaratorContext::TrailingReturnVarContext:
  2764. // Class and enumeration definitions are syntactically not allowed in
  2765. // trailing return types.
  2766. llvm_unreachable("parser should not have allowed this");
  2767. break;
  2768. case DeclaratorContext::FileContext:
  2769. case DeclaratorContext::MemberContext:
  2770. case DeclaratorContext::BlockContext:
  2771. case DeclaratorContext::ForContext:
  2772. case DeclaratorContext::InitStmtContext:
  2773. case DeclaratorContext::BlockLiteralContext:
  2774. case DeclaratorContext::LambdaExprContext:
  2775. // C++11 [dcl.type]p3:
  2776. // A type-specifier-seq shall not define a class or enumeration unless
  2777. // it appears in the type-id of an alias-declaration (7.1.3) that is not
  2778. // the declaration of a template-declaration.
  2779. case DeclaratorContext::AliasDeclContext:
  2780. break;
  2781. case DeclaratorContext::AliasTemplateContext:
  2782. DiagID = diag::err_type_defined_in_alias_template;
  2783. break;
  2784. case DeclaratorContext::TypeNameContext:
  2785. case DeclaratorContext::FunctionalCastContext:
  2786. case DeclaratorContext::ConversionIdContext:
  2787. case DeclaratorContext::TemplateParamContext:
  2788. case DeclaratorContext::CXXNewContext:
  2789. case DeclaratorContext::CXXCatchContext:
  2790. case DeclaratorContext::ObjCCatchContext:
  2791. case DeclaratorContext::TemplateArgContext:
  2792. case DeclaratorContext::TemplateTypeArgContext:
  2793. DiagID = diag::err_type_defined_in_type_specifier;
  2794. break;
  2795. case DeclaratorContext::PrototypeContext:
  2796. case DeclaratorContext::LambdaExprParameterContext:
  2797. case DeclaratorContext::ObjCParameterContext:
  2798. case DeclaratorContext::ObjCResultContext:
  2799. case DeclaratorContext::KNRTypeListContext:
  2800. // C++ [dcl.fct]p6:
  2801. // Types shall not be defined in return or parameter types.
  2802. DiagID = diag::err_type_defined_in_param_type;
  2803. break;
  2804. case DeclaratorContext::ConditionContext:
  2805. // C++ 6.4p2:
  2806. // The type-specifier-seq shall not contain typedef and shall not declare
  2807. // a new class or enumeration.
  2808. DiagID = diag::err_type_defined_in_condition;
  2809. break;
  2810. }
  2811. if (DiagID != 0) {
  2812. SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
  2813. << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
  2814. D.setInvalidType(true);
  2815. }
  2816. }
  2817. assert(!T.isNull() && "This function should not return a null type");
  2818. return T;
  2819. }
  2820. /// Produce an appropriate diagnostic for an ambiguity between a function
  2821. /// declarator and a C++ direct-initializer.
  2822. static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
  2823. DeclaratorChunk &DeclType, QualType RT) {
  2824. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  2825. assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
  2826. // If the return type is void there is no ambiguity.
  2827. if (RT->isVoidType())
  2828. return;
  2829. // An initializer for a non-class type can have at most one argument.
  2830. if (!RT->isRecordType() && FTI.NumParams > 1)
  2831. return;
  2832. // An initializer for a reference must have exactly one argument.
  2833. if (RT->isReferenceType() && FTI.NumParams != 1)
  2834. return;
  2835. // Only warn if this declarator is declaring a function at block scope, and
  2836. // doesn't have a storage class (such as 'extern') specified.
  2837. if (!D.isFunctionDeclarator() ||
  2838. D.getFunctionDefinitionKind() != FDK_Declaration ||
  2839. !S.CurContext->isFunctionOrMethod() ||
  2840. D.getDeclSpec().getStorageClassSpec()
  2841. != DeclSpec::SCS_unspecified)
  2842. return;
  2843. // Inside a condition, a direct initializer is not permitted. We allow one to
  2844. // be parsed in order to give better diagnostics in condition parsing.
  2845. if (D.getContext() == DeclaratorContext::ConditionContext)
  2846. return;
  2847. SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
  2848. S.Diag(DeclType.Loc,
  2849. FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
  2850. : diag::warn_empty_parens_are_function_decl)
  2851. << ParenRange;
  2852. // If the declaration looks like:
  2853. // T var1,
  2854. // f();
  2855. // and name lookup finds a function named 'f', then the ',' was
  2856. // probably intended to be a ';'.
  2857. if (!D.isFirstDeclarator() && D.getIdentifier()) {
  2858. FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
  2859. FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
  2860. if (Comma.getFileID() != Name.getFileID() ||
  2861. Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
  2862. LookupResult Result(S, D.getIdentifier(), SourceLocation(),
  2863. Sema::LookupOrdinaryName);
  2864. if (S.LookupName(Result, S.getCurScope()))
  2865. S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
  2866. << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
  2867. << D.getIdentifier();
  2868. Result.suppressDiagnostics();
  2869. }
  2870. }
  2871. if (FTI.NumParams > 0) {
  2872. // For a declaration with parameters, eg. "T var(T());", suggest adding
  2873. // parens around the first parameter to turn the declaration into a
  2874. // variable declaration.
  2875. SourceRange Range = FTI.Params[0].Param->getSourceRange();
  2876. SourceLocation B = Range.getBegin();
  2877. SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
  2878. // FIXME: Maybe we should suggest adding braces instead of parens
  2879. // in C++11 for classes that don't have an initializer_list constructor.
  2880. S.Diag(B, diag::note_additional_parens_for_variable_declaration)
  2881. << FixItHint::CreateInsertion(B, "(")
  2882. << FixItHint::CreateInsertion(E, ")");
  2883. } else {
  2884. // For a declaration without parameters, eg. "T var();", suggest replacing
  2885. // the parens with an initializer to turn the declaration into a variable
  2886. // declaration.
  2887. const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
  2888. // Empty parens mean value-initialization, and no parens mean
  2889. // default initialization. These are equivalent if the default
  2890. // constructor is user-provided or if zero-initialization is a
  2891. // no-op.
  2892. if (RD && RD->hasDefinition() &&
  2893. (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
  2894. S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
  2895. << FixItHint::CreateRemoval(ParenRange);
  2896. else {
  2897. std::string Init =
  2898. S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
  2899. if (Init.empty() && S.LangOpts.CPlusPlus11)
  2900. Init = "{}";
  2901. if (!Init.empty())
  2902. S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
  2903. << FixItHint::CreateReplacement(ParenRange, Init);
  2904. }
  2905. }
  2906. }
  2907. /// Produce an appropriate diagnostic for a declarator with top-level
  2908. /// parentheses.
  2909. static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
  2910. DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
  2911. assert(Paren.Kind == DeclaratorChunk::Paren &&
  2912. "do not have redundant top-level parentheses");
  2913. // This is a syntactic check; we're not interested in cases that arise
  2914. // during template instantiation.
  2915. if (S.inTemplateInstantiation())
  2916. return;
  2917. // Check whether this could be intended to be a construction of a temporary
  2918. // object in C++ via a function-style cast.
  2919. bool CouldBeTemporaryObject =
  2920. S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
  2921. !D.isInvalidType() && D.getIdentifier() &&
  2922. D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
  2923. (T->isRecordType() || T->isDependentType()) &&
  2924. D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
  2925. bool StartsWithDeclaratorId = true;
  2926. for (auto &C : D.type_objects()) {
  2927. switch (C.Kind) {
  2928. case DeclaratorChunk::Paren:
  2929. if (&C == &Paren)
  2930. continue;
  2931. LLVM_FALLTHROUGH;
  2932. case DeclaratorChunk::Pointer:
  2933. StartsWithDeclaratorId = false;
  2934. continue;
  2935. case DeclaratorChunk::Array:
  2936. if (!C.Arr.NumElts)
  2937. CouldBeTemporaryObject = false;
  2938. continue;
  2939. case DeclaratorChunk::Reference:
  2940. // FIXME: Suppress the warning here if there is no initializer; we're
  2941. // going to give an error anyway.
  2942. // We assume that something like 'T (&x) = y;' is highly likely to not
  2943. // be intended to be a temporary object.
  2944. CouldBeTemporaryObject = false;
  2945. StartsWithDeclaratorId = false;
  2946. continue;
  2947. case DeclaratorChunk::Function:
  2948. // In a new-type-id, function chunks require parentheses.
  2949. if (D.getContext() == DeclaratorContext::CXXNewContext)
  2950. return;
  2951. // FIXME: "A(f())" deserves a vexing-parse warning, not just a
  2952. // redundant-parens warning, but we don't know whether the function
  2953. // chunk was syntactically valid as an expression here.
  2954. CouldBeTemporaryObject = false;
  2955. continue;
  2956. case DeclaratorChunk::BlockPointer:
  2957. case DeclaratorChunk::MemberPointer:
  2958. case DeclaratorChunk::Pipe:
  2959. // These cannot appear in expressions.
  2960. CouldBeTemporaryObject = false;
  2961. StartsWithDeclaratorId = false;
  2962. continue;
  2963. }
  2964. }
  2965. // FIXME: If there is an initializer, assume that this is not intended to be
  2966. // a construction of a temporary object.
  2967. // Check whether the name has already been declared; if not, this is not a
  2968. // function-style cast.
  2969. if (CouldBeTemporaryObject) {
  2970. LookupResult Result(S, D.getIdentifier(), SourceLocation(),
  2971. Sema::LookupOrdinaryName);
  2972. if (!S.LookupName(Result, S.getCurScope()))
  2973. CouldBeTemporaryObject = false;
  2974. Result.suppressDiagnostics();
  2975. }
  2976. SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
  2977. if (!CouldBeTemporaryObject) {
  2978. // If we have A (::B), the parentheses affect the meaning of the program.
  2979. // Suppress the warning in that case. Don't bother looking at the DeclSpec
  2980. // here: even (e.g.) "int ::x" is visually ambiguous even though it's
  2981. // formally unambiguous.
  2982. if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
  2983. for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
  2984. NNS = NNS->getPrefix()) {
  2985. if (NNS->getKind() == NestedNameSpecifier::Global)
  2986. return;
  2987. }
  2988. }
  2989. S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
  2990. << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
  2991. << FixItHint::CreateRemoval(Paren.EndLoc);
  2992. return;
  2993. }
  2994. S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
  2995. << ParenRange << D.getIdentifier();
  2996. auto *RD = T->getAsCXXRecordDecl();
  2997. if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
  2998. S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
  2999. << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
  3000. << D.getIdentifier();
  3001. // FIXME: A cast to void is probably a better suggestion in cases where it's
  3002. // valid (when there is no initializer and we're not in a condition).
  3003. S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
  3004. << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
  3005. << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
  3006. S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
  3007. << FixItHint::CreateRemoval(Paren.Loc)
  3008. << FixItHint::CreateRemoval(Paren.EndLoc);
  3009. }
  3010. /// Helper for figuring out the default CC for a function declarator type. If
  3011. /// this is the outermost chunk, then we can determine the CC from the
  3012. /// declarator context. If not, then this could be either a member function
  3013. /// type or normal function type.
  3014. static CallingConv getCCForDeclaratorChunk(
  3015. Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
  3016. const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
  3017. assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
  3018. // Check for an explicit CC attribute.
  3019. for (const ParsedAttr &AL : AttrList) {
  3020. switch (AL.getKind()) {
  3021. CALLING_CONV_ATTRS_CASELIST : {
  3022. // Ignore attributes that don't validate or can't apply to the
  3023. // function type. We'll diagnose the failure to apply them in
  3024. // handleFunctionTypeAttr.
  3025. CallingConv CC;
  3026. if (!S.CheckCallingConvAttr(AL, CC) &&
  3027. (!FTI.isVariadic || supportsVariadicCall(CC))) {
  3028. return CC;
  3029. }
  3030. break;
  3031. }
  3032. default:
  3033. break;
  3034. }
  3035. }
  3036. bool IsCXXInstanceMethod = false;
  3037. if (S.getLangOpts().CPlusPlus) {
  3038. // Look inwards through parentheses to see if this chunk will form a
  3039. // member pointer type or if we're the declarator. Any type attributes
  3040. // between here and there will override the CC we choose here.
  3041. unsigned I = ChunkIndex;
  3042. bool FoundNonParen = false;
  3043. while (I && !FoundNonParen) {
  3044. --I;
  3045. if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
  3046. FoundNonParen = true;
  3047. }
  3048. if (FoundNonParen) {
  3049. // If we're not the declarator, we're a regular function type unless we're
  3050. // in a member pointer.
  3051. IsCXXInstanceMethod =
  3052. D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
  3053. } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
  3054. // This can only be a call operator for a lambda, which is an instance
  3055. // method.
  3056. IsCXXInstanceMethod = true;
  3057. } else {
  3058. // We're the innermost decl chunk, so must be a function declarator.
  3059. assert(D.isFunctionDeclarator());
  3060. // If we're inside a record, we're declaring a method, but it could be
  3061. // explicitly or implicitly static.
  3062. IsCXXInstanceMethod =
  3063. D.isFirstDeclarationOfMember() &&
  3064. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
  3065. !D.isStaticMember();
  3066. }
  3067. }
  3068. CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
  3069. IsCXXInstanceMethod);
  3070. // Attribute AT_OpenCLKernel affects the calling convention for SPIR
  3071. // and AMDGPU targets, hence it cannot be treated as a calling
  3072. // convention attribute. This is the simplest place to infer
  3073. // calling convention for OpenCL kernels.
  3074. if (S.getLangOpts().OpenCL) {
  3075. for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
  3076. if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
  3077. CC = CC_OpenCLKernel;
  3078. break;
  3079. }
  3080. }
  3081. }
  3082. return CC;
  3083. }
  3084. namespace {
  3085. /// A simple notion of pointer kinds, which matches up with the various
  3086. /// pointer declarators.
  3087. enum class SimplePointerKind {
  3088. Pointer,
  3089. BlockPointer,
  3090. MemberPointer,
  3091. Array,
  3092. };
  3093. } // end anonymous namespace
  3094. IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
  3095. switch (nullability) {
  3096. case NullabilityKind::NonNull:
  3097. if (!Ident__Nonnull)
  3098. Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
  3099. return Ident__Nonnull;
  3100. case NullabilityKind::Nullable:
  3101. if (!Ident__Nullable)
  3102. Ident__Nullable = PP.getIdentifierInfo("_Nullable");
  3103. return Ident__Nullable;
  3104. case NullabilityKind::Unspecified:
  3105. if (!Ident__Null_unspecified)
  3106. Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
  3107. return Ident__Null_unspecified;
  3108. }
  3109. llvm_unreachable("Unknown nullability kind.");
  3110. }
  3111. /// Retrieve the identifier "NSError".
  3112. IdentifierInfo *Sema::getNSErrorIdent() {
  3113. if (!Ident_NSError)
  3114. Ident_NSError = PP.getIdentifierInfo("NSError");
  3115. return Ident_NSError;
  3116. }
  3117. /// Check whether there is a nullability attribute of any kind in the given
  3118. /// attribute list.
  3119. static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
  3120. for (const ParsedAttr &AL : attrs) {
  3121. if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
  3122. AL.getKind() == ParsedAttr::AT_TypeNullable ||
  3123. AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
  3124. return true;
  3125. }
  3126. return false;
  3127. }
  3128. namespace {
  3129. /// Describes the kind of a pointer a declarator describes.
  3130. enum class PointerDeclaratorKind {
  3131. // Not a pointer.
  3132. NonPointer,
  3133. // Single-level pointer.
  3134. SingleLevelPointer,
  3135. // Multi-level pointer (of any pointer kind).
  3136. MultiLevelPointer,
  3137. // CFFooRef*
  3138. MaybePointerToCFRef,
  3139. // CFErrorRef*
  3140. CFErrorRefPointer,
  3141. // NSError**
  3142. NSErrorPointerPointer,
  3143. };
  3144. /// Describes a declarator chunk wrapping a pointer that marks inference as
  3145. /// unexpected.
  3146. // These values must be kept in sync with diagnostics.
  3147. enum class PointerWrappingDeclaratorKind {
  3148. /// Pointer is top-level.
  3149. None = -1,
  3150. /// Pointer is an array element.
  3151. Array = 0,
  3152. /// Pointer is the referent type of a C++ reference.
  3153. Reference = 1
  3154. };
  3155. } // end anonymous namespace
  3156. /// Classify the given declarator, whose type-specified is \c type, based on
  3157. /// what kind of pointer it refers to.
  3158. ///
  3159. /// This is used to determine the default nullability.
  3160. static PointerDeclaratorKind
  3161. classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
  3162. PointerWrappingDeclaratorKind &wrappingKind) {
  3163. unsigned numNormalPointers = 0;
  3164. // For any dependent type, we consider it a non-pointer.
  3165. if (type->isDependentType())
  3166. return PointerDeclaratorKind::NonPointer;
  3167. // Look through the declarator chunks to identify pointers.
  3168. for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
  3169. DeclaratorChunk &chunk = declarator.getTypeObject(i);
  3170. switch (chunk.Kind) {
  3171. case DeclaratorChunk::Array:
  3172. if (numNormalPointers == 0)
  3173. wrappingKind = PointerWrappingDeclaratorKind::Array;
  3174. break;
  3175. case DeclaratorChunk::Function:
  3176. case DeclaratorChunk::Pipe:
  3177. break;
  3178. case DeclaratorChunk::BlockPointer:
  3179. case DeclaratorChunk::MemberPointer:
  3180. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3181. : PointerDeclaratorKind::SingleLevelPointer;
  3182. case DeclaratorChunk::Paren:
  3183. break;
  3184. case DeclaratorChunk::Reference:
  3185. if (numNormalPointers == 0)
  3186. wrappingKind = PointerWrappingDeclaratorKind::Reference;
  3187. break;
  3188. case DeclaratorChunk::Pointer:
  3189. ++numNormalPointers;
  3190. if (numNormalPointers > 2)
  3191. return PointerDeclaratorKind::MultiLevelPointer;
  3192. break;
  3193. }
  3194. }
  3195. // Then, dig into the type specifier itself.
  3196. unsigned numTypeSpecifierPointers = 0;
  3197. do {
  3198. // Decompose normal pointers.
  3199. if (auto ptrType = type->getAs<PointerType>()) {
  3200. ++numNormalPointers;
  3201. if (numNormalPointers > 2)
  3202. return PointerDeclaratorKind::MultiLevelPointer;
  3203. type = ptrType->getPointeeType();
  3204. ++numTypeSpecifierPointers;
  3205. continue;
  3206. }
  3207. // Decompose block pointers.
  3208. if (type->getAs<BlockPointerType>()) {
  3209. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3210. : PointerDeclaratorKind::SingleLevelPointer;
  3211. }
  3212. // Decompose member pointers.
  3213. if (type->getAs<MemberPointerType>()) {
  3214. return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
  3215. : PointerDeclaratorKind::SingleLevelPointer;
  3216. }
  3217. // Look at Objective-C object pointers.
  3218. if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
  3219. ++numNormalPointers;
  3220. ++numTypeSpecifierPointers;
  3221. // If this is NSError**, report that.
  3222. if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
  3223. if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
  3224. numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  3225. return PointerDeclaratorKind::NSErrorPointerPointer;
  3226. }
  3227. }
  3228. break;
  3229. }
  3230. // Look at Objective-C class types.
  3231. if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
  3232. if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
  3233. if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
  3234. return PointerDeclaratorKind::NSErrorPointerPointer;
  3235. }
  3236. break;
  3237. }
  3238. // If at this point we haven't seen a pointer, we won't see one.
  3239. if (numNormalPointers == 0)
  3240. return PointerDeclaratorKind::NonPointer;
  3241. if (auto recordType = type->getAs<RecordType>()) {
  3242. RecordDecl *recordDecl = recordType->getDecl();
  3243. bool isCFError = false;
  3244. if (S.CFError) {
  3245. // If we already know about CFError, test it directly.
  3246. isCFError = (S.CFError == recordDecl);
  3247. } else {
  3248. // Check whether this is CFError, which we identify based on its bridge
  3249. // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
  3250. // now declared with "objc_bridge_mutable", so look for either one of
  3251. // the two attributes.
  3252. if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
  3253. IdentifierInfo *bridgedType = nullptr;
  3254. if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
  3255. bridgedType = bridgeAttr->getBridgedType();
  3256. else if (auto bridgeAttr =
  3257. recordDecl->getAttr<ObjCBridgeMutableAttr>())
  3258. bridgedType = bridgeAttr->getBridgedType();
  3259. if (bridgedType == S.getNSErrorIdent()) {
  3260. S.CFError = recordDecl;
  3261. isCFError = true;
  3262. }
  3263. }
  3264. }
  3265. // If this is CFErrorRef*, report it as such.
  3266. if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
  3267. return PointerDeclaratorKind::CFErrorRefPointer;
  3268. }
  3269. break;
  3270. }
  3271. break;
  3272. } while (true);
  3273. switch (numNormalPointers) {
  3274. case 0:
  3275. return PointerDeclaratorKind::NonPointer;
  3276. case 1:
  3277. return PointerDeclaratorKind::SingleLevelPointer;
  3278. case 2:
  3279. return PointerDeclaratorKind::MaybePointerToCFRef;
  3280. default:
  3281. return PointerDeclaratorKind::MultiLevelPointer;
  3282. }
  3283. }
  3284. static FileID getNullabilityCompletenessCheckFileID(Sema &S,
  3285. SourceLocation loc) {
  3286. // If we're anywhere in a function, method, or closure context, don't perform
  3287. // completeness checks.
  3288. for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
  3289. if (ctx->isFunctionOrMethod())
  3290. return FileID();
  3291. if (ctx->isFileContext())
  3292. break;
  3293. }
  3294. // We only care about the expansion location.
  3295. loc = S.SourceMgr.getExpansionLoc(loc);
  3296. FileID file = S.SourceMgr.getFileID(loc);
  3297. if (file.isInvalid())
  3298. return FileID();
  3299. // Retrieve file information.
  3300. bool invalid = false;
  3301. const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
  3302. if (invalid || !sloc.isFile())
  3303. return FileID();
  3304. // We don't want to perform completeness checks on the main file or in
  3305. // system headers.
  3306. const SrcMgr::FileInfo &fileInfo = sloc.getFile();
  3307. if (fileInfo.getIncludeLoc().isInvalid())
  3308. return FileID();
  3309. if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
  3310. S.Diags.getSuppressSystemWarnings()) {
  3311. return FileID();
  3312. }
  3313. return file;
  3314. }
  3315. /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
  3316. /// taking into account whitespace before and after.
  3317. static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
  3318. SourceLocation PointerLoc,
  3319. NullabilityKind Nullability) {
  3320. assert(PointerLoc.isValid());
  3321. if (PointerLoc.isMacroID())
  3322. return;
  3323. SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
  3324. if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
  3325. return;
  3326. const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
  3327. if (!NextChar)
  3328. return;
  3329. SmallString<32> InsertionTextBuf{" "};
  3330. InsertionTextBuf += getNullabilitySpelling(Nullability);
  3331. InsertionTextBuf += " ";
  3332. StringRef InsertionText = InsertionTextBuf.str();
  3333. if (isWhitespace(*NextChar)) {
  3334. InsertionText = InsertionText.drop_back();
  3335. } else if (NextChar[-1] == '[') {
  3336. if (NextChar[0] == ']')
  3337. InsertionText = InsertionText.drop_back().drop_front();
  3338. else
  3339. InsertionText = InsertionText.drop_front();
  3340. } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
  3341. !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
  3342. InsertionText = InsertionText.drop_back().drop_front();
  3343. }
  3344. Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
  3345. }
  3346. static void emitNullabilityConsistencyWarning(Sema &S,
  3347. SimplePointerKind PointerKind,
  3348. SourceLocation PointerLoc,
  3349. SourceLocation PointerEndLoc) {
  3350. assert(PointerLoc.isValid());
  3351. if (PointerKind == SimplePointerKind::Array) {
  3352. S.Diag(PointerLoc, diag::warn_nullability_missing_array);
  3353. } else {
  3354. S.Diag(PointerLoc, diag::warn_nullability_missing)
  3355. << static_cast<unsigned>(PointerKind);
  3356. }
  3357. auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
  3358. if (FixItLoc.isMacroID())
  3359. return;
  3360. auto addFixIt = [&](NullabilityKind Nullability) {
  3361. auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
  3362. Diag << static_cast<unsigned>(Nullability);
  3363. Diag << static_cast<unsigned>(PointerKind);
  3364. fixItNullability(S, Diag, FixItLoc, Nullability);
  3365. };
  3366. addFixIt(NullabilityKind::Nullable);
  3367. addFixIt(NullabilityKind::NonNull);
  3368. }
  3369. /// Complains about missing nullability if the file containing \p pointerLoc
  3370. /// has other uses of nullability (either the keywords or the \c assume_nonnull
  3371. /// pragma).
  3372. ///
  3373. /// If the file has \e not seen other uses of nullability, this particular
  3374. /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
  3375. static void
  3376. checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
  3377. SourceLocation pointerLoc,
  3378. SourceLocation pointerEndLoc = SourceLocation()) {
  3379. // Determine which file we're performing consistency checking for.
  3380. FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
  3381. if (file.isInvalid())
  3382. return;
  3383. // If we haven't seen any type nullability in this file, we won't warn now
  3384. // about anything.
  3385. FileNullability &fileNullability = S.NullabilityMap[file];
  3386. if (!fileNullability.SawTypeNullability) {
  3387. // If this is the first pointer declarator in the file, and the appropriate
  3388. // warning is on, record it in case we need to diagnose it retroactively.
  3389. diag::kind diagKind;
  3390. if (pointerKind == SimplePointerKind::Array)
  3391. diagKind = diag::warn_nullability_missing_array;
  3392. else
  3393. diagKind = diag::warn_nullability_missing;
  3394. if (fileNullability.PointerLoc.isInvalid() &&
  3395. !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
  3396. fileNullability.PointerLoc = pointerLoc;
  3397. fileNullability.PointerEndLoc = pointerEndLoc;
  3398. fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
  3399. }
  3400. return;
  3401. }
  3402. // Complain about missing nullability.
  3403. emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
  3404. }
  3405. /// Marks that a nullability feature has been used in the file containing
  3406. /// \p loc.
  3407. ///
  3408. /// If this file already had pointer types in it that were missing nullability,
  3409. /// the first such instance is retroactively diagnosed.
  3410. ///
  3411. /// \sa checkNullabilityConsistency
  3412. static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
  3413. FileID file = getNullabilityCompletenessCheckFileID(S, loc);
  3414. if (file.isInvalid())
  3415. return;
  3416. FileNullability &fileNullability = S.NullabilityMap[file];
  3417. if (fileNullability.SawTypeNullability)
  3418. return;
  3419. fileNullability.SawTypeNullability = true;
  3420. // If we haven't seen any type nullability before, now we have. Retroactively
  3421. // diagnose the first unannotated pointer, if there was one.
  3422. if (fileNullability.PointerLoc.isInvalid())
  3423. return;
  3424. auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
  3425. emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
  3426. fileNullability.PointerEndLoc);
  3427. }
  3428. /// Returns true if any of the declarator chunks before \p endIndex include a
  3429. /// level of indirection: array, pointer, reference, or pointer-to-member.
  3430. ///
  3431. /// Because declarator chunks are stored in outer-to-inner order, testing
  3432. /// every chunk before \p endIndex is testing all chunks that embed the current
  3433. /// chunk as part of their type.
  3434. ///
  3435. /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
  3436. /// end index, in which case all chunks are tested.
  3437. static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
  3438. unsigned i = endIndex;
  3439. while (i != 0) {
  3440. // Walk outwards along the declarator chunks.
  3441. --i;
  3442. const DeclaratorChunk &DC = D.getTypeObject(i);
  3443. switch (DC.Kind) {
  3444. case DeclaratorChunk::Paren:
  3445. break;
  3446. case DeclaratorChunk::Array:
  3447. case DeclaratorChunk::Pointer:
  3448. case DeclaratorChunk::Reference:
  3449. case DeclaratorChunk::MemberPointer:
  3450. return true;
  3451. case DeclaratorChunk::Function:
  3452. case DeclaratorChunk::BlockPointer:
  3453. case DeclaratorChunk::Pipe:
  3454. // These are invalid anyway, so just ignore.
  3455. break;
  3456. }
  3457. }
  3458. return false;
  3459. }
  3460. static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
  3461. return (Chunk.Kind == DeclaratorChunk::Pointer ||
  3462. Chunk.Kind == DeclaratorChunk::Array);
  3463. }
  3464. template<typename AttrT>
  3465. static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
  3466. AL.setUsedAsTypeAttr();
  3467. return ::new (Ctx) AttrT(Ctx, AL);
  3468. }
  3469. static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
  3470. NullabilityKind NK) {
  3471. switch (NK) {
  3472. case NullabilityKind::NonNull:
  3473. return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
  3474. case NullabilityKind::Nullable:
  3475. return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
  3476. case NullabilityKind::Unspecified:
  3477. return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
  3478. }
  3479. llvm_unreachable("unknown NullabilityKind");
  3480. }
  3481. // Diagnose whether this is a case with the multiple addr spaces.
  3482. // Returns true if this is an invalid case.
  3483. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
  3484. // by qualifiers for two or more different address spaces."
  3485. static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
  3486. LangAS ASNew,
  3487. SourceLocation AttrLoc) {
  3488. if (ASOld != LangAS::Default) {
  3489. if (ASOld != ASNew) {
  3490. S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
  3491. return true;
  3492. }
  3493. // Emit a warning if they are identical; it's likely unintended.
  3494. S.Diag(AttrLoc,
  3495. diag::warn_attribute_address_multiple_identical_qualifiers);
  3496. }
  3497. return false;
  3498. }
  3499. static TypeSourceInfo *
  3500. GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
  3501. QualType T, TypeSourceInfo *ReturnTypeInfo);
  3502. static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
  3503. QualType declSpecType,
  3504. TypeSourceInfo *TInfo) {
  3505. // The TypeSourceInfo that this function returns will not be a null type.
  3506. // If there is an error, this function will fill in a dummy type as fallback.
  3507. QualType T = declSpecType;
  3508. Declarator &D = state.getDeclarator();
  3509. Sema &S = state.getSema();
  3510. ASTContext &Context = S.Context;
  3511. const LangOptions &LangOpts = S.getLangOpts();
  3512. // The name we're declaring, if any.
  3513. DeclarationName Name;
  3514. if (D.getIdentifier())
  3515. Name = D.getIdentifier();
  3516. // Does this declaration declare a typedef-name?
  3517. bool IsTypedefName =
  3518. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
  3519. D.getContext() == DeclaratorContext::AliasDeclContext ||
  3520. D.getContext() == DeclaratorContext::AliasTemplateContext;
  3521. // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
  3522. bool IsQualifiedFunction = T->isFunctionProtoType() &&
  3523. (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
  3524. T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
  3525. // If T is 'decltype(auto)', the only declarators we can have are parens
  3526. // and at most one function declarator if this is a function declaration.
  3527. // If T is a deduced class template specialization type, we can have no
  3528. // declarator chunks at all.
  3529. if (auto *DT = T->getAs<DeducedType>()) {
  3530. const AutoType *AT = T->getAs<AutoType>();
  3531. bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
  3532. if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
  3533. for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
  3534. unsigned Index = E - I - 1;
  3535. DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
  3536. unsigned DiagId = IsClassTemplateDeduction
  3537. ? diag::err_deduced_class_template_compound_type
  3538. : diag::err_decltype_auto_compound_type;
  3539. unsigned DiagKind = 0;
  3540. switch (DeclChunk.Kind) {
  3541. case DeclaratorChunk::Paren:
  3542. // FIXME: Rejecting this is a little silly.
  3543. if (IsClassTemplateDeduction) {
  3544. DiagKind = 4;
  3545. break;
  3546. }
  3547. continue;
  3548. case DeclaratorChunk::Function: {
  3549. if (IsClassTemplateDeduction) {
  3550. DiagKind = 3;
  3551. break;
  3552. }
  3553. unsigned FnIndex;
  3554. if (D.isFunctionDeclarationContext() &&
  3555. D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
  3556. continue;
  3557. DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
  3558. break;
  3559. }
  3560. case DeclaratorChunk::Pointer:
  3561. case DeclaratorChunk::BlockPointer:
  3562. case DeclaratorChunk::MemberPointer:
  3563. DiagKind = 0;
  3564. break;
  3565. case DeclaratorChunk::Reference:
  3566. DiagKind = 1;
  3567. break;
  3568. case DeclaratorChunk::Array:
  3569. DiagKind = 2;
  3570. break;
  3571. case DeclaratorChunk::Pipe:
  3572. break;
  3573. }
  3574. S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
  3575. D.setInvalidType(true);
  3576. break;
  3577. }
  3578. }
  3579. }
  3580. // Determine whether we should infer _Nonnull on pointer types.
  3581. Optional<NullabilityKind> inferNullability;
  3582. bool inferNullabilityCS = false;
  3583. bool inferNullabilityInnerOnly = false;
  3584. bool inferNullabilityInnerOnlyComplete = false;
  3585. // Are we in an assume-nonnull region?
  3586. bool inAssumeNonNullRegion = false;
  3587. SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
  3588. if (assumeNonNullLoc.isValid()) {
  3589. inAssumeNonNullRegion = true;
  3590. recordNullabilitySeen(S, assumeNonNullLoc);
  3591. }
  3592. // Whether to complain about missing nullability specifiers or not.
  3593. enum {
  3594. /// Never complain.
  3595. CAMN_No,
  3596. /// Complain on the inner pointers (but not the outermost
  3597. /// pointer).
  3598. CAMN_InnerPointers,
  3599. /// Complain about any pointers that don't have nullability
  3600. /// specified or inferred.
  3601. CAMN_Yes
  3602. } complainAboutMissingNullability = CAMN_No;
  3603. unsigned NumPointersRemaining = 0;
  3604. auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
  3605. if (IsTypedefName) {
  3606. // For typedefs, we do not infer any nullability (the default),
  3607. // and we only complain about missing nullability specifiers on
  3608. // inner pointers.
  3609. complainAboutMissingNullability = CAMN_InnerPointers;
  3610. if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
  3611. !T->getNullability(S.Context)) {
  3612. // Note that we allow but don't require nullability on dependent types.
  3613. ++NumPointersRemaining;
  3614. }
  3615. for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
  3616. DeclaratorChunk &chunk = D.getTypeObject(i);
  3617. switch (chunk.Kind) {
  3618. case DeclaratorChunk::Array:
  3619. case DeclaratorChunk::Function:
  3620. case DeclaratorChunk::Pipe:
  3621. break;
  3622. case DeclaratorChunk::BlockPointer:
  3623. case DeclaratorChunk::MemberPointer:
  3624. ++NumPointersRemaining;
  3625. break;
  3626. case DeclaratorChunk::Paren:
  3627. case DeclaratorChunk::Reference:
  3628. continue;
  3629. case DeclaratorChunk::Pointer:
  3630. ++NumPointersRemaining;
  3631. continue;
  3632. }
  3633. }
  3634. } else {
  3635. bool isFunctionOrMethod = false;
  3636. switch (auto context = state.getDeclarator().getContext()) {
  3637. case DeclaratorContext::ObjCParameterContext:
  3638. case DeclaratorContext::ObjCResultContext:
  3639. case DeclaratorContext::PrototypeContext:
  3640. case DeclaratorContext::TrailingReturnContext:
  3641. case DeclaratorContext::TrailingReturnVarContext:
  3642. isFunctionOrMethod = true;
  3643. LLVM_FALLTHROUGH;
  3644. case DeclaratorContext::MemberContext:
  3645. if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
  3646. complainAboutMissingNullability = CAMN_No;
  3647. break;
  3648. }
  3649. // Weak properties are inferred to be nullable.
  3650. if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
  3651. inferNullability = NullabilityKind::Nullable;
  3652. break;
  3653. }
  3654. LLVM_FALLTHROUGH;
  3655. case DeclaratorContext::FileContext:
  3656. case DeclaratorContext::KNRTypeListContext: {
  3657. complainAboutMissingNullability = CAMN_Yes;
  3658. // Nullability inference depends on the type and declarator.
  3659. auto wrappingKind = PointerWrappingDeclaratorKind::None;
  3660. switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
  3661. case PointerDeclaratorKind::NonPointer:
  3662. case PointerDeclaratorKind::MultiLevelPointer:
  3663. // Cannot infer nullability.
  3664. break;
  3665. case PointerDeclaratorKind::SingleLevelPointer:
  3666. // Infer _Nonnull if we are in an assumes-nonnull region.
  3667. if (inAssumeNonNullRegion) {
  3668. complainAboutInferringWithinChunk = wrappingKind;
  3669. inferNullability = NullabilityKind::NonNull;
  3670. inferNullabilityCS =
  3671. (context == DeclaratorContext::ObjCParameterContext ||
  3672. context == DeclaratorContext::ObjCResultContext);
  3673. }
  3674. break;
  3675. case PointerDeclaratorKind::CFErrorRefPointer:
  3676. case PointerDeclaratorKind::NSErrorPointerPointer:
  3677. // Within a function or method signature, infer _Nullable at both
  3678. // levels.
  3679. if (isFunctionOrMethod && inAssumeNonNullRegion)
  3680. inferNullability = NullabilityKind::Nullable;
  3681. break;
  3682. case PointerDeclaratorKind::MaybePointerToCFRef:
  3683. if (isFunctionOrMethod) {
  3684. // On pointer-to-pointer parameters marked cf_returns_retained or
  3685. // cf_returns_not_retained, if the outer pointer is explicit then
  3686. // infer the inner pointer as _Nullable.
  3687. auto hasCFReturnsAttr =
  3688. [](const ParsedAttributesView &AttrList) -> bool {
  3689. return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
  3690. AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
  3691. };
  3692. if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
  3693. if (hasCFReturnsAttr(D.getAttributes()) ||
  3694. hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
  3695. hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
  3696. inferNullability = NullabilityKind::Nullable;
  3697. inferNullabilityInnerOnly = true;
  3698. }
  3699. }
  3700. }
  3701. break;
  3702. }
  3703. break;
  3704. }
  3705. case DeclaratorContext::ConversionIdContext:
  3706. complainAboutMissingNullability = CAMN_Yes;
  3707. break;
  3708. case DeclaratorContext::AliasDeclContext:
  3709. case DeclaratorContext::AliasTemplateContext:
  3710. case DeclaratorContext::BlockContext:
  3711. case DeclaratorContext::BlockLiteralContext:
  3712. case DeclaratorContext::ConditionContext:
  3713. case DeclaratorContext::CXXCatchContext:
  3714. case DeclaratorContext::CXXNewContext:
  3715. case DeclaratorContext::ForContext:
  3716. case DeclaratorContext::InitStmtContext:
  3717. case DeclaratorContext::LambdaExprContext:
  3718. case DeclaratorContext::LambdaExprParameterContext:
  3719. case DeclaratorContext::ObjCCatchContext:
  3720. case DeclaratorContext::TemplateParamContext:
  3721. case DeclaratorContext::TemplateArgContext:
  3722. case DeclaratorContext::TemplateTypeArgContext:
  3723. case DeclaratorContext::TypeNameContext:
  3724. case DeclaratorContext::FunctionalCastContext:
  3725. // Don't infer in these contexts.
  3726. break;
  3727. }
  3728. }
  3729. // Local function that returns true if its argument looks like a va_list.
  3730. auto isVaList = [&S](QualType T) -> bool {
  3731. auto *typedefTy = T->getAs<TypedefType>();
  3732. if (!typedefTy)
  3733. return false;
  3734. TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
  3735. do {
  3736. if (typedefTy->getDecl() == vaListTypedef)
  3737. return true;
  3738. if (auto *name = typedefTy->getDecl()->getIdentifier())
  3739. if (name->isStr("va_list"))
  3740. return true;
  3741. typedefTy = typedefTy->desugar()->getAs<TypedefType>();
  3742. } while (typedefTy);
  3743. return false;
  3744. };
  3745. // Local function that checks the nullability for a given pointer declarator.
  3746. // Returns true if _Nonnull was inferred.
  3747. auto inferPointerNullability =
  3748. [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
  3749. SourceLocation pointerEndLoc,
  3750. ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
  3751. // We've seen a pointer.
  3752. if (NumPointersRemaining > 0)
  3753. --NumPointersRemaining;
  3754. // If a nullability attribute is present, there's nothing to do.
  3755. if (hasNullabilityAttr(attrs))
  3756. return nullptr;
  3757. // If we're supposed to infer nullability, do so now.
  3758. if (inferNullability && !inferNullabilityInnerOnlyComplete) {
  3759. ParsedAttr::Syntax syntax = inferNullabilityCS
  3760. ? ParsedAttr::AS_ContextSensitiveKeyword
  3761. : ParsedAttr::AS_Keyword;
  3762. ParsedAttr *nullabilityAttr = Pool.create(
  3763. S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
  3764. nullptr, SourceLocation(), nullptr, 0, syntax);
  3765. attrs.addAtEnd(nullabilityAttr);
  3766. if (inferNullabilityCS) {
  3767. state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
  3768. ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
  3769. }
  3770. if (pointerLoc.isValid() &&
  3771. complainAboutInferringWithinChunk !=
  3772. PointerWrappingDeclaratorKind::None) {
  3773. auto Diag =
  3774. S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
  3775. Diag << static_cast<int>(complainAboutInferringWithinChunk);
  3776. fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
  3777. }
  3778. if (inferNullabilityInnerOnly)
  3779. inferNullabilityInnerOnlyComplete = true;
  3780. return nullabilityAttr;
  3781. }
  3782. // If we're supposed to complain about missing nullability, do so
  3783. // now if it's truly missing.
  3784. switch (complainAboutMissingNullability) {
  3785. case CAMN_No:
  3786. break;
  3787. case CAMN_InnerPointers:
  3788. if (NumPointersRemaining == 0)
  3789. break;
  3790. LLVM_FALLTHROUGH;
  3791. case CAMN_Yes:
  3792. checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
  3793. }
  3794. return nullptr;
  3795. };
  3796. // If the type itself could have nullability but does not, infer pointer
  3797. // nullability and perform consistency checking.
  3798. if (S.CodeSynthesisContexts.empty()) {
  3799. if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
  3800. !T->getNullability(S.Context)) {
  3801. if (isVaList(T)) {
  3802. // Record that we've seen a pointer, but do nothing else.
  3803. if (NumPointersRemaining > 0)
  3804. --NumPointersRemaining;
  3805. } else {
  3806. SimplePointerKind pointerKind = SimplePointerKind::Pointer;
  3807. if (T->isBlockPointerType())
  3808. pointerKind = SimplePointerKind::BlockPointer;
  3809. else if (T->isMemberPointerType())
  3810. pointerKind = SimplePointerKind::MemberPointer;
  3811. if (auto *attr = inferPointerNullability(
  3812. pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
  3813. D.getDeclSpec().getEndLoc(),
  3814. D.getMutableDeclSpec().getAttributes(),
  3815. D.getMutableDeclSpec().getAttributePool())) {
  3816. T = state.getAttributedType(
  3817. createNullabilityAttr(Context, *attr, *inferNullability), T, T);
  3818. }
  3819. }
  3820. }
  3821. if (complainAboutMissingNullability == CAMN_Yes &&
  3822. T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
  3823. D.isPrototypeContext() &&
  3824. !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
  3825. checkNullabilityConsistency(S, SimplePointerKind::Array,
  3826. D.getDeclSpec().getTypeSpecTypeLoc());
  3827. }
  3828. }
  3829. bool ExpectNoDerefChunk =
  3830. state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
  3831. // Walk the DeclTypeInfo, building the recursive type as we go.
  3832. // DeclTypeInfos are ordered from the identifier out, which is
  3833. // opposite of what we want :).
  3834. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  3835. unsigned chunkIndex = e - i - 1;
  3836. state.setCurrentChunkIndex(chunkIndex);
  3837. DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
  3838. IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
  3839. switch (DeclType.Kind) {
  3840. case DeclaratorChunk::Paren:
  3841. if (i == 0)
  3842. warnAboutRedundantParens(S, D, T);
  3843. T = S.BuildParenType(T);
  3844. break;
  3845. case DeclaratorChunk::BlockPointer:
  3846. // If blocks are disabled, emit an error.
  3847. if (!LangOpts.Blocks)
  3848. S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
  3849. // Handle pointer nullability.
  3850. inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
  3851. DeclType.EndLoc, DeclType.getAttrs(),
  3852. state.getDeclarator().getAttributePool());
  3853. T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
  3854. if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
  3855. // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
  3856. // qualified with const.
  3857. if (LangOpts.OpenCL)
  3858. DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
  3859. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
  3860. }
  3861. break;
  3862. case DeclaratorChunk::Pointer:
  3863. // Verify that we're not building a pointer to pointer to function with
  3864. // exception specification.
  3865. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3866. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3867. D.setInvalidType(true);
  3868. // Build the type anyway.
  3869. }
  3870. // Handle pointer nullability
  3871. inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
  3872. DeclType.EndLoc, DeclType.getAttrs(),
  3873. state.getDeclarator().getAttributePool());
  3874. if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
  3875. T = Context.getObjCObjectPointerType(T);
  3876. if (DeclType.Ptr.TypeQuals)
  3877. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3878. break;
  3879. }
  3880. // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
  3881. // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
  3882. // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
  3883. if (LangOpts.OpenCL) {
  3884. if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
  3885. T->isBlockPointerType()) {
  3886. S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
  3887. D.setInvalidType(true);
  3888. }
  3889. }
  3890. T = S.BuildPointerType(T, DeclType.Loc, Name);
  3891. if (DeclType.Ptr.TypeQuals)
  3892. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
  3893. break;
  3894. case DeclaratorChunk::Reference: {
  3895. // Verify that we're not building a reference to pointer to function with
  3896. // exception specification.
  3897. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3898. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3899. D.setInvalidType(true);
  3900. // Build the type anyway.
  3901. }
  3902. T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
  3903. if (DeclType.Ref.HasRestrict)
  3904. T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
  3905. break;
  3906. }
  3907. case DeclaratorChunk::Array: {
  3908. // Verify that we're not building an array of pointers to function with
  3909. // exception specification.
  3910. if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
  3911. S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
  3912. D.setInvalidType(true);
  3913. // Build the type anyway.
  3914. }
  3915. DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
  3916. Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
  3917. ArrayType::ArraySizeModifier ASM;
  3918. if (ATI.isStar)
  3919. ASM = ArrayType::Star;
  3920. else if (ATI.hasStatic)
  3921. ASM = ArrayType::Static;
  3922. else
  3923. ASM = ArrayType::Normal;
  3924. if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
  3925. // FIXME: This check isn't quite right: it allows star in prototypes
  3926. // for function definitions, and disallows some edge cases detailed
  3927. // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
  3928. S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
  3929. ASM = ArrayType::Normal;
  3930. D.setInvalidType(true);
  3931. }
  3932. // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
  3933. // shall appear only in a declaration of a function parameter with an
  3934. // array type, ...
  3935. if (ASM == ArrayType::Static || ATI.TypeQuals) {
  3936. if (!(D.isPrototypeContext() ||
  3937. D.getContext() == DeclaratorContext::KNRTypeListContext)) {
  3938. S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
  3939. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3940. // Remove the 'static' and the type qualifiers.
  3941. if (ASM == ArrayType::Static)
  3942. ASM = ArrayType::Normal;
  3943. ATI.TypeQuals = 0;
  3944. D.setInvalidType(true);
  3945. }
  3946. // C99 6.7.5.2p1: ... and then only in the outermost array type
  3947. // derivation.
  3948. if (hasOuterPointerLikeChunk(D, chunkIndex)) {
  3949. S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
  3950. (ASM == ArrayType::Static ? "'static'" : "type qualifier");
  3951. if (ASM == ArrayType::Static)
  3952. ASM = ArrayType::Normal;
  3953. ATI.TypeQuals = 0;
  3954. D.setInvalidType(true);
  3955. }
  3956. }
  3957. const AutoType *AT = T->getContainedAutoType();
  3958. // Allow arrays of auto if we are a generic lambda parameter.
  3959. // i.e. [](auto (&array)[5]) { return array[0]; }; OK
  3960. if (AT &&
  3961. D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
  3962. // We've already diagnosed this for decltype(auto).
  3963. if (!AT->isDecltypeAuto())
  3964. S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
  3965. << getPrintableNameForEntity(Name) << T;
  3966. T = QualType();
  3967. break;
  3968. }
  3969. // Array parameters can be marked nullable as well, although it's not
  3970. // necessary if they're marked 'static'.
  3971. if (complainAboutMissingNullability == CAMN_Yes &&
  3972. !hasNullabilityAttr(DeclType.getAttrs()) &&
  3973. ASM != ArrayType::Static &&
  3974. D.isPrototypeContext() &&
  3975. !hasOuterPointerLikeChunk(D, chunkIndex)) {
  3976. checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
  3977. }
  3978. T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
  3979. SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
  3980. break;
  3981. }
  3982. case DeclaratorChunk::Function: {
  3983. // If the function declarator has a prototype (i.e. it is not () and
  3984. // does not have a K&R-style identifier list), then the arguments are part
  3985. // of the type, otherwise the argument list is ().
  3986. DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  3987. IsQualifiedFunction =
  3988. FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
  3989. // Check for auto functions and trailing return type and adjust the
  3990. // return type accordingly.
  3991. if (!D.isInvalidType()) {
  3992. // trailing-return-type is only required if we're declaring a function,
  3993. // and not, for instance, a pointer to a function.
  3994. if (D.getDeclSpec().hasAutoTypeSpec() &&
  3995. !FTI.hasTrailingReturnType() && chunkIndex == 0) {
  3996. if (!S.getLangOpts().CPlusPlus14) {
  3997. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  3998. D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
  3999. ? diag::err_auto_missing_trailing_return
  4000. : diag::err_deduced_return_type);
  4001. T = Context.IntTy;
  4002. D.setInvalidType(true);
  4003. } else {
  4004. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  4005. diag::warn_cxx11_compat_deduced_return_type);
  4006. }
  4007. } else if (FTI.hasTrailingReturnType()) {
  4008. // T must be exactly 'auto' at this point. See CWG issue 681.
  4009. if (isa<ParenType>(T)) {
  4010. S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
  4011. << T << D.getSourceRange();
  4012. D.setInvalidType(true);
  4013. } else if (D.getName().getKind() ==
  4014. UnqualifiedIdKind::IK_DeductionGuideName) {
  4015. if (T != Context.DependentTy) {
  4016. S.Diag(D.getDeclSpec().getBeginLoc(),
  4017. diag::err_deduction_guide_with_complex_decl)
  4018. << D.getSourceRange();
  4019. D.setInvalidType(true);
  4020. }
  4021. } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
  4022. (T.hasQualifiers() || !isa<AutoType>(T) ||
  4023. cast<AutoType>(T)->getKeyword() !=
  4024. AutoTypeKeyword::Auto)) {
  4025. S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
  4026. diag::err_trailing_return_without_auto)
  4027. << T << D.getDeclSpec().getSourceRange();
  4028. D.setInvalidType(true);
  4029. }
  4030. T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
  4031. if (T.isNull()) {
  4032. // An error occurred parsing the trailing return type.
  4033. T = Context.IntTy;
  4034. D.setInvalidType(true);
  4035. }
  4036. } else {
  4037. // This function type is not the type of the entity being declared,
  4038. // so checking the 'auto' is not the responsibility of this chunk.
  4039. }
  4040. }
  4041. // C99 6.7.5.3p1: The return type may not be a function or array type.
  4042. // For conversion functions, we'll diagnose this particular error later.
  4043. if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
  4044. (D.getName().getKind() !=
  4045. UnqualifiedIdKind::IK_ConversionFunctionId)) {
  4046. unsigned diagID = diag::err_func_returning_array_function;
  4047. // Last processing chunk in block context means this function chunk
  4048. // represents the block.
  4049. if (chunkIndex == 0 &&
  4050. D.getContext() == DeclaratorContext::BlockLiteralContext)
  4051. diagID = diag::err_block_returning_array_function;
  4052. S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
  4053. T = Context.IntTy;
  4054. D.setInvalidType(true);
  4055. }
  4056. // Do not allow returning half FP value.
  4057. // FIXME: This really should be in BuildFunctionType.
  4058. if (T->isHalfType()) {
  4059. if (S.getLangOpts().OpenCL) {
  4060. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  4061. S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
  4062. << T << 0 /*pointer hint*/;
  4063. D.setInvalidType(true);
  4064. }
  4065. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  4066. S.Diag(D.getIdentifierLoc(),
  4067. diag::err_parameters_retval_cannot_have_fp16_type) << 1;
  4068. D.setInvalidType(true);
  4069. }
  4070. }
  4071. if (LangOpts.OpenCL) {
  4072. // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
  4073. // function.
  4074. if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
  4075. T->isPipeType()) {
  4076. S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
  4077. << T << 1 /*hint off*/;
  4078. D.setInvalidType(true);
  4079. }
  4080. // OpenCL doesn't support variadic functions and blocks
  4081. // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
  4082. // We also allow here any toolchain reserved identifiers.
  4083. if (FTI.isVariadic &&
  4084. !(D.getIdentifier() &&
  4085. ((D.getIdentifier()->getName() == "printf" &&
  4086. (LangOpts.OpenCLCPlusPlus || LangOpts.OpenCLVersion >= 120)) ||
  4087. D.getIdentifier()->getName().startswith("__")))) {
  4088. S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
  4089. D.setInvalidType(true);
  4090. }
  4091. }
  4092. // Methods cannot return interface types. All ObjC objects are
  4093. // passed by reference.
  4094. if (T->isObjCObjectType()) {
  4095. SourceLocation DiagLoc, FixitLoc;
  4096. if (TInfo) {
  4097. DiagLoc = TInfo->getTypeLoc().getBeginLoc();
  4098. FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
  4099. } else {
  4100. DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
  4101. FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
  4102. }
  4103. S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
  4104. << 0 << T
  4105. << FixItHint::CreateInsertion(FixitLoc, "*");
  4106. T = Context.getObjCObjectPointerType(T);
  4107. if (TInfo) {
  4108. TypeLocBuilder TLB;
  4109. TLB.pushFullCopy(TInfo->getTypeLoc());
  4110. ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
  4111. TLoc.setStarLoc(FixitLoc);
  4112. TInfo = TLB.getTypeSourceInfo(Context, T);
  4113. }
  4114. D.setInvalidType(true);
  4115. }
  4116. // cv-qualifiers on return types are pointless except when the type is a
  4117. // class type in C++.
  4118. if ((T.getCVRQualifiers() || T->isAtomicType()) &&
  4119. !(S.getLangOpts().CPlusPlus &&
  4120. (T->isDependentType() || T->isRecordType()))) {
  4121. if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
  4122. D.getFunctionDefinitionKind() == FDK_Definition) {
  4123. // [6.9.1/3] qualified void return is invalid on a C
  4124. // function definition. Apparently ok on declarations and
  4125. // in C++ though (!)
  4126. S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
  4127. } else
  4128. diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
  4129. // C++2a [dcl.fct]p12:
  4130. // A volatile-qualified return type is deprecated
  4131. if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus2a)
  4132. S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
  4133. }
  4134. // Objective-C ARC ownership qualifiers are ignored on the function
  4135. // return type (by type canonicalization). Complain if this attribute
  4136. // was written here.
  4137. if (T.getQualifiers().hasObjCLifetime()) {
  4138. SourceLocation AttrLoc;
  4139. if (chunkIndex + 1 < D.getNumTypeObjects()) {
  4140. DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
  4141. for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
  4142. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
  4143. AttrLoc = AL.getLoc();
  4144. break;
  4145. }
  4146. }
  4147. }
  4148. if (AttrLoc.isInvalid()) {
  4149. for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
  4150. if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
  4151. AttrLoc = AL.getLoc();
  4152. break;
  4153. }
  4154. }
  4155. }
  4156. if (AttrLoc.isValid()) {
  4157. // The ownership attributes are almost always written via
  4158. // the predefined
  4159. // __strong/__weak/__autoreleasing/__unsafe_unretained.
  4160. if (AttrLoc.isMacroID())
  4161. AttrLoc =
  4162. S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
  4163. S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
  4164. << T.getQualifiers().getObjCLifetime();
  4165. }
  4166. }
  4167. if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
  4168. // C++ [dcl.fct]p6:
  4169. // Types shall not be defined in return or parameter types.
  4170. TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
  4171. S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
  4172. << Context.getTypeDeclType(Tag);
  4173. }
  4174. // Exception specs are not allowed in typedefs. Complain, but add it
  4175. // anyway.
  4176. if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
  4177. S.Diag(FTI.getExceptionSpecLocBeg(),
  4178. diag::err_exception_spec_in_typedef)
  4179. << (D.getContext() == DeclaratorContext::AliasDeclContext ||
  4180. D.getContext() == DeclaratorContext::AliasTemplateContext);
  4181. // If we see "T var();" or "T var(T());" at block scope, it is probably
  4182. // an attempt to initialize a variable, not a function declaration.
  4183. if (FTI.isAmbiguous)
  4184. warnAboutAmbiguousFunction(S, D, DeclType, T);
  4185. FunctionType::ExtInfo EI(
  4186. getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
  4187. if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
  4188. && !LangOpts.OpenCL) {
  4189. // Simple void foo(), where the incoming T is the result type.
  4190. T = Context.getFunctionNoProtoType(T, EI);
  4191. } else {
  4192. // We allow a zero-parameter variadic function in C if the
  4193. // function is marked with the "overloadable" attribute. Scan
  4194. // for this attribute now.
  4195. if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
  4196. if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
  4197. S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
  4198. if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
  4199. // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
  4200. // definition.
  4201. S.Diag(FTI.Params[0].IdentLoc,
  4202. diag::err_ident_list_in_fn_declaration);
  4203. D.setInvalidType(true);
  4204. // Recover by creating a K&R-style function type.
  4205. T = Context.getFunctionNoProtoType(T, EI);
  4206. break;
  4207. }
  4208. FunctionProtoType::ExtProtoInfo EPI;
  4209. EPI.ExtInfo = EI;
  4210. EPI.Variadic = FTI.isVariadic;
  4211. EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
  4212. EPI.TypeQuals.addCVRUQualifiers(
  4213. FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
  4214. : 0);
  4215. EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
  4216. : FTI.RefQualifierIsLValueRef? RQ_LValue
  4217. : RQ_RValue;
  4218. // Otherwise, we have a function with a parameter list that is
  4219. // potentially variadic.
  4220. SmallVector<QualType, 16> ParamTys;
  4221. ParamTys.reserve(FTI.NumParams);
  4222. SmallVector<FunctionProtoType::ExtParameterInfo, 16>
  4223. ExtParameterInfos(FTI.NumParams);
  4224. bool HasAnyInterestingExtParameterInfos = false;
  4225. for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
  4226. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  4227. QualType ParamTy = Param->getType();
  4228. assert(!ParamTy.isNull() && "Couldn't parse type?");
  4229. // Look for 'void'. void is allowed only as a single parameter to a
  4230. // function with no other parameters (C99 6.7.5.3p10). We record
  4231. // int(void) as a FunctionProtoType with an empty parameter list.
  4232. if (ParamTy->isVoidType()) {
  4233. // If this is something like 'float(int, void)', reject it. 'void'
  4234. // is an incomplete type (C99 6.2.5p19) and function decls cannot
  4235. // have parameters of incomplete type.
  4236. if (FTI.NumParams != 1 || FTI.isVariadic) {
  4237. S.Diag(DeclType.Loc, diag::err_void_only_param);
  4238. ParamTy = Context.IntTy;
  4239. Param->setType(ParamTy);
  4240. } else if (FTI.Params[i].Ident) {
  4241. // Reject, but continue to parse 'int(void abc)'.
  4242. S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
  4243. ParamTy = Context.IntTy;
  4244. Param->setType(ParamTy);
  4245. } else {
  4246. // Reject, but continue to parse 'float(const void)'.
  4247. if (ParamTy.hasQualifiers())
  4248. S.Diag(DeclType.Loc, diag::err_void_param_qualified);
  4249. // Do not add 'void' to the list.
  4250. break;
  4251. }
  4252. } else if (ParamTy->isHalfType()) {
  4253. // Disallow half FP parameters.
  4254. // FIXME: This really should be in BuildFunctionType.
  4255. if (S.getLangOpts().OpenCL) {
  4256. if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
  4257. S.Diag(Param->getLocation(),
  4258. diag::err_opencl_half_param) << ParamTy;
  4259. D.setInvalidType();
  4260. Param->setInvalidDecl();
  4261. }
  4262. } else if (!S.getLangOpts().HalfArgsAndReturns) {
  4263. S.Diag(Param->getLocation(),
  4264. diag::err_parameters_retval_cannot_have_fp16_type) << 0;
  4265. D.setInvalidType();
  4266. }
  4267. } else if (!FTI.hasPrototype) {
  4268. if (ParamTy->isPromotableIntegerType()) {
  4269. ParamTy = Context.getPromotedIntegerType(ParamTy);
  4270. Param->setKNRPromoted(true);
  4271. } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
  4272. if (BTy->getKind() == BuiltinType::Float) {
  4273. ParamTy = Context.DoubleTy;
  4274. Param->setKNRPromoted(true);
  4275. }
  4276. }
  4277. }
  4278. if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
  4279. ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
  4280. HasAnyInterestingExtParameterInfos = true;
  4281. }
  4282. if (auto attr = Param->getAttr<ParameterABIAttr>()) {
  4283. ExtParameterInfos[i] =
  4284. ExtParameterInfos[i].withABI(attr->getABI());
  4285. HasAnyInterestingExtParameterInfos = true;
  4286. }
  4287. if (Param->hasAttr<PassObjectSizeAttr>()) {
  4288. ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
  4289. HasAnyInterestingExtParameterInfos = true;
  4290. }
  4291. if (Param->hasAttr<NoEscapeAttr>()) {
  4292. ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
  4293. HasAnyInterestingExtParameterInfos = true;
  4294. }
  4295. ParamTys.push_back(ParamTy);
  4296. }
  4297. if (HasAnyInterestingExtParameterInfos) {
  4298. EPI.ExtParameterInfos = ExtParameterInfos.data();
  4299. checkExtParameterInfos(S, ParamTys, EPI,
  4300. [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
  4301. }
  4302. SmallVector<QualType, 4> Exceptions;
  4303. SmallVector<ParsedType, 2> DynamicExceptions;
  4304. SmallVector<SourceRange, 2> DynamicExceptionRanges;
  4305. Expr *NoexceptExpr = nullptr;
  4306. if (FTI.getExceptionSpecType() == EST_Dynamic) {
  4307. // FIXME: It's rather inefficient to have to split into two vectors
  4308. // here.
  4309. unsigned N = FTI.getNumExceptions();
  4310. DynamicExceptions.reserve(N);
  4311. DynamicExceptionRanges.reserve(N);
  4312. for (unsigned I = 0; I != N; ++I) {
  4313. DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
  4314. DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
  4315. }
  4316. } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
  4317. NoexceptExpr = FTI.NoexceptExpr;
  4318. }
  4319. S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
  4320. FTI.getExceptionSpecType(),
  4321. DynamicExceptions,
  4322. DynamicExceptionRanges,
  4323. NoexceptExpr,
  4324. Exceptions,
  4325. EPI.ExceptionSpec);
  4326. // FIXME: Set address space from attrs for C++ mode here.
  4327. // OpenCLCPlusPlus: A class member function has an address space.
  4328. auto IsClassMember = [&]() {
  4329. return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
  4330. state.getDeclarator()
  4331. .getCXXScopeSpec()
  4332. .getScopeRep()
  4333. ->getKind() == NestedNameSpecifier::TypeSpec) ||
  4334. state.getDeclarator().getContext() ==
  4335. DeclaratorContext::MemberContext;
  4336. };
  4337. if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
  4338. LangAS ASIdx = LangAS::Default;
  4339. // Take address space attr if any and mark as invalid to avoid adding
  4340. // them later while creating QualType.
  4341. if (FTI.MethodQualifiers)
  4342. for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
  4343. LangAS ASIdxNew = attr.asOpenCLLangAS();
  4344. if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
  4345. attr.getLoc()))
  4346. D.setInvalidType(true);
  4347. else
  4348. ASIdx = ASIdxNew;
  4349. }
  4350. // If a class member function's address space is not set, set it to
  4351. // __generic.
  4352. LangAS AS =
  4353. (ASIdx == LangAS::Default ? LangAS::opencl_generic : ASIdx);
  4354. EPI.TypeQuals.addAddressSpace(AS);
  4355. }
  4356. T = Context.getFunctionType(T, ParamTys, EPI);
  4357. }
  4358. break;
  4359. }
  4360. case DeclaratorChunk::MemberPointer: {
  4361. // The scope spec must refer to a class, or be dependent.
  4362. CXXScopeSpec &SS = DeclType.Mem.Scope();
  4363. QualType ClsType;
  4364. // Handle pointer nullability.
  4365. inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
  4366. DeclType.EndLoc, DeclType.getAttrs(),
  4367. state.getDeclarator().getAttributePool());
  4368. if (SS.isInvalid()) {
  4369. // Avoid emitting extra errors if we already errored on the scope.
  4370. D.setInvalidType(true);
  4371. } else if (S.isDependentScopeSpecifier(SS) ||
  4372. dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
  4373. NestedNameSpecifier *NNS = SS.getScopeRep();
  4374. NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
  4375. switch (NNS->getKind()) {
  4376. case NestedNameSpecifier::Identifier:
  4377. ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
  4378. NNS->getAsIdentifier());
  4379. break;
  4380. case NestedNameSpecifier::Namespace:
  4381. case NestedNameSpecifier::NamespaceAlias:
  4382. case NestedNameSpecifier::Global:
  4383. case NestedNameSpecifier::Super:
  4384. llvm_unreachable("Nested-name-specifier must name a type");
  4385. case NestedNameSpecifier::TypeSpec:
  4386. case NestedNameSpecifier::TypeSpecWithTemplate:
  4387. ClsType = QualType(NNS->getAsType(), 0);
  4388. // Note: if the NNS has a prefix and ClsType is a nondependent
  4389. // TemplateSpecializationType, then the NNS prefix is NOT included
  4390. // in ClsType; hence we wrap ClsType into an ElaboratedType.
  4391. // NOTE: in particular, no wrap occurs if ClsType already is an
  4392. // Elaborated, DependentName, or DependentTemplateSpecialization.
  4393. if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
  4394. ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
  4395. break;
  4396. }
  4397. } else {
  4398. S.Diag(DeclType.Mem.Scope().getBeginLoc(),
  4399. diag::err_illegal_decl_mempointer_in_nonclass)
  4400. << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
  4401. << DeclType.Mem.Scope().getRange();
  4402. D.setInvalidType(true);
  4403. }
  4404. if (!ClsType.isNull())
  4405. T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
  4406. D.getIdentifier());
  4407. if (T.isNull()) {
  4408. T = Context.IntTy;
  4409. D.setInvalidType(true);
  4410. } else if (DeclType.Mem.TypeQuals) {
  4411. T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
  4412. }
  4413. break;
  4414. }
  4415. case DeclaratorChunk::Pipe: {
  4416. T = S.BuildReadPipeType(T, DeclType.Loc);
  4417. processTypeAttrs(state, T, TAL_DeclSpec,
  4418. D.getMutableDeclSpec().getAttributes());
  4419. break;
  4420. }
  4421. }
  4422. if (T.isNull()) {
  4423. D.setInvalidType(true);
  4424. T = Context.IntTy;
  4425. }
  4426. // See if there are any attributes on this declarator chunk.
  4427. processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
  4428. if (DeclType.Kind != DeclaratorChunk::Paren) {
  4429. if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
  4430. S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
  4431. ExpectNoDerefChunk = state.didParseNoDeref();
  4432. }
  4433. }
  4434. if (ExpectNoDerefChunk)
  4435. S.Diag(state.getDeclarator().getBeginLoc(),
  4436. diag::warn_noderef_on_non_pointer_or_array);
  4437. // GNU warning -Wstrict-prototypes
  4438. // Warn if a function declaration is without a prototype.
  4439. // This warning is issued for all kinds of unprototyped function
  4440. // declarations (i.e. function type typedef, function pointer etc.)
  4441. // C99 6.7.5.3p14:
  4442. // The empty list in a function declarator that is not part of a definition
  4443. // of that function specifies that no information about the number or types
  4444. // of the parameters is supplied.
  4445. if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
  4446. bool IsBlock = false;
  4447. for (const DeclaratorChunk &DeclType : D.type_objects()) {
  4448. switch (DeclType.Kind) {
  4449. case DeclaratorChunk::BlockPointer:
  4450. IsBlock = true;
  4451. break;
  4452. case DeclaratorChunk::Function: {
  4453. const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
  4454. // We supress the warning when there's no LParen location, as this
  4455. // indicates the declaration was an implicit declaration, which gets
  4456. // warned about separately via -Wimplicit-function-declaration.
  4457. if (FTI.NumParams == 0 && !FTI.isVariadic && FTI.getLParenLoc().isValid())
  4458. S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
  4459. << IsBlock
  4460. << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
  4461. IsBlock = false;
  4462. break;
  4463. }
  4464. default:
  4465. break;
  4466. }
  4467. }
  4468. }
  4469. assert(!T.isNull() && "T must not be null after this point");
  4470. if (LangOpts.CPlusPlus && T->isFunctionType()) {
  4471. const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
  4472. assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
  4473. // C++ 8.3.5p4:
  4474. // A cv-qualifier-seq shall only be part of the function type
  4475. // for a nonstatic member function, the function type to which a pointer
  4476. // to member refers, or the top-level function type of a function typedef
  4477. // declaration.
  4478. //
  4479. // Core issue 547 also allows cv-qualifiers on function types that are
  4480. // top-level template type arguments.
  4481. enum { NonMember, Member, DeductionGuide } Kind = NonMember;
  4482. if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
  4483. Kind = DeductionGuide;
  4484. else if (!D.getCXXScopeSpec().isSet()) {
  4485. if ((D.getContext() == DeclaratorContext::MemberContext ||
  4486. D.getContext() == DeclaratorContext::LambdaExprContext) &&
  4487. !D.getDeclSpec().isFriendSpecified())
  4488. Kind = Member;
  4489. } else {
  4490. DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
  4491. if (!DC || DC->isRecord())
  4492. Kind = Member;
  4493. }
  4494. // C++11 [dcl.fct]p6 (w/DR1417):
  4495. // An attempt to specify a function type with a cv-qualifier-seq or a
  4496. // ref-qualifier (including by typedef-name) is ill-formed unless it is:
  4497. // - the function type for a non-static member function,
  4498. // - the function type to which a pointer to member refers,
  4499. // - the top-level function type of a function typedef declaration or
  4500. // alias-declaration,
  4501. // - the type-id in the default argument of a type-parameter, or
  4502. // - the type-id of a template-argument for a type-parameter
  4503. //
  4504. // FIXME: Checking this here is insufficient. We accept-invalid on:
  4505. //
  4506. // template<typename T> struct S { void f(T); };
  4507. // S<int() const> s;
  4508. //
  4509. // ... for instance.
  4510. if (IsQualifiedFunction &&
  4511. !(Kind == Member &&
  4512. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
  4513. !IsTypedefName &&
  4514. D.getContext() != DeclaratorContext::TemplateArgContext &&
  4515. D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
  4516. SourceLocation Loc = D.getBeginLoc();
  4517. SourceRange RemovalRange;
  4518. unsigned I;
  4519. if (D.isFunctionDeclarator(I)) {
  4520. SmallVector<SourceLocation, 4> RemovalLocs;
  4521. const DeclaratorChunk &Chunk = D.getTypeObject(I);
  4522. assert(Chunk.Kind == DeclaratorChunk::Function);
  4523. if (Chunk.Fun.hasRefQualifier())
  4524. RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
  4525. if (Chunk.Fun.hasMethodTypeQualifiers())
  4526. Chunk.Fun.MethodQualifiers->forEachQualifier(
  4527. [&](DeclSpec::TQ TypeQual, StringRef QualName,
  4528. SourceLocation SL) { RemovalLocs.push_back(SL); });
  4529. if (!RemovalLocs.empty()) {
  4530. llvm::sort(RemovalLocs,
  4531. BeforeThanCompare<SourceLocation>(S.getSourceManager()));
  4532. RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
  4533. Loc = RemovalLocs.front();
  4534. }
  4535. }
  4536. S.Diag(Loc, diag::err_invalid_qualified_function_type)
  4537. << Kind << D.isFunctionDeclarator() << T
  4538. << getFunctionQualifiersAsString(FnTy)
  4539. << FixItHint::CreateRemoval(RemovalRange);
  4540. // Strip the cv-qualifiers and ref-qualifiers from the type.
  4541. FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
  4542. EPI.TypeQuals.removeCVRQualifiers();
  4543. EPI.RefQualifier = RQ_None;
  4544. T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
  4545. EPI);
  4546. // Rebuild any parens around the identifier in the function type.
  4547. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  4548. if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
  4549. break;
  4550. T = S.BuildParenType(T);
  4551. }
  4552. }
  4553. }
  4554. // Apply any undistributed attributes from the declarator.
  4555. processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
  4556. // Diagnose any ignored type attributes.
  4557. state.diagnoseIgnoredTypeAttrs(T);
  4558. // C++0x [dcl.constexpr]p9:
  4559. // A constexpr specifier used in an object declaration declares the object
  4560. // as const.
  4561. if (D.getDeclSpec().getConstexprSpecifier() == CSK_constexpr &&
  4562. T->isObjectType())
  4563. T.addConst();
  4564. // C++2a [dcl.fct]p4:
  4565. // A parameter with volatile-qualified type is deprecated
  4566. if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus2a &&
  4567. (D.getContext() == DeclaratorContext::PrototypeContext ||
  4568. D.getContext() == DeclaratorContext::LambdaExprParameterContext))
  4569. S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
  4570. // If there was an ellipsis in the declarator, the declaration declares a
  4571. // parameter pack whose type may be a pack expansion type.
  4572. if (D.hasEllipsis()) {
  4573. // C++0x [dcl.fct]p13:
  4574. // A declarator-id or abstract-declarator containing an ellipsis shall
  4575. // only be used in a parameter-declaration. Such a parameter-declaration
  4576. // is a parameter pack (14.5.3). [...]
  4577. switch (D.getContext()) {
  4578. case DeclaratorContext::PrototypeContext:
  4579. case DeclaratorContext::LambdaExprParameterContext:
  4580. // C++0x [dcl.fct]p13:
  4581. // [...] When it is part of a parameter-declaration-clause, the
  4582. // parameter pack is a function parameter pack (14.5.3). The type T
  4583. // of the declarator-id of the function parameter pack shall contain
  4584. // a template parameter pack; each template parameter pack in T is
  4585. // expanded by the function parameter pack.
  4586. //
  4587. // We represent function parameter packs as function parameters whose
  4588. // type is a pack expansion.
  4589. if (!T->containsUnexpandedParameterPack()) {
  4590. S.Diag(D.getEllipsisLoc(),
  4591. diag::err_function_parameter_pack_without_parameter_packs)
  4592. << T << D.getSourceRange();
  4593. D.setEllipsisLoc(SourceLocation());
  4594. } else {
  4595. T = Context.getPackExpansionType(T, None);
  4596. }
  4597. break;
  4598. case DeclaratorContext::TemplateParamContext:
  4599. // C++0x [temp.param]p15:
  4600. // If a template-parameter is a [...] is a parameter-declaration that
  4601. // declares a parameter pack (8.3.5), then the template-parameter is a
  4602. // template parameter pack (14.5.3).
  4603. //
  4604. // Note: core issue 778 clarifies that, if there are any unexpanded
  4605. // parameter packs in the type of the non-type template parameter, then
  4606. // it expands those parameter packs.
  4607. if (T->containsUnexpandedParameterPack())
  4608. T = Context.getPackExpansionType(T, None);
  4609. else
  4610. S.Diag(D.getEllipsisLoc(),
  4611. LangOpts.CPlusPlus11
  4612. ? diag::warn_cxx98_compat_variadic_templates
  4613. : diag::ext_variadic_templates);
  4614. break;
  4615. case DeclaratorContext::FileContext:
  4616. case DeclaratorContext::KNRTypeListContext:
  4617. case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
  4618. // here?
  4619. case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
  4620. // here?
  4621. case DeclaratorContext::TypeNameContext:
  4622. case DeclaratorContext::FunctionalCastContext:
  4623. case DeclaratorContext::CXXNewContext:
  4624. case DeclaratorContext::AliasDeclContext:
  4625. case DeclaratorContext::AliasTemplateContext:
  4626. case DeclaratorContext::MemberContext:
  4627. case DeclaratorContext::BlockContext:
  4628. case DeclaratorContext::ForContext:
  4629. case DeclaratorContext::InitStmtContext:
  4630. case DeclaratorContext::ConditionContext:
  4631. case DeclaratorContext::CXXCatchContext:
  4632. case DeclaratorContext::ObjCCatchContext:
  4633. case DeclaratorContext::BlockLiteralContext:
  4634. case DeclaratorContext::LambdaExprContext:
  4635. case DeclaratorContext::ConversionIdContext:
  4636. case DeclaratorContext::TrailingReturnContext:
  4637. case DeclaratorContext::TrailingReturnVarContext:
  4638. case DeclaratorContext::TemplateArgContext:
  4639. case DeclaratorContext::TemplateTypeArgContext:
  4640. // FIXME: We may want to allow parameter packs in block-literal contexts
  4641. // in the future.
  4642. S.Diag(D.getEllipsisLoc(),
  4643. diag::err_ellipsis_in_declarator_not_parameter);
  4644. D.setEllipsisLoc(SourceLocation());
  4645. break;
  4646. }
  4647. }
  4648. assert(!T.isNull() && "T must not be null at the end of this function");
  4649. if (D.isInvalidType())
  4650. return Context.getTrivialTypeSourceInfo(T);
  4651. return GetTypeSourceInfoForDeclarator(state, T, TInfo);
  4652. }
  4653. /// GetTypeForDeclarator - Convert the type for the specified
  4654. /// declarator to Type instances.
  4655. ///
  4656. /// The result of this call will never be null, but the associated
  4657. /// type may be a null type if there's an unrecoverable error.
  4658. TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
  4659. // Determine the type of the declarator. Not all forms of declarator
  4660. // have a type.
  4661. TypeProcessingState state(*this, D);
  4662. TypeSourceInfo *ReturnTypeInfo = nullptr;
  4663. QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  4664. if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
  4665. inferARCWriteback(state, T);
  4666. return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
  4667. }
  4668. static void transferARCOwnershipToDeclSpec(Sema &S,
  4669. QualType &declSpecTy,
  4670. Qualifiers::ObjCLifetime ownership) {
  4671. if (declSpecTy->isObjCRetainableType() &&
  4672. declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
  4673. Qualifiers qs;
  4674. qs.addObjCLifetime(ownership);
  4675. declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
  4676. }
  4677. }
  4678. static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
  4679. Qualifiers::ObjCLifetime ownership,
  4680. unsigned chunkIndex) {
  4681. Sema &S = state.getSema();
  4682. Declarator &D = state.getDeclarator();
  4683. // Look for an explicit lifetime attribute.
  4684. DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
  4685. if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
  4686. return;
  4687. const char *attrStr = nullptr;
  4688. switch (ownership) {
  4689. case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
  4690. case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
  4691. case Qualifiers::OCL_Strong: attrStr = "strong"; break;
  4692. case Qualifiers::OCL_Weak: attrStr = "weak"; break;
  4693. case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
  4694. }
  4695. IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
  4696. Arg->Ident = &S.Context.Idents.get(attrStr);
  4697. Arg->Loc = SourceLocation();
  4698. ArgsUnion Args(Arg);
  4699. // If there wasn't one, add one (with an invalid source location
  4700. // so that we don't make an AttributedType for it).
  4701. ParsedAttr *attr = D.getAttributePool().create(
  4702. &S.Context.Idents.get("objc_ownership"), SourceLocation(),
  4703. /*scope*/ nullptr, SourceLocation(),
  4704. /*args*/ &Args, 1, ParsedAttr::AS_GNU);
  4705. chunk.getAttrs().addAtEnd(attr);
  4706. // TODO: mark whether we did this inference?
  4707. }
  4708. /// Used for transferring ownership in casts resulting in l-values.
  4709. static void transferARCOwnership(TypeProcessingState &state,
  4710. QualType &declSpecTy,
  4711. Qualifiers::ObjCLifetime ownership) {
  4712. Sema &S = state.getSema();
  4713. Declarator &D = state.getDeclarator();
  4714. int inner = -1;
  4715. bool hasIndirection = false;
  4716. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  4717. DeclaratorChunk &chunk = D.getTypeObject(i);
  4718. switch (chunk.Kind) {
  4719. case DeclaratorChunk::Paren:
  4720. // Ignore parens.
  4721. break;
  4722. case DeclaratorChunk::Array:
  4723. case DeclaratorChunk::Reference:
  4724. case DeclaratorChunk::Pointer:
  4725. if (inner != -1)
  4726. hasIndirection = true;
  4727. inner = i;
  4728. break;
  4729. case DeclaratorChunk::BlockPointer:
  4730. if (inner != -1)
  4731. transferARCOwnershipToDeclaratorChunk(state, ownership, i);
  4732. return;
  4733. case DeclaratorChunk::Function:
  4734. case DeclaratorChunk::MemberPointer:
  4735. case DeclaratorChunk::Pipe:
  4736. return;
  4737. }
  4738. }
  4739. if (inner == -1)
  4740. return;
  4741. DeclaratorChunk &chunk = D.getTypeObject(inner);
  4742. if (chunk.Kind == DeclaratorChunk::Pointer) {
  4743. if (declSpecTy->isObjCRetainableType())
  4744. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  4745. if (declSpecTy->isObjCObjectType() && hasIndirection)
  4746. return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
  4747. } else {
  4748. assert(chunk.Kind == DeclaratorChunk::Array ||
  4749. chunk.Kind == DeclaratorChunk::Reference);
  4750. return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
  4751. }
  4752. }
  4753. TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
  4754. TypeProcessingState state(*this, D);
  4755. TypeSourceInfo *ReturnTypeInfo = nullptr;
  4756. QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
  4757. if (getLangOpts().ObjC) {
  4758. Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
  4759. if (ownership != Qualifiers::OCL_None)
  4760. transferARCOwnership(state, declSpecTy, ownership);
  4761. }
  4762. return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
  4763. }
  4764. static void fillAttributedTypeLoc(AttributedTypeLoc TL,
  4765. TypeProcessingState &State) {
  4766. TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
  4767. }
  4768. namespace {
  4769. class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
  4770. ASTContext &Context;
  4771. TypeProcessingState &State;
  4772. const DeclSpec &DS;
  4773. public:
  4774. TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
  4775. const DeclSpec &DS)
  4776. : Context(Context), State(State), DS(DS) {}
  4777. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4778. Visit(TL.getModifiedLoc());
  4779. fillAttributedTypeLoc(TL, State);
  4780. }
  4781. void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  4782. Visit(TL.getInnerLoc());
  4783. TL.setExpansionLoc(
  4784. State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
  4785. }
  4786. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4787. Visit(TL.getUnqualifiedLoc());
  4788. }
  4789. void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  4790. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4791. }
  4792. void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  4793. TL.setNameLoc(DS.getTypeSpecTypeLoc());
  4794. // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
  4795. // addition field. What we have is good enough for dispay of location
  4796. // of 'fixit' on interface name.
  4797. TL.setNameEndLoc(DS.getEndLoc());
  4798. }
  4799. void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  4800. TypeSourceInfo *RepTInfo = nullptr;
  4801. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4802. TL.copy(RepTInfo->getTypeLoc());
  4803. }
  4804. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4805. TypeSourceInfo *RepTInfo = nullptr;
  4806. Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
  4807. TL.copy(RepTInfo->getTypeLoc());
  4808. }
  4809. void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
  4810. TypeSourceInfo *TInfo = nullptr;
  4811. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4812. // If we got no declarator info from previous Sema routines,
  4813. // just fill with the typespec loc.
  4814. if (!TInfo) {
  4815. TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
  4816. return;
  4817. }
  4818. TypeLoc OldTL = TInfo->getTypeLoc();
  4819. if (TInfo->getType()->getAs<ElaboratedType>()) {
  4820. ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
  4821. TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
  4822. .castAs<TemplateSpecializationTypeLoc>();
  4823. TL.copy(NamedTL);
  4824. } else {
  4825. TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
  4826. assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
  4827. }
  4828. }
  4829. void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  4830. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
  4831. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4832. TL.setParensRange(DS.getTypeofParensRange());
  4833. }
  4834. void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  4835. assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
  4836. TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
  4837. TL.setParensRange(DS.getTypeofParensRange());
  4838. assert(DS.getRepAsType());
  4839. TypeSourceInfo *TInfo = nullptr;
  4840. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4841. TL.setUnderlyingTInfo(TInfo);
  4842. }
  4843. void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  4844. // FIXME: This holds only because we only have one unary transform.
  4845. assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
  4846. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4847. TL.setParensRange(DS.getTypeofParensRange());
  4848. assert(DS.getRepAsType());
  4849. TypeSourceInfo *TInfo = nullptr;
  4850. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4851. TL.setUnderlyingTInfo(TInfo);
  4852. }
  4853. void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  4854. // By default, use the source location of the type specifier.
  4855. TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
  4856. if (TL.needsExtraLocalData()) {
  4857. // Set info for the written builtin specifiers.
  4858. TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
  4859. // Try to have a meaningful source location.
  4860. if (TL.getWrittenSignSpec() != TSS_unspecified)
  4861. TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
  4862. if (TL.getWrittenWidthSpec() != TSW_unspecified)
  4863. TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
  4864. }
  4865. }
  4866. void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  4867. ElaboratedTypeKeyword Keyword
  4868. = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
  4869. if (DS.getTypeSpecType() == TST_typename) {
  4870. TypeSourceInfo *TInfo = nullptr;
  4871. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4872. if (TInfo) {
  4873. TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
  4874. return;
  4875. }
  4876. }
  4877. TL.setElaboratedKeywordLoc(Keyword != ETK_None
  4878. ? DS.getTypeSpecTypeLoc()
  4879. : SourceLocation());
  4880. const CXXScopeSpec& SS = DS.getTypeSpecScope();
  4881. TL.setQualifierLoc(SS.getWithLocInContext(Context));
  4882. Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
  4883. }
  4884. void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  4885. assert(DS.getTypeSpecType() == TST_typename);
  4886. TypeSourceInfo *TInfo = nullptr;
  4887. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4888. assert(TInfo);
  4889. TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
  4890. }
  4891. void VisitDependentTemplateSpecializationTypeLoc(
  4892. DependentTemplateSpecializationTypeLoc TL) {
  4893. assert(DS.getTypeSpecType() == TST_typename);
  4894. TypeSourceInfo *TInfo = nullptr;
  4895. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4896. assert(TInfo);
  4897. TL.copy(
  4898. TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
  4899. }
  4900. void VisitTagTypeLoc(TagTypeLoc TL) {
  4901. TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
  4902. }
  4903. void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  4904. // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
  4905. // or an _Atomic qualifier.
  4906. if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
  4907. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4908. TL.setParensRange(DS.getTypeofParensRange());
  4909. TypeSourceInfo *TInfo = nullptr;
  4910. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4911. assert(TInfo);
  4912. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4913. } else {
  4914. TL.setKWLoc(DS.getAtomicSpecLoc());
  4915. // No parens, to indicate this was spelled as an _Atomic qualifier.
  4916. TL.setParensRange(SourceRange());
  4917. Visit(TL.getValueLoc());
  4918. }
  4919. }
  4920. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  4921. TL.setKWLoc(DS.getTypeSpecTypeLoc());
  4922. TypeSourceInfo *TInfo = nullptr;
  4923. Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
  4924. TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
  4925. }
  4926. void VisitTypeLoc(TypeLoc TL) {
  4927. // FIXME: add other typespec types and change this to an assert.
  4928. TL.initialize(Context, DS.getTypeSpecTypeLoc());
  4929. }
  4930. };
  4931. class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
  4932. ASTContext &Context;
  4933. TypeProcessingState &State;
  4934. const DeclaratorChunk &Chunk;
  4935. public:
  4936. DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
  4937. const DeclaratorChunk &Chunk)
  4938. : Context(Context), State(State), Chunk(Chunk) {}
  4939. void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4940. llvm_unreachable("qualified type locs not expected here!");
  4941. }
  4942. void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  4943. llvm_unreachable("decayed type locs not expected here!");
  4944. }
  4945. void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4946. fillAttributedTypeLoc(TL, State);
  4947. }
  4948. void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  4949. // nothing
  4950. }
  4951. void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  4952. assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
  4953. TL.setCaretLoc(Chunk.Loc);
  4954. }
  4955. void VisitPointerTypeLoc(PointerTypeLoc TL) {
  4956. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4957. TL.setStarLoc(Chunk.Loc);
  4958. }
  4959. void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4960. assert(Chunk.Kind == DeclaratorChunk::Pointer);
  4961. TL.setStarLoc(Chunk.Loc);
  4962. }
  4963. void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  4964. assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
  4965. const CXXScopeSpec& SS = Chunk.Mem.Scope();
  4966. NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
  4967. const Type* ClsTy = TL.getClass();
  4968. QualType ClsQT = QualType(ClsTy, 0);
  4969. TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
  4970. // Now copy source location info into the type loc component.
  4971. TypeLoc ClsTL = ClsTInfo->getTypeLoc();
  4972. switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
  4973. case NestedNameSpecifier::Identifier:
  4974. assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
  4975. {
  4976. DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
  4977. DNTLoc.setElaboratedKeywordLoc(SourceLocation());
  4978. DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
  4979. DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
  4980. }
  4981. break;
  4982. case NestedNameSpecifier::TypeSpec:
  4983. case NestedNameSpecifier::TypeSpecWithTemplate:
  4984. if (isa<ElaboratedType>(ClsTy)) {
  4985. ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
  4986. ETLoc.setElaboratedKeywordLoc(SourceLocation());
  4987. ETLoc.setQualifierLoc(NNSLoc.getPrefix());
  4988. TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
  4989. NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4990. } else {
  4991. ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
  4992. }
  4993. break;
  4994. case NestedNameSpecifier::Namespace:
  4995. case NestedNameSpecifier::NamespaceAlias:
  4996. case NestedNameSpecifier::Global:
  4997. case NestedNameSpecifier::Super:
  4998. llvm_unreachable("Nested-name-specifier must name a type");
  4999. }
  5000. // Finally fill in MemberPointerLocInfo fields.
  5001. TL.setStarLoc(Chunk.Loc);
  5002. TL.setClassTInfo(ClsTInfo);
  5003. }
  5004. void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  5005. assert(Chunk.Kind == DeclaratorChunk::Reference);
  5006. // 'Amp' is misleading: this might have been originally
  5007. /// spelled with AmpAmp.
  5008. TL.setAmpLoc(Chunk.Loc);
  5009. }
  5010. void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  5011. assert(Chunk.Kind == DeclaratorChunk::Reference);
  5012. assert(!Chunk.Ref.LValueRef);
  5013. TL.setAmpAmpLoc(Chunk.Loc);
  5014. }
  5015. void VisitArrayTypeLoc(ArrayTypeLoc TL) {
  5016. assert(Chunk.Kind == DeclaratorChunk::Array);
  5017. TL.setLBracketLoc(Chunk.Loc);
  5018. TL.setRBracketLoc(Chunk.EndLoc);
  5019. TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
  5020. }
  5021. void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  5022. assert(Chunk.Kind == DeclaratorChunk::Function);
  5023. TL.setLocalRangeBegin(Chunk.Loc);
  5024. TL.setLocalRangeEnd(Chunk.EndLoc);
  5025. const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
  5026. TL.setLParenLoc(FTI.getLParenLoc());
  5027. TL.setRParenLoc(FTI.getRParenLoc());
  5028. for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
  5029. ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
  5030. TL.setParam(tpi++, Param);
  5031. }
  5032. TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
  5033. }
  5034. void VisitParenTypeLoc(ParenTypeLoc TL) {
  5035. assert(Chunk.Kind == DeclaratorChunk::Paren);
  5036. TL.setLParenLoc(Chunk.Loc);
  5037. TL.setRParenLoc(Chunk.EndLoc);
  5038. }
  5039. void VisitPipeTypeLoc(PipeTypeLoc TL) {
  5040. assert(Chunk.Kind == DeclaratorChunk::Pipe);
  5041. TL.setKWLoc(Chunk.Loc);
  5042. }
  5043. void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  5044. TL.setExpansionLoc(Chunk.Loc);
  5045. }
  5046. void VisitTypeLoc(TypeLoc TL) {
  5047. llvm_unreachable("unsupported TypeLoc kind in declarator!");
  5048. }
  5049. };
  5050. } // end anonymous namespace
  5051. static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
  5052. SourceLocation Loc;
  5053. switch (Chunk.Kind) {
  5054. case DeclaratorChunk::Function:
  5055. case DeclaratorChunk::Array:
  5056. case DeclaratorChunk::Paren:
  5057. case DeclaratorChunk::Pipe:
  5058. llvm_unreachable("cannot be _Atomic qualified");
  5059. case DeclaratorChunk::Pointer:
  5060. Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
  5061. break;
  5062. case DeclaratorChunk::BlockPointer:
  5063. case DeclaratorChunk::Reference:
  5064. case DeclaratorChunk::MemberPointer:
  5065. // FIXME: Provide a source location for the _Atomic keyword.
  5066. break;
  5067. }
  5068. ATL.setKWLoc(Loc);
  5069. ATL.setParensRange(SourceRange());
  5070. }
  5071. static void
  5072. fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
  5073. const ParsedAttributesView &Attrs) {
  5074. for (const ParsedAttr &AL : Attrs) {
  5075. if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
  5076. DASTL.setAttrNameLoc(AL.getLoc());
  5077. DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
  5078. DASTL.setAttrOperandParensRange(SourceRange());
  5079. return;
  5080. }
  5081. }
  5082. llvm_unreachable(
  5083. "no address_space attribute found at the expected location!");
  5084. }
  5085. /// Create and instantiate a TypeSourceInfo with type source information.
  5086. ///
  5087. /// \param T QualType referring to the type as written in source code.
  5088. ///
  5089. /// \param ReturnTypeInfo For declarators whose return type does not show
  5090. /// up in the normal place in the declaration specifiers (such as a C++
  5091. /// conversion function), this pointer will refer to a type source information
  5092. /// for that return type.
  5093. static TypeSourceInfo *
  5094. GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
  5095. QualType T, TypeSourceInfo *ReturnTypeInfo) {
  5096. Sema &S = State.getSema();
  5097. Declarator &D = State.getDeclarator();
  5098. TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
  5099. UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
  5100. // Handle parameter packs whose type is a pack expansion.
  5101. if (isa<PackExpansionType>(T)) {
  5102. CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
  5103. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  5104. }
  5105. for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
  5106. // An AtomicTypeLoc might be produced by an atomic qualifier in this
  5107. // declarator chunk.
  5108. if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
  5109. fillAtomicQualLoc(ATL, D.getTypeObject(i));
  5110. CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
  5111. }
  5112. while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
  5113. TL.setExpansionLoc(
  5114. State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
  5115. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  5116. }
  5117. while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
  5118. fillAttributedTypeLoc(TL, State);
  5119. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  5120. }
  5121. while (DependentAddressSpaceTypeLoc TL =
  5122. CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
  5123. fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
  5124. CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
  5125. }
  5126. // FIXME: Ordering here?
  5127. while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
  5128. CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
  5129. DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
  5130. CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
  5131. }
  5132. // If we have different source information for the return type, use
  5133. // that. This really only applies to C++ conversion functions.
  5134. if (ReturnTypeInfo) {
  5135. TypeLoc TL = ReturnTypeInfo->getTypeLoc();
  5136. assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
  5137. memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
  5138. } else {
  5139. TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL);
  5140. }
  5141. return TInfo;
  5142. }
  5143. /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
  5144. ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
  5145. // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
  5146. // and Sema during declaration parsing. Try deallocating/caching them when
  5147. // it's appropriate, instead of allocating them and keeping them around.
  5148. LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
  5149. TypeAlignment);
  5150. new (LocT) LocInfoType(T, TInfo);
  5151. assert(LocT->getTypeClass() != T->getTypeClass() &&
  5152. "LocInfoType's TypeClass conflicts with an existing Type class");
  5153. return ParsedType::make(QualType(LocT, 0));
  5154. }
  5155. void LocInfoType::getAsStringInternal(std::string &Str,
  5156. const PrintingPolicy &Policy) const {
  5157. llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
  5158. " was used directly instead of getting the QualType through"
  5159. " GetTypeFromParser");
  5160. }
  5161. TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
  5162. // C99 6.7.6: Type names have no identifier. This is already validated by
  5163. // the parser.
  5164. assert(D.getIdentifier() == nullptr &&
  5165. "Type name should have no identifier!");
  5166. TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
  5167. QualType T = TInfo->getType();
  5168. if (D.isInvalidType())
  5169. return true;
  5170. // Make sure there are no unused decl attributes on the declarator.
  5171. // We don't want to do this for ObjC parameters because we're going
  5172. // to apply them to the actual parameter declaration.
  5173. // Likewise, we don't want to do this for alias declarations, because
  5174. // we are actually going to build a declaration from this eventually.
  5175. if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
  5176. D.getContext() != DeclaratorContext::AliasDeclContext &&
  5177. D.getContext() != DeclaratorContext::AliasTemplateContext)
  5178. checkUnusedDeclAttributes(D);
  5179. if (getLangOpts().CPlusPlus) {
  5180. // Check that there are no default arguments (C++ only).
  5181. CheckExtraCXXDefaultArguments(D);
  5182. }
  5183. return CreateParsedType(T, TInfo);
  5184. }
  5185. ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
  5186. QualType T = Context.getObjCInstanceType();
  5187. TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
  5188. return CreateParsedType(T, TInfo);
  5189. }
  5190. //===----------------------------------------------------------------------===//
  5191. // Type Attribute Processing
  5192. //===----------------------------------------------------------------------===//
  5193. /// Build an AddressSpace index from a constant expression and diagnose any
  5194. /// errors related to invalid address_spaces. Returns true on successfully
  5195. /// building an AddressSpace index.
  5196. static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
  5197. const Expr *AddrSpace,
  5198. SourceLocation AttrLoc) {
  5199. if (!AddrSpace->isValueDependent()) {
  5200. llvm::APSInt addrSpace(32);
  5201. if (!AddrSpace->isIntegerConstantExpr(addrSpace, S.Context)) {
  5202. S.Diag(AttrLoc, diag::err_attribute_argument_type)
  5203. << "'address_space'" << AANT_ArgumentIntegerConstant
  5204. << AddrSpace->getSourceRange();
  5205. return false;
  5206. }
  5207. // Bounds checking.
  5208. if (addrSpace.isSigned()) {
  5209. if (addrSpace.isNegative()) {
  5210. S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
  5211. << AddrSpace->getSourceRange();
  5212. return false;
  5213. }
  5214. addrSpace.setIsSigned(false);
  5215. }
  5216. llvm::APSInt max(addrSpace.getBitWidth());
  5217. max =
  5218. Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
  5219. if (addrSpace > max) {
  5220. S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
  5221. << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
  5222. return false;
  5223. }
  5224. ASIdx =
  5225. getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
  5226. return true;
  5227. }
  5228. // Default value for DependentAddressSpaceTypes
  5229. ASIdx = LangAS::Default;
  5230. return true;
  5231. }
  5232. /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
  5233. /// is uninstantiated. If instantiated it will apply the appropriate address
  5234. /// space to the type. This function allows dependent template variables to be
  5235. /// used in conjunction with the address_space attribute
  5236. QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
  5237. SourceLocation AttrLoc) {
  5238. if (!AddrSpace->isValueDependent()) {
  5239. if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
  5240. AttrLoc))
  5241. return QualType();
  5242. return Context.getAddrSpaceQualType(T, ASIdx);
  5243. }
  5244. // A check with similar intentions as checking if a type already has an
  5245. // address space except for on a dependent types, basically if the
  5246. // current type is already a DependentAddressSpaceType then its already
  5247. // lined up to have another address space on it and we can't have
  5248. // multiple address spaces on the one pointer indirection
  5249. if (T->getAs<DependentAddressSpaceType>()) {
  5250. Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
  5251. return QualType();
  5252. }
  5253. return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
  5254. }
  5255. QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
  5256. SourceLocation AttrLoc) {
  5257. LangAS ASIdx;
  5258. if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
  5259. return QualType();
  5260. return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
  5261. }
  5262. /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
  5263. /// specified type. The attribute contains 1 argument, the id of the address
  5264. /// space for the type.
  5265. static void HandleAddressSpaceTypeAttribute(QualType &Type,
  5266. const ParsedAttr &Attr,
  5267. TypeProcessingState &State) {
  5268. Sema &S = State.getSema();
  5269. // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
  5270. // qualified by an address-space qualifier."
  5271. if (Type->isFunctionType()) {
  5272. S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
  5273. Attr.setInvalid();
  5274. return;
  5275. }
  5276. LangAS ASIdx;
  5277. if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
  5278. // Check the attribute arguments.
  5279. if (Attr.getNumArgs() != 1) {
  5280. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  5281. << 1;
  5282. Attr.setInvalid();
  5283. return;
  5284. }
  5285. Expr *ASArgExpr;
  5286. if (Attr.isArgIdent(0)) {
  5287. // Special case where the argument is a template id.
  5288. CXXScopeSpec SS;
  5289. SourceLocation TemplateKWLoc;
  5290. UnqualifiedId id;
  5291. id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  5292. ExprResult AddrSpace = S.ActOnIdExpression(
  5293. S.getCurScope(), SS, TemplateKWLoc, id, /*HasTrailingLParen=*/false,
  5294. /*IsAddressOfOperand=*/false);
  5295. if (AddrSpace.isInvalid())
  5296. return;
  5297. ASArgExpr = static_cast<Expr *>(AddrSpace.get());
  5298. } else {
  5299. ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  5300. }
  5301. LangAS ASIdx;
  5302. if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
  5303. Attr.setInvalid();
  5304. return;
  5305. }
  5306. ASTContext &Ctx = S.Context;
  5307. auto *ASAttr =
  5308. ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
  5309. // If the expression is not value dependent (not templated), then we can
  5310. // apply the address space qualifiers just to the equivalent type.
  5311. // Otherwise, we make an AttributedType with the modified and equivalent
  5312. // type the same, and wrap it in a DependentAddressSpaceType. When this
  5313. // dependent type is resolved, the qualifier is added to the equivalent type
  5314. // later.
  5315. QualType T;
  5316. if (!ASArgExpr->isValueDependent()) {
  5317. QualType EquivType =
  5318. S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
  5319. if (EquivType.isNull()) {
  5320. Attr.setInvalid();
  5321. return;
  5322. }
  5323. T = State.getAttributedType(ASAttr, Type, EquivType);
  5324. } else {
  5325. T = State.getAttributedType(ASAttr, Type, Type);
  5326. T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
  5327. }
  5328. if (!T.isNull())
  5329. Type = T;
  5330. else
  5331. Attr.setInvalid();
  5332. } else {
  5333. // The keyword-based type attributes imply which address space to use.
  5334. ASIdx = Attr.asOpenCLLangAS();
  5335. if (ASIdx == LangAS::Default)
  5336. llvm_unreachable("Invalid address space");
  5337. if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
  5338. Attr.getLoc())) {
  5339. Attr.setInvalid();
  5340. return;
  5341. }
  5342. Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
  5343. }
  5344. }
  5345. /// handleObjCOwnershipTypeAttr - Process an objc_ownership
  5346. /// attribute on the specified type.
  5347. ///
  5348. /// Returns 'true' if the attribute was handled.
  5349. static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
  5350. ParsedAttr &attr, QualType &type) {
  5351. bool NonObjCPointer = false;
  5352. if (!type->isDependentType() && !type->isUndeducedType()) {
  5353. if (const PointerType *ptr = type->getAs<PointerType>()) {
  5354. QualType pointee = ptr->getPointeeType();
  5355. if (pointee->isObjCRetainableType() || pointee->isPointerType())
  5356. return false;
  5357. // It is important not to lose the source info that there was an attribute
  5358. // applied to non-objc pointer. We will create an attributed type but
  5359. // its type will be the same as the original type.
  5360. NonObjCPointer = true;
  5361. } else if (!type->isObjCRetainableType()) {
  5362. return false;
  5363. }
  5364. // Don't accept an ownership attribute in the declspec if it would
  5365. // just be the return type of a block pointer.
  5366. if (state.isProcessingDeclSpec()) {
  5367. Declarator &D = state.getDeclarator();
  5368. if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
  5369. /*onlyBlockPointers=*/true))
  5370. return false;
  5371. }
  5372. }
  5373. Sema &S = state.getSema();
  5374. SourceLocation AttrLoc = attr.getLoc();
  5375. if (AttrLoc.isMacroID())
  5376. AttrLoc =
  5377. S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
  5378. if (!attr.isArgIdent(0)) {
  5379. S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
  5380. << AANT_ArgumentString;
  5381. attr.setInvalid();
  5382. return true;
  5383. }
  5384. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  5385. Qualifiers::ObjCLifetime lifetime;
  5386. if (II->isStr("none"))
  5387. lifetime = Qualifiers::OCL_ExplicitNone;
  5388. else if (II->isStr("strong"))
  5389. lifetime = Qualifiers::OCL_Strong;
  5390. else if (II->isStr("weak"))
  5391. lifetime = Qualifiers::OCL_Weak;
  5392. else if (II->isStr("autoreleasing"))
  5393. lifetime = Qualifiers::OCL_Autoreleasing;
  5394. else {
  5395. S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
  5396. attr.setInvalid();
  5397. return true;
  5398. }
  5399. // Just ignore lifetime attributes other than __weak and __unsafe_unretained
  5400. // outside of ARC mode.
  5401. if (!S.getLangOpts().ObjCAutoRefCount &&
  5402. lifetime != Qualifiers::OCL_Weak &&
  5403. lifetime != Qualifiers::OCL_ExplicitNone) {
  5404. return true;
  5405. }
  5406. SplitQualType underlyingType = type.split();
  5407. // Check for redundant/conflicting ownership qualifiers.
  5408. if (Qualifiers::ObjCLifetime previousLifetime
  5409. = type.getQualifiers().getObjCLifetime()) {
  5410. // If it's written directly, that's an error.
  5411. if (S.Context.hasDirectOwnershipQualifier(type)) {
  5412. S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
  5413. << type;
  5414. return true;
  5415. }
  5416. // Otherwise, if the qualifiers actually conflict, pull sugar off
  5417. // and remove the ObjCLifetime qualifiers.
  5418. if (previousLifetime != lifetime) {
  5419. // It's possible to have multiple local ObjCLifetime qualifiers. We
  5420. // can't stop after we reach a type that is directly qualified.
  5421. const Type *prevTy = nullptr;
  5422. while (!prevTy || prevTy != underlyingType.Ty) {
  5423. prevTy = underlyingType.Ty;
  5424. underlyingType = underlyingType.getSingleStepDesugaredType();
  5425. }
  5426. underlyingType.Quals.removeObjCLifetime();
  5427. }
  5428. }
  5429. underlyingType.Quals.addObjCLifetime(lifetime);
  5430. if (NonObjCPointer) {
  5431. StringRef name = attr.getAttrName()->getName();
  5432. switch (lifetime) {
  5433. case Qualifiers::OCL_None:
  5434. case Qualifiers::OCL_ExplicitNone:
  5435. break;
  5436. case Qualifiers::OCL_Strong: name = "__strong"; break;
  5437. case Qualifiers::OCL_Weak: name = "__weak"; break;
  5438. case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
  5439. }
  5440. S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
  5441. << TDS_ObjCObjOrBlock << type;
  5442. }
  5443. // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
  5444. // because having both 'T' and '__unsafe_unretained T' exist in the type
  5445. // system causes unfortunate widespread consistency problems. (For example,
  5446. // they're not considered compatible types, and we mangle them identicially
  5447. // as template arguments.) These problems are all individually fixable,
  5448. // but it's easier to just not add the qualifier and instead sniff it out
  5449. // in specific places using isObjCInertUnsafeUnretainedType().
  5450. //
  5451. // Doing this does means we miss some trivial consistency checks that
  5452. // would've triggered in ARC, but that's better than trying to solve all
  5453. // the coexistence problems with __unsafe_unretained.
  5454. if (!S.getLangOpts().ObjCAutoRefCount &&
  5455. lifetime == Qualifiers::OCL_ExplicitNone) {
  5456. type = state.getAttributedType(
  5457. createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
  5458. type, type);
  5459. return true;
  5460. }
  5461. QualType origType = type;
  5462. if (!NonObjCPointer)
  5463. type = S.Context.getQualifiedType(underlyingType);
  5464. // If we have a valid source location for the attribute, use an
  5465. // AttributedType instead.
  5466. if (AttrLoc.isValid()) {
  5467. type = state.getAttributedType(::new (S.Context)
  5468. ObjCOwnershipAttr(S.Context, attr, II),
  5469. origType, type);
  5470. }
  5471. auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
  5472. unsigned diagnostic, QualType type) {
  5473. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  5474. S.DelayedDiagnostics.add(
  5475. sema::DelayedDiagnostic::makeForbiddenType(
  5476. S.getSourceManager().getExpansionLoc(loc),
  5477. diagnostic, type, /*ignored*/ 0));
  5478. } else {
  5479. S.Diag(loc, diagnostic);
  5480. }
  5481. };
  5482. // Sometimes, __weak isn't allowed.
  5483. if (lifetime == Qualifiers::OCL_Weak &&
  5484. !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
  5485. // Use a specialized diagnostic if the runtime just doesn't support them.
  5486. unsigned diagnostic =
  5487. (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
  5488. : diag::err_arc_weak_no_runtime);
  5489. // In any case, delay the diagnostic until we know what we're parsing.
  5490. diagnoseOrDelay(S, AttrLoc, diagnostic, type);
  5491. attr.setInvalid();
  5492. return true;
  5493. }
  5494. // Forbid __weak for class objects marked as
  5495. // objc_arc_weak_reference_unavailable
  5496. if (lifetime == Qualifiers::OCL_Weak) {
  5497. if (const ObjCObjectPointerType *ObjT =
  5498. type->getAs<ObjCObjectPointerType>()) {
  5499. if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
  5500. if (Class->isArcWeakrefUnavailable()) {
  5501. S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
  5502. S.Diag(ObjT->getInterfaceDecl()->getLocation(),
  5503. diag::note_class_declared);
  5504. }
  5505. }
  5506. }
  5507. }
  5508. return true;
  5509. }
  5510. /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
  5511. /// attribute on the specified type. Returns true to indicate that
  5512. /// the attribute was handled, false to indicate that the type does
  5513. /// not permit the attribute.
  5514. static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  5515. QualType &type) {
  5516. Sema &S = state.getSema();
  5517. // Delay if this isn't some kind of pointer.
  5518. if (!type->isPointerType() &&
  5519. !type->isObjCObjectPointerType() &&
  5520. !type->isBlockPointerType())
  5521. return false;
  5522. if (type.getObjCGCAttr() != Qualifiers::GCNone) {
  5523. S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
  5524. attr.setInvalid();
  5525. return true;
  5526. }
  5527. // Check the attribute arguments.
  5528. if (!attr.isArgIdent(0)) {
  5529. S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
  5530. << attr << AANT_ArgumentString;
  5531. attr.setInvalid();
  5532. return true;
  5533. }
  5534. Qualifiers::GC GCAttr;
  5535. if (attr.getNumArgs() > 1) {
  5536. S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
  5537. << 1;
  5538. attr.setInvalid();
  5539. return true;
  5540. }
  5541. IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
  5542. if (II->isStr("weak"))
  5543. GCAttr = Qualifiers::Weak;
  5544. else if (II->isStr("strong"))
  5545. GCAttr = Qualifiers::Strong;
  5546. else {
  5547. S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
  5548. << attr << II;
  5549. attr.setInvalid();
  5550. return true;
  5551. }
  5552. QualType origType = type;
  5553. type = S.Context.getObjCGCQualType(origType, GCAttr);
  5554. // Make an attributed type to preserve the source information.
  5555. if (attr.getLoc().isValid())
  5556. type = state.getAttributedType(
  5557. ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
  5558. return true;
  5559. }
  5560. namespace {
  5561. /// A helper class to unwrap a type down to a function for the
  5562. /// purposes of applying attributes there.
  5563. ///
  5564. /// Use:
  5565. /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
  5566. /// if (unwrapped.isFunctionType()) {
  5567. /// const FunctionType *fn = unwrapped.get();
  5568. /// // change fn somehow
  5569. /// T = unwrapped.wrap(fn);
  5570. /// }
  5571. struct FunctionTypeUnwrapper {
  5572. enum WrapKind {
  5573. Desugar,
  5574. Attributed,
  5575. Parens,
  5576. Pointer,
  5577. BlockPointer,
  5578. Reference,
  5579. MemberPointer
  5580. };
  5581. QualType Original;
  5582. const FunctionType *Fn;
  5583. SmallVector<unsigned char /*WrapKind*/, 8> Stack;
  5584. FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
  5585. while (true) {
  5586. const Type *Ty = T.getTypePtr();
  5587. if (isa<FunctionType>(Ty)) {
  5588. Fn = cast<FunctionType>(Ty);
  5589. return;
  5590. } else if (isa<ParenType>(Ty)) {
  5591. T = cast<ParenType>(Ty)->getInnerType();
  5592. Stack.push_back(Parens);
  5593. } else if (isa<PointerType>(Ty)) {
  5594. T = cast<PointerType>(Ty)->getPointeeType();
  5595. Stack.push_back(Pointer);
  5596. } else if (isa<BlockPointerType>(Ty)) {
  5597. T = cast<BlockPointerType>(Ty)->getPointeeType();
  5598. Stack.push_back(BlockPointer);
  5599. } else if (isa<MemberPointerType>(Ty)) {
  5600. T = cast<MemberPointerType>(Ty)->getPointeeType();
  5601. Stack.push_back(MemberPointer);
  5602. } else if (isa<ReferenceType>(Ty)) {
  5603. T = cast<ReferenceType>(Ty)->getPointeeType();
  5604. Stack.push_back(Reference);
  5605. } else if (isa<AttributedType>(Ty)) {
  5606. T = cast<AttributedType>(Ty)->getEquivalentType();
  5607. Stack.push_back(Attributed);
  5608. } else {
  5609. const Type *DTy = Ty->getUnqualifiedDesugaredType();
  5610. if (Ty == DTy) {
  5611. Fn = nullptr;
  5612. return;
  5613. }
  5614. T = QualType(DTy, 0);
  5615. Stack.push_back(Desugar);
  5616. }
  5617. }
  5618. }
  5619. bool isFunctionType() const { return (Fn != nullptr); }
  5620. const FunctionType *get() const { return Fn; }
  5621. QualType wrap(Sema &S, const FunctionType *New) {
  5622. // If T wasn't modified from the unwrapped type, do nothing.
  5623. if (New == get()) return Original;
  5624. Fn = New;
  5625. return wrap(S.Context, Original, 0);
  5626. }
  5627. private:
  5628. QualType wrap(ASTContext &C, QualType Old, unsigned I) {
  5629. if (I == Stack.size())
  5630. return C.getQualifiedType(Fn, Old.getQualifiers());
  5631. // Build up the inner type, applying the qualifiers from the old
  5632. // type to the new type.
  5633. SplitQualType SplitOld = Old.split();
  5634. // As a special case, tail-recurse if there are no qualifiers.
  5635. if (SplitOld.Quals.empty())
  5636. return wrap(C, SplitOld.Ty, I);
  5637. return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
  5638. }
  5639. QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
  5640. if (I == Stack.size()) return QualType(Fn, 0);
  5641. switch (static_cast<WrapKind>(Stack[I++])) {
  5642. case Desugar:
  5643. // This is the point at which we potentially lose source
  5644. // information.
  5645. return wrap(C, Old->getUnqualifiedDesugaredType(), I);
  5646. case Attributed:
  5647. return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
  5648. case Parens: {
  5649. QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
  5650. return C.getParenType(New);
  5651. }
  5652. case Pointer: {
  5653. QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
  5654. return C.getPointerType(New);
  5655. }
  5656. case BlockPointer: {
  5657. QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
  5658. return C.getBlockPointerType(New);
  5659. }
  5660. case MemberPointer: {
  5661. const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
  5662. QualType New = wrap(C, OldMPT->getPointeeType(), I);
  5663. return C.getMemberPointerType(New, OldMPT->getClass());
  5664. }
  5665. case Reference: {
  5666. const ReferenceType *OldRef = cast<ReferenceType>(Old);
  5667. QualType New = wrap(C, OldRef->getPointeeType(), I);
  5668. if (isa<LValueReferenceType>(OldRef))
  5669. return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
  5670. else
  5671. return C.getRValueReferenceType(New);
  5672. }
  5673. }
  5674. llvm_unreachable("unknown wrapping kind");
  5675. }
  5676. };
  5677. } // end anonymous namespace
  5678. static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
  5679. ParsedAttr &PAttr, QualType &Type) {
  5680. Sema &S = State.getSema();
  5681. Attr *A;
  5682. switch (PAttr.getKind()) {
  5683. default: llvm_unreachable("Unknown attribute kind");
  5684. case ParsedAttr::AT_Ptr32:
  5685. A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
  5686. break;
  5687. case ParsedAttr::AT_Ptr64:
  5688. A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
  5689. break;
  5690. case ParsedAttr::AT_SPtr:
  5691. A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
  5692. break;
  5693. case ParsedAttr::AT_UPtr:
  5694. A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
  5695. break;
  5696. }
  5697. attr::Kind NewAttrKind = A->getKind();
  5698. QualType Desugared = Type;
  5699. const AttributedType *AT = dyn_cast<AttributedType>(Type);
  5700. while (AT) {
  5701. attr::Kind CurAttrKind = AT->getAttrKind();
  5702. // You cannot specify duplicate type attributes, so if the attribute has
  5703. // already been applied, flag it.
  5704. if (NewAttrKind == CurAttrKind) {
  5705. S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
  5706. return true;
  5707. }
  5708. // You cannot have both __sptr and __uptr on the same type, nor can you
  5709. // have __ptr32 and __ptr64.
  5710. if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) ||
  5711. (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) {
  5712. S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
  5713. << "'__ptr32'" << "'__ptr64'";
  5714. return true;
  5715. } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) ||
  5716. (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) {
  5717. S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
  5718. << "'__sptr'" << "'__uptr'";
  5719. return true;
  5720. }
  5721. Desugared = AT->getEquivalentType();
  5722. AT = dyn_cast<AttributedType>(Desugared);
  5723. }
  5724. // Pointer type qualifiers can only operate on pointer types, but not
  5725. // pointer-to-member types.
  5726. //
  5727. // FIXME: Should we really be disallowing this attribute if there is any
  5728. // type sugar between it and the pointer (other than attributes)? Eg, this
  5729. // disallows the attribute on a parenthesized pointer.
  5730. // And if so, should we really allow *any* type attribute?
  5731. if (!isa<PointerType>(Desugared)) {
  5732. if (Type->isMemberPointerType())
  5733. S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
  5734. else
  5735. S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
  5736. return true;
  5737. }
  5738. Type = State.getAttributedType(A, Type, Type);
  5739. return false;
  5740. }
  5741. /// Map a nullability attribute kind to a nullability kind.
  5742. static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
  5743. switch (kind) {
  5744. case ParsedAttr::AT_TypeNonNull:
  5745. return NullabilityKind::NonNull;
  5746. case ParsedAttr::AT_TypeNullable:
  5747. return NullabilityKind::Nullable;
  5748. case ParsedAttr::AT_TypeNullUnspecified:
  5749. return NullabilityKind::Unspecified;
  5750. default:
  5751. llvm_unreachable("not a nullability attribute kind");
  5752. }
  5753. }
  5754. /// Applies a nullability type specifier to the given type, if possible.
  5755. ///
  5756. /// \param state The type processing state.
  5757. ///
  5758. /// \param type The type to which the nullability specifier will be
  5759. /// added. On success, this type will be updated appropriately.
  5760. ///
  5761. /// \param attr The attribute as written on the type.
  5762. ///
  5763. /// \param allowOnArrayType Whether to accept nullability specifiers on an
  5764. /// array type (e.g., because it will decay to a pointer).
  5765. ///
  5766. /// \returns true if a problem has been diagnosed, false on success.
  5767. static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
  5768. QualType &type,
  5769. ParsedAttr &attr,
  5770. bool allowOnArrayType) {
  5771. Sema &S = state.getSema();
  5772. NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
  5773. SourceLocation nullabilityLoc = attr.getLoc();
  5774. bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
  5775. recordNullabilitySeen(S, nullabilityLoc);
  5776. // Check for existing nullability attributes on the type.
  5777. QualType desugared = type;
  5778. while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
  5779. // Check whether there is already a null
  5780. if (auto existingNullability = attributed->getImmediateNullability()) {
  5781. // Duplicated nullability.
  5782. if (nullability == *existingNullability) {
  5783. S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
  5784. << DiagNullabilityKind(nullability, isContextSensitive)
  5785. << FixItHint::CreateRemoval(nullabilityLoc);
  5786. break;
  5787. }
  5788. // Conflicting nullability.
  5789. S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
  5790. << DiagNullabilityKind(nullability, isContextSensitive)
  5791. << DiagNullabilityKind(*existingNullability, false);
  5792. return true;
  5793. }
  5794. desugared = attributed->getModifiedType();
  5795. }
  5796. // If there is already a different nullability specifier, complain.
  5797. // This (unlike the code above) looks through typedefs that might
  5798. // have nullability specifiers on them, which means we cannot
  5799. // provide a useful Fix-It.
  5800. if (auto existingNullability = desugared->getNullability(S.Context)) {
  5801. if (nullability != *existingNullability) {
  5802. S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
  5803. << DiagNullabilityKind(nullability, isContextSensitive)
  5804. << DiagNullabilityKind(*existingNullability, false);
  5805. // Try to find the typedef with the existing nullability specifier.
  5806. if (auto typedefType = desugared->getAs<TypedefType>()) {
  5807. TypedefNameDecl *typedefDecl = typedefType->getDecl();
  5808. QualType underlyingType = typedefDecl->getUnderlyingType();
  5809. if (auto typedefNullability
  5810. = AttributedType::stripOuterNullability(underlyingType)) {
  5811. if (*typedefNullability == *existingNullability) {
  5812. S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
  5813. << DiagNullabilityKind(*existingNullability, false);
  5814. }
  5815. }
  5816. }
  5817. return true;
  5818. }
  5819. }
  5820. // If this definitely isn't a pointer type, reject the specifier.
  5821. if (!desugared->canHaveNullability() &&
  5822. !(allowOnArrayType && desugared->isArrayType())) {
  5823. S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
  5824. << DiagNullabilityKind(nullability, isContextSensitive) << type;
  5825. return true;
  5826. }
  5827. // For the context-sensitive keywords/Objective-C property
  5828. // attributes, require that the type be a single-level pointer.
  5829. if (isContextSensitive) {
  5830. // Make sure that the pointee isn't itself a pointer type.
  5831. const Type *pointeeType;
  5832. if (desugared->isArrayType())
  5833. pointeeType = desugared->getArrayElementTypeNoTypeQual();
  5834. else
  5835. pointeeType = desugared->getPointeeType().getTypePtr();
  5836. if (pointeeType->isAnyPointerType() ||
  5837. pointeeType->isObjCObjectPointerType() ||
  5838. pointeeType->isMemberPointerType()) {
  5839. S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
  5840. << DiagNullabilityKind(nullability, true)
  5841. << type;
  5842. S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
  5843. << DiagNullabilityKind(nullability, false)
  5844. << type
  5845. << FixItHint::CreateReplacement(nullabilityLoc,
  5846. getNullabilitySpelling(nullability));
  5847. return true;
  5848. }
  5849. }
  5850. // Form the attributed type.
  5851. type = state.getAttributedType(
  5852. createNullabilityAttr(S.Context, attr, nullability), type, type);
  5853. return false;
  5854. }
  5855. /// Check the application of the Objective-C '__kindof' qualifier to
  5856. /// the given type.
  5857. static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
  5858. ParsedAttr &attr) {
  5859. Sema &S = state.getSema();
  5860. if (isa<ObjCTypeParamType>(type)) {
  5861. // Build the attributed type to record where __kindof occurred.
  5862. type = state.getAttributedType(
  5863. createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
  5864. return false;
  5865. }
  5866. // Find out if it's an Objective-C object or object pointer type;
  5867. const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
  5868. const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
  5869. : type->getAs<ObjCObjectType>();
  5870. // If not, we can't apply __kindof.
  5871. if (!objType) {
  5872. // FIXME: Handle dependent types that aren't yet object types.
  5873. S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
  5874. << type;
  5875. return true;
  5876. }
  5877. // Rebuild the "equivalent" type, which pushes __kindof down into
  5878. // the object type.
  5879. // There is no need to apply kindof on an unqualified id type.
  5880. QualType equivType = S.Context.getObjCObjectType(
  5881. objType->getBaseType(), objType->getTypeArgsAsWritten(),
  5882. objType->getProtocols(),
  5883. /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
  5884. // If we started with an object pointer type, rebuild it.
  5885. if (ptrType) {
  5886. equivType = S.Context.getObjCObjectPointerType(equivType);
  5887. if (auto nullability = type->getNullability(S.Context)) {
  5888. // We create a nullability attribute from the __kindof attribute.
  5889. // Make sure that will make sense.
  5890. assert(attr.getAttributeSpellingListIndex() == 0 &&
  5891. "multiple spellings for __kindof?");
  5892. Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
  5893. A->setImplicit(true);
  5894. equivType = state.getAttributedType(A, equivType, equivType);
  5895. }
  5896. }
  5897. // Build the attributed type to record where __kindof occurred.
  5898. type = state.getAttributedType(
  5899. createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
  5900. return false;
  5901. }
  5902. /// Distribute a nullability type attribute that cannot be applied to
  5903. /// the type specifier to a pointer, block pointer, or member pointer
  5904. /// declarator, complaining if necessary.
  5905. ///
  5906. /// \returns true if the nullability annotation was distributed, false
  5907. /// otherwise.
  5908. static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
  5909. QualType type, ParsedAttr &attr) {
  5910. Declarator &declarator = state.getDeclarator();
  5911. /// Attempt to move the attribute to the specified chunk.
  5912. auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
  5913. // If there is already a nullability attribute there, don't add
  5914. // one.
  5915. if (hasNullabilityAttr(chunk.getAttrs()))
  5916. return false;
  5917. // Complain about the nullability qualifier being in the wrong
  5918. // place.
  5919. enum {
  5920. PK_Pointer,
  5921. PK_BlockPointer,
  5922. PK_MemberPointer,
  5923. PK_FunctionPointer,
  5924. PK_MemberFunctionPointer,
  5925. } pointerKind
  5926. = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
  5927. : PK_Pointer)
  5928. : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
  5929. : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
  5930. auto diag = state.getSema().Diag(attr.getLoc(),
  5931. diag::warn_nullability_declspec)
  5932. << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
  5933. attr.isContextSensitiveKeywordAttribute())
  5934. << type
  5935. << static_cast<unsigned>(pointerKind);
  5936. // FIXME: MemberPointer chunks don't carry the location of the *.
  5937. if (chunk.Kind != DeclaratorChunk::MemberPointer) {
  5938. diag << FixItHint::CreateRemoval(attr.getLoc())
  5939. << FixItHint::CreateInsertion(
  5940. state.getSema().getPreprocessor().getLocForEndOfToken(
  5941. chunk.Loc),
  5942. " " + attr.getAttrName()->getName().str() + " ");
  5943. }
  5944. moveAttrFromListToList(attr, state.getCurrentAttributes(),
  5945. chunk.getAttrs());
  5946. return true;
  5947. };
  5948. // Move it to the outermost pointer, member pointer, or block
  5949. // pointer declarator.
  5950. for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
  5951. DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
  5952. switch (chunk.Kind) {
  5953. case DeclaratorChunk::Pointer:
  5954. case DeclaratorChunk::BlockPointer:
  5955. case DeclaratorChunk::MemberPointer:
  5956. return moveToChunk(chunk, false);
  5957. case DeclaratorChunk::Paren:
  5958. case DeclaratorChunk::Array:
  5959. continue;
  5960. case DeclaratorChunk::Function:
  5961. // Try to move past the return type to a function/block/member
  5962. // function pointer.
  5963. if (DeclaratorChunk *dest = maybeMovePastReturnType(
  5964. declarator, i,
  5965. /*onlyBlockPointers=*/false)) {
  5966. return moveToChunk(*dest, true);
  5967. }
  5968. return false;
  5969. // Don't walk through these.
  5970. case DeclaratorChunk::Reference:
  5971. case DeclaratorChunk::Pipe:
  5972. return false;
  5973. }
  5974. }
  5975. return false;
  5976. }
  5977. static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
  5978. assert(!Attr.isInvalid());
  5979. switch (Attr.getKind()) {
  5980. default:
  5981. llvm_unreachable("not a calling convention attribute");
  5982. case ParsedAttr::AT_CDecl:
  5983. return createSimpleAttr<CDeclAttr>(Ctx, Attr);
  5984. case ParsedAttr::AT_FastCall:
  5985. return createSimpleAttr<FastCallAttr>(Ctx, Attr);
  5986. case ParsedAttr::AT_StdCall:
  5987. return createSimpleAttr<StdCallAttr>(Ctx, Attr);
  5988. case ParsedAttr::AT_ThisCall:
  5989. return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
  5990. case ParsedAttr::AT_RegCall:
  5991. return createSimpleAttr<RegCallAttr>(Ctx, Attr);
  5992. case ParsedAttr::AT_Pascal:
  5993. return createSimpleAttr<PascalAttr>(Ctx, Attr);
  5994. case ParsedAttr::AT_SwiftCall:
  5995. return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
  5996. case ParsedAttr::AT_VectorCall:
  5997. return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
  5998. case ParsedAttr::AT_AArch64VectorPcs:
  5999. return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
  6000. case ParsedAttr::AT_Pcs: {
  6001. // The attribute may have had a fixit applied where we treated an
  6002. // identifier as a string literal. The contents of the string are valid,
  6003. // but the form may not be.
  6004. StringRef Str;
  6005. if (Attr.isArgExpr(0))
  6006. Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
  6007. else
  6008. Str = Attr.getArgAsIdent(0)->Ident->getName();
  6009. PcsAttr::PCSType Type;
  6010. if (!PcsAttr::ConvertStrToPCSType(Str, Type))
  6011. llvm_unreachable("already validated the attribute");
  6012. return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
  6013. }
  6014. case ParsedAttr::AT_IntelOclBicc:
  6015. return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
  6016. case ParsedAttr::AT_MSABI:
  6017. return createSimpleAttr<MSABIAttr>(Ctx, Attr);
  6018. case ParsedAttr::AT_SysVABI:
  6019. return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
  6020. case ParsedAttr::AT_PreserveMost:
  6021. return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
  6022. case ParsedAttr::AT_PreserveAll:
  6023. return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
  6024. }
  6025. llvm_unreachable("unexpected attribute kind!");
  6026. }
  6027. /// Process an individual function attribute. Returns true to
  6028. /// indicate that the attribute was handled, false if it wasn't.
  6029. static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
  6030. QualType &type) {
  6031. Sema &S = state.getSema();
  6032. FunctionTypeUnwrapper unwrapped(S, type);
  6033. if (attr.getKind() == ParsedAttr::AT_NoReturn) {
  6034. if (S.CheckAttrNoArgs(attr))
  6035. return true;
  6036. // Delay if this is not a function type.
  6037. if (!unwrapped.isFunctionType())
  6038. return false;
  6039. // Otherwise we can process right away.
  6040. FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
  6041. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6042. return true;
  6043. }
  6044. // ns_returns_retained is not always a type attribute, but if we got
  6045. // here, we're treating it as one right now.
  6046. if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
  6047. if (attr.getNumArgs()) return true;
  6048. // Delay if this is not a function type.
  6049. if (!unwrapped.isFunctionType())
  6050. return false;
  6051. // Check whether the return type is reasonable.
  6052. if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
  6053. unwrapped.get()->getReturnType()))
  6054. return true;
  6055. // Only actually change the underlying type in ARC builds.
  6056. QualType origType = type;
  6057. if (state.getSema().getLangOpts().ObjCAutoRefCount) {
  6058. FunctionType::ExtInfo EI
  6059. = unwrapped.get()->getExtInfo().withProducesResult(true);
  6060. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6061. }
  6062. type = state.getAttributedType(
  6063. createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
  6064. origType, type);
  6065. return true;
  6066. }
  6067. if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
  6068. if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
  6069. return true;
  6070. // Delay if this is not a function type.
  6071. if (!unwrapped.isFunctionType())
  6072. return false;
  6073. FunctionType::ExtInfo EI =
  6074. unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
  6075. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6076. return true;
  6077. }
  6078. if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
  6079. if (!S.getLangOpts().CFProtectionBranch) {
  6080. S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
  6081. attr.setInvalid();
  6082. return true;
  6083. }
  6084. if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
  6085. return true;
  6086. // If this is not a function type, warning will be asserted by subject
  6087. // check.
  6088. if (!unwrapped.isFunctionType())
  6089. return true;
  6090. FunctionType::ExtInfo EI =
  6091. unwrapped.get()->getExtInfo().withNoCfCheck(true);
  6092. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6093. return true;
  6094. }
  6095. if (attr.getKind() == ParsedAttr::AT_Regparm) {
  6096. unsigned value;
  6097. if (S.CheckRegparmAttr(attr, value))
  6098. return true;
  6099. // Delay if this is not a function type.
  6100. if (!unwrapped.isFunctionType())
  6101. return false;
  6102. // Diagnose regparm with fastcall.
  6103. const FunctionType *fn = unwrapped.get();
  6104. CallingConv CC = fn->getCallConv();
  6105. if (CC == CC_X86FastCall) {
  6106. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6107. << FunctionType::getNameForCallConv(CC)
  6108. << "regparm";
  6109. attr.setInvalid();
  6110. return true;
  6111. }
  6112. FunctionType::ExtInfo EI =
  6113. unwrapped.get()->getExtInfo().withRegParm(value);
  6114. type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6115. return true;
  6116. }
  6117. if (attr.getKind() == ParsedAttr::AT_NoThrow) {
  6118. // Delay if this is not a function type.
  6119. if (!unwrapped.isFunctionType())
  6120. return false;
  6121. if (S.CheckAttrNoArgs(attr)) {
  6122. attr.setInvalid();
  6123. return true;
  6124. }
  6125. // Otherwise we can process right away.
  6126. auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
  6127. // MSVC ignores nothrow if it is in conflict with an explicit exception
  6128. // specification.
  6129. if (Proto->hasExceptionSpec()) {
  6130. switch (Proto->getExceptionSpecType()) {
  6131. case EST_None:
  6132. llvm_unreachable("This doesn't have an exception spec!");
  6133. case EST_DynamicNone:
  6134. case EST_BasicNoexcept:
  6135. case EST_NoexceptTrue:
  6136. case EST_NoThrow:
  6137. // Exception spec doesn't conflict with nothrow, so don't warn.
  6138. LLVM_FALLTHROUGH;
  6139. case EST_Unparsed:
  6140. case EST_Uninstantiated:
  6141. case EST_DependentNoexcept:
  6142. case EST_Unevaluated:
  6143. // We don't have enough information to properly determine if there is a
  6144. // conflict, so suppress the warning.
  6145. break;
  6146. case EST_Dynamic:
  6147. case EST_MSAny:
  6148. case EST_NoexceptFalse:
  6149. S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
  6150. break;
  6151. }
  6152. return true;
  6153. }
  6154. type = unwrapped.wrap(
  6155. S, S.Context
  6156. .getFunctionTypeWithExceptionSpec(
  6157. QualType{Proto, 0},
  6158. FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
  6159. ->getAs<FunctionType>());
  6160. return true;
  6161. }
  6162. // Delay if the type didn't work out to a function.
  6163. if (!unwrapped.isFunctionType()) return false;
  6164. // Otherwise, a calling convention.
  6165. CallingConv CC;
  6166. if (S.CheckCallingConvAttr(attr, CC))
  6167. return true;
  6168. const FunctionType *fn = unwrapped.get();
  6169. CallingConv CCOld = fn->getCallConv();
  6170. Attr *CCAttr = getCCTypeAttr(S.Context, attr);
  6171. if (CCOld != CC) {
  6172. // Error out on when there's already an attribute on the type
  6173. // and the CCs don't match.
  6174. if (S.getCallingConvAttributedType(type)) {
  6175. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6176. << FunctionType::getNameForCallConv(CC)
  6177. << FunctionType::getNameForCallConv(CCOld);
  6178. attr.setInvalid();
  6179. return true;
  6180. }
  6181. }
  6182. // Diagnose use of variadic functions with calling conventions that
  6183. // don't support them (e.g. because they're callee-cleanup).
  6184. // We delay warning about this on unprototyped function declarations
  6185. // until after redeclaration checking, just in case we pick up a
  6186. // prototype that way. And apparently we also "delay" warning about
  6187. // unprototyped function types in general, despite not necessarily having
  6188. // much ability to diagnose it later.
  6189. if (!supportsVariadicCall(CC)) {
  6190. const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
  6191. if (FnP && FnP->isVariadic()) {
  6192. // stdcall and fastcall are ignored with a warning for GCC and MS
  6193. // compatibility.
  6194. if (CC == CC_X86StdCall || CC == CC_X86FastCall)
  6195. return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
  6196. << FunctionType::getNameForCallConv(CC)
  6197. << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
  6198. attr.setInvalid();
  6199. return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
  6200. << FunctionType::getNameForCallConv(CC);
  6201. }
  6202. }
  6203. // Also diagnose fastcall with regparm.
  6204. if (CC == CC_X86FastCall && fn->getHasRegParm()) {
  6205. S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
  6206. << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
  6207. attr.setInvalid();
  6208. return true;
  6209. }
  6210. // Modify the CC from the wrapped function type, wrap it all back, and then
  6211. // wrap the whole thing in an AttributedType as written. The modified type
  6212. // might have a different CC if we ignored the attribute.
  6213. QualType Equivalent;
  6214. if (CCOld == CC) {
  6215. Equivalent = type;
  6216. } else {
  6217. auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
  6218. Equivalent =
  6219. unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
  6220. }
  6221. type = state.getAttributedType(CCAttr, type, Equivalent);
  6222. return true;
  6223. }
  6224. bool Sema::hasExplicitCallingConv(QualType T) {
  6225. const AttributedType *AT;
  6226. // Stop if we'd be stripping off a typedef sugar node to reach the
  6227. // AttributedType.
  6228. while ((AT = T->getAs<AttributedType>()) &&
  6229. AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
  6230. if (AT->isCallingConv())
  6231. return true;
  6232. T = AT->getModifiedType();
  6233. }
  6234. return false;
  6235. }
  6236. void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
  6237. SourceLocation Loc) {
  6238. FunctionTypeUnwrapper Unwrapped(*this, T);
  6239. const FunctionType *FT = Unwrapped.get();
  6240. bool IsVariadic = (isa<FunctionProtoType>(FT) &&
  6241. cast<FunctionProtoType>(FT)->isVariadic());
  6242. CallingConv CurCC = FT->getCallConv();
  6243. CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
  6244. if (CurCC == ToCC)
  6245. return;
  6246. // MS compiler ignores explicit calling convention attributes on structors. We
  6247. // should do the same.
  6248. if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
  6249. // Issue a warning on ignored calling convention -- except of __stdcall.
  6250. // Again, this is what MS compiler does.
  6251. if (CurCC != CC_X86StdCall)
  6252. Diag(Loc, diag::warn_cconv_unsupported)
  6253. << FunctionType::getNameForCallConv(CurCC)
  6254. << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
  6255. // Default adjustment.
  6256. } else {
  6257. // Only adjust types with the default convention. For example, on Windows
  6258. // we should adjust a __cdecl type to __thiscall for instance methods, and a
  6259. // __thiscall type to __cdecl for static methods.
  6260. CallingConv DefaultCC =
  6261. Context.getDefaultCallingConvention(IsVariadic, IsStatic);
  6262. if (CurCC != DefaultCC || DefaultCC == ToCC)
  6263. return;
  6264. if (hasExplicitCallingConv(T))
  6265. return;
  6266. }
  6267. FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
  6268. QualType Wrapped = Unwrapped.wrap(*this, FT);
  6269. T = Context.getAdjustedType(T, Wrapped);
  6270. }
  6271. /// HandleVectorSizeAttribute - this attribute is only applicable to integral
  6272. /// and float scalars, although arrays, pointers, and function return values are
  6273. /// allowed in conjunction with this construct. Aggregates with this attribute
  6274. /// are invalid, even if they are of the same size as a corresponding scalar.
  6275. /// The raw attribute should contain precisely 1 argument, the vector size for
  6276. /// the variable, measured in bytes. If curType and rawAttr are well formed,
  6277. /// this routine will return a new vector type.
  6278. static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
  6279. Sema &S) {
  6280. // Check the attribute arguments.
  6281. if (Attr.getNumArgs() != 1) {
  6282. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6283. << 1;
  6284. Attr.setInvalid();
  6285. return;
  6286. }
  6287. Expr *SizeExpr;
  6288. // Special case where the argument is a template id.
  6289. if (Attr.isArgIdent(0)) {
  6290. CXXScopeSpec SS;
  6291. SourceLocation TemplateKWLoc;
  6292. UnqualifiedId Id;
  6293. Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  6294. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  6295. Id, /*HasTrailingLParen=*/false,
  6296. /*IsAddressOfOperand=*/false);
  6297. if (Size.isInvalid())
  6298. return;
  6299. SizeExpr = Size.get();
  6300. } else {
  6301. SizeExpr = Attr.getArgAsExpr(0);
  6302. }
  6303. QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
  6304. if (!T.isNull())
  6305. CurType = T;
  6306. else
  6307. Attr.setInvalid();
  6308. }
  6309. /// Process the OpenCL-like ext_vector_type attribute when it occurs on
  6310. /// a type.
  6311. static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  6312. Sema &S) {
  6313. // check the attribute arguments.
  6314. if (Attr.getNumArgs() != 1) {
  6315. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6316. << 1;
  6317. return;
  6318. }
  6319. Expr *sizeExpr;
  6320. // Special case where the argument is a template id.
  6321. if (Attr.isArgIdent(0)) {
  6322. CXXScopeSpec SS;
  6323. SourceLocation TemplateKWLoc;
  6324. UnqualifiedId id;
  6325. id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
  6326. ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
  6327. id, /*HasTrailingLParen=*/false,
  6328. /*IsAddressOfOperand=*/false);
  6329. if (Size.isInvalid())
  6330. return;
  6331. sizeExpr = Size.get();
  6332. } else {
  6333. sizeExpr = Attr.getArgAsExpr(0);
  6334. }
  6335. // Create the vector type.
  6336. QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
  6337. if (!T.isNull())
  6338. CurType = T;
  6339. }
  6340. static bool isPermittedNeonBaseType(QualType &Ty,
  6341. VectorType::VectorKind VecKind, Sema &S) {
  6342. const BuiltinType *BTy = Ty->getAs<BuiltinType>();
  6343. if (!BTy)
  6344. return false;
  6345. llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
  6346. // Signed poly is mathematically wrong, but has been baked into some ABIs by
  6347. // now.
  6348. bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
  6349. Triple.getArch() == llvm::Triple::aarch64_be;
  6350. if (VecKind == VectorType::NeonPolyVector) {
  6351. if (IsPolyUnsigned) {
  6352. // AArch64 polynomial vectors are unsigned and support poly64.
  6353. return BTy->getKind() == BuiltinType::UChar ||
  6354. BTy->getKind() == BuiltinType::UShort ||
  6355. BTy->getKind() == BuiltinType::ULong ||
  6356. BTy->getKind() == BuiltinType::ULongLong;
  6357. } else {
  6358. // AArch32 polynomial vector are signed.
  6359. return BTy->getKind() == BuiltinType::SChar ||
  6360. BTy->getKind() == BuiltinType::Short;
  6361. }
  6362. }
  6363. // Non-polynomial vector types: the usual suspects are allowed, as well as
  6364. // float64_t on AArch64.
  6365. bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
  6366. Triple.getArch() == llvm::Triple::aarch64_be;
  6367. if (Is64Bit && BTy->getKind() == BuiltinType::Double)
  6368. return true;
  6369. return BTy->getKind() == BuiltinType::SChar ||
  6370. BTy->getKind() == BuiltinType::UChar ||
  6371. BTy->getKind() == BuiltinType::Short ||
  6372. BTy->getKind() == BuiltinType::UShort ||
  6373. BTy->getKind() == BuiltinType::Int ||
  6374. BTy->getKind() == BuiltinType::UInt ||
  6375. BTy->getKind() == BuiltinType::Long ||
  6376. BTy->getKind() == BuiltinType::ULong ||
  6377. BTy->getKind() == BuiltinType::LongLong ||
  6378. BTy->getKind() == BuiltinType::ULongLong ||
  6379. BTy->getKind() == BuiltinType::Float ||
  6380. BTy->getKind() == BuiltinType::Half;
  6381. }
  6382. /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
  6383. /// "neon_polyvector_type" attributes are used to create vector types that
  6384. /// are mangled according to ARM's ABI. Otherwise, these types are identical
  6385. /// to those created with the "vector_size" attribute. Unlike "vector_size"
  6386. /// the argument to these Neon attributes is the number of vector elements,
  6387. /// not the vector size in bytes. The vector width and element type must
  6388. /// match one of the standard Neon vector types.
  6389. static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  6390. Sema &S, VectorType::VectorKind VecKind) {
  6391. // Target must have NEON
  6392. if (!S.Context.getTargetInfo().hasFeature("neon")) {
  6393. S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
  6394. Attr.setInvalid();
  6395. return;
  6396. }
  6397. // Check the attribute arguments.
  6398. if (Attr.getNumArgs() != 1) {
  6399. S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
  6400. << 1;
  6401. Attr.setInvalid();
  6402. return;
  6403. }
  6404. // The number of elements must be an ICE.
  6405. Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
  6406. llvm::APSInt numEltsInt(32);
  6407. if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
  6408. !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
  6409. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  6410. << Attr << AANT_ArgumentIntegerConstant
  6411. << numEltsExpr->getSourceRange();
  6412. Attr.setInvalid();
  6413. return;
  6414. }
  6415. // Only certain element types are supported for Neon vectors.
  6416. if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
  6417. S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
  6418. Attr.setInvalid();
  6419. return;
  6420. }
  6421. // The total size of the vector must be 64 or 128 bits.
  6422. unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
  6423. unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
  6424. unsigned vecSize = typeSize * numElts;
  6425. if (vecSize != 64 && vecSize != 128) {
  6426. S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
  6427. Attr.setInvalid();
  6428. return;
  6429. }
  6430. CurType = S.Context.getVectorType(CurType, numElts, VecKind);
  6431. }
  6432. /// Handle OpenCL Access Qualifier Attribute.
  6433. static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
  6434. Sema &S) {
  6435. // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
  6436. if (!(CurType->isImageType() || CurType->isPipeType())) {
  6437. S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
  6438. Attr.setInvalid();
  6439. return;
  6440. }
  6441. if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
  6442. QualType BaseTy = TypedefTy->desugar();
  6443. std::string PrevAccessQual;
  6444. if (BaseTy->isPipeType()) {
  6445. if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
  6446. OpenCLAccessAttr *Attr =
  6447. TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
  6448. PrevAccessQual = Attr->getSpelling();
  6449. } else {
  6450. PrevAccessQual = "read_only";
  6451. }
  6452. } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
  6453. switch (ImgType->getKind()) {
  6454. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6455. case BuiltinType::Id: \
  6456. PrevAccessQual = #Access; \
  6457. break;
  6458. #include "clang/Basic/OpenCLImageTypes.def"
  6459. default:
  6460. llvm_unreachable("Unable to find corresponding image type.");
  6461. }
  6462. } else {
  6463. llvm_unreachable("unexpected type");
  6464. }
  6465. StringRef AttrName = Attr.getAttrName()->getName();
  6466. if (PrevAccessQual == AttrName.ltrim("_")) {
  6467. // Duplicated qualifiers
  6468. S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
  6469. << AttrName << Attr.getRange();
  6470. } else {
  6471. // Contradicting qualifiers
  6472. S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
  6473. }
  6474. S.Diag(TypedefTy->getDecl()->getBeginLoc(),
  6475. diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
  6476. } else if (CurType->isPipeType()) {
  6477. if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
  6478. QualType ElemType = CurType->getAs<PipeType>()->getElementType();
  6479. CurType = S.Context.getWritePipeType(ElemType);
  6480. }
  6481. }
  6482. }
  6483. static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
  6484. QualType &T, TypeAttrLocation TAL) {
  6485. Declarator &D = State.getDeclarator();
  6486. // Handle the cases where address space should not be deduced.
  6487. //
  6488. // The pointee type of a pointer type is always deduced since a pointer always
  6489. // points to some memory location which should has an address space.
  6490. //
  6491. // There are situations that at the point of certain declarations, the address
  6492. // space may be unknown and better to be left as default. For example, when
  6493. // defining a typedef or struct type, they are not associated with any
  6494. // specific address space. Later on, they may be used with any address space
  6495. // to declare a variable.
  6496. //
  6497. // The return value of a function is r-value, therefore should not have
  6498. // address space.
  6499. //
  6500. // The void type does not occupy memory, therefore should not have address
  6501. // space, except when it is used as a pointee type.
  6502. //
  6503. // Since LLVM assumes function type is in default address space, it should not
  6504. // have address space.
  6505. auto ChunkIndex = State.getCurrentChunkIndex();
  6506. bool IsPointee =
  6507. ChunkIndex > 0 &&
  6508. (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
  6509. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference ||
  6510. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer);
  6511. // For pointers/references to arrays the next chunk is always an array
  6512. // followed by any number of parentheses.
  6513. if (!IsPointee && ChunkIndex > 1) {
  6514. auto AdjustedCI = ChunkIndex - 1;
  6515. if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Array)
  6516. AdjustedCI--;
  6517. // Skip over all parentheses.
  6518. while (AdjustedCI > 0 &&
  6519. D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Paren)
  6520. AdjustedCI--;
  6521. if (D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Pointer ||
  6522. D.getTypeObject(AdjustedCI).Kind == DeclaratorChunk::Reference)
  6523. IsPointee = true;
  6524. }
  6525. bool IsFuncReturnType =
  6526. ChunkIndex > 0 &&
  6527. D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
  6528. bool IsFuncType =
  6529. ChunkIndex < D.getNumTypeObjects() &&
  6530. D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
  6531. if ( // Do not deduce addr space for function return type and function type,
  6532. // otherwise it will fail some sema check.
  6533. IsFuncReturnType || IsFuncType ||
  6534. // Do not deduce addr space for member types of struct, except the pointee
  6535. // type of a pointer member type or static data members.
  6536. (D.getContext() == DeclaratorContext::MemberContext &&
  6537. (!IsPointee &&
  6538. D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)) ||
  6539. // Do not deduce addr space of non-pointee in type alias because it
  6540. // doesn't define any object.
  6541. (D.getContext() == DeclaratorContext::AliasDeclContext && !IsPointee) ||
  6542. // Do not deduce addr space for types used to define a typedef and the
  6543. // typedef itself, except the pointee type of a pointer type which is used
  6544. // to define the typedef.
  6545. (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
  6546. !IsPointee) ||
  6547. // Do not deduce addr space of the void type, e.g. in f(void), otherwise
  6548. // it will fail some sema check.
  6549. (T->isVoidType() && !IsPointee) ||
  6550. // Do not deduce addr spaces for dependent types because they might end
  6551. // up instantiating to a type with an explicit address space qualifier.
  6552. // Except for pointer or reference types because the addr space in
  6553. // template argument can only belong to a pointee.
  6554. (T->isDependentType() && !T->isPointerType() && !T->isReferenceType()) ||
  6555. // Do not deduce addr space of decltype because it will be taken from
  6556. // its argument.
  6557. T->isDecltypeType() ||
  6558. // OpenCL spec v2.0 s6.9.b:
  6559. // The sampler type cannot be used with the __local and __global address
  6560. // space qualifiers.
  6561. // OpenCL spec v2.0 s6.13.14:
  6562. // Samplers can also be declared as global constants in the program
  6563. // source using the following syntax.
  6564. // const sampler_t <sampler name> = <value>
  6565. // In codegen, file-scope sampler type variable has special handing and
  6566. // does not rely on address space qualifier. On the other hand, deducing
  6567. // address space of const sampler file-scope variable as global address
  6568. // space causes spurious diagnostic about __global address space
  6569. // qualifier, therefore do not deduce address space of file-scope sampler
  6570. // type variable.
  6571. (D.getContext() == DeclaratorContext::FileContext && T->isSamplerT()))
  6572. return;
  6573. LangAS ImpAddr = LangAS::Default;
  6574. // Put OpenCL automatic variable in private address space.
  6575. // OpenCL v1.2 s6.5:
  6576. // The default address space name for arguments to a function in a
  6577. // program, or local variables of a function is __private. All function
  6578. // arguments shall be in the __private address space.
  6579. if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
  6580. !State.getSema().getLangOpts().OpenCLCPlusPlus) {
  6581. ImpAddr = LangAS::opencl_private;
  6582. } else {
  6583. // If address space is not set, OpenCL 2.0 defines non private default
  6584. // address spaces for some cases:
  6585. // OpenCL 2.0, section 6.5:
  6586. // The address space for a variable at program scope or a static variable
  6587. // inside a function can either be __global or __constant, but defaults to
  6588. // __global if not specified.
  6589. // (...)
  6590. // Pointers that are declared without pointing to a named address space
  6591. // point to the generic address space.
  6592. if (IsPointee) {
  6593. ImpAddr = LangAS::opencl_generic;
  6594. } else {
  6595. if (D.getContext() == DeclaratorContext::TemplateArgContext) {
  6596. // Do not deduce address space for non-pointee type in template arg.
  6597. } else if (D.getContext() == DeclaratorContext::FileContext) {
  6598. ImpAddr = LangAS::opencl_global;
  6599. } else {
  6600. if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
  6601. D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
  6602. ImpAddr = LangAS::opencl_global;
  6603. } else {
  6604. ImpAddr = LangAS::opencl_private;
  6605. }
  6606. }
  6607. }
  6608. }
  6609. T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
  6610. }
  6611. static void HandleLifetimeBoundAttr(TypeProcessingState &State,
  6612. QualType &CurType,
  6613. ParsedAttr &Attr) {
  6614. if (State.getDeclarator().isDeclarationOfFunction()) {
  6615. CurType = State.getAttributedType(
  6616. createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
  6617. CurType, CurType);
  6618. } else {
  6619. Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
  6620. }
  6621. }
  6622. static void processTypeAttrs(TypeProcessingState &state, QualType &type,
  6623. TypeAttrLocation TAL,
  6624. ParsedAttributesView &attrs) {
  6625. // Scan through and apply attributes to this type where it makes sense. Some
  6626. // attributes (such as __address_space__, __vector_size__, etc) apply to the
  6627. // type, but others can be present in the type specifiers even though they
  6628. // apply to the decl. Here we apply type attributes and ignore the rest.
  6629. // This loop modifies the list pretty frequently, but we still need to make
  6630. // sure we visit every element once. Copy the attributes list, and iterate
  6631. // over that.
  6632. ParsedAttributesView AttrsCopy{attrs};
  6633. state.setParsedNoDeref(false);
  6634. for (ParsedAttr &attr : AttrsCopy) {
  6635. // Skip attributes that were marked to be invalid.
  6636. if (attr.isInvalid())
  6637. continue;
  6638. if (attr.isCXX11Attribute()) {
  6639. // [[gnu::...]] attributes are treated as declaration attributes, so may
  6640. // not appertain to a DeclaratorChunk. If we handle them as type
  6641. // attributes, accept them in that position and diagnose the GCC
  6642. // incompatibility.
  6643. if (attr.isGNUScope()) {
  6644. bool IsTypeAttr = attr.isTypeAttr();
  6645. if (TAL == TAL_DeclChunk) {
  6646. state.getSema().Diag(attr.getLoc(),
  6647. IsTypeAttr
  6648. ? diag::warn_gcc_ignores_type_attr
  6649. : diag::warn_cxx11_gnu_attribute_on_type)
  6650. << attr;
  6651. if (!IsTypeAttr)
  6652. continue;
  6653. }
  6654. } else if (TAL != TAL_DeclChunk &&
  6655. attr.getKind() != ParsedAttr::AT_AddressSpace) {
  6656. // Otherwise, only consider type processing for a C++11 attribute if
  6657. // it's actually been applied to a type.
  6658. // We also allow C++11 address_space attributes to pass through.
  6659. continue;
  6660. }
  6661. }
  6662. // If this is an attribute we can handle, do so now,
  6663. // otherwise, add it to the FnAttrs list for rechaining.
  6664. switch (attr.getKind()) {
  6665. default:
  6666. // A C++11 attribute on a declarator chunk must appertain to a type.
  6667. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
  6668. state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
  6669. << attr;
  6670. attr.setUsedAsTypeAttr();
  6671. }
  6672. break;
  6673. case ParsedAttr::UnknownAttribute:
  6674. if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
  6675. state.getSema().Diag(attr.getLoc(),
  6676. diag::warn_unknown_attribute_ignored)
  6677. << attr;
  6678. break;
  6679. case ParsedAttr::IgnoredAttribute:
  6680. break;
  6681. case ParsedAttr::AT_MayAlias:
  6682. // FIXME: This attribute needs to actually be handled, but if we ignore
  6683. // it it breaks large amounts of Linux software.
  6684. attr.setUsedAsTypeAttr();
  6685. break;
  6686. case ParsedAttr::AT_OpenCLPrivateAddressSpace:
  6687. case ParsedAttr::AT_OpenCLGlobalAddressSpace:
  6688. case ParsedAttr::AT_OpenCLLocalAddressSpace:
  6689. case ParsedAttr::AT_OpenCLConstantAddressSpace:
  6690. case ParsedAttr::AT_OpenCLGenericAddressSpace:
  6691. case ParsedAttr::AT_AddressSpace:
  6692. HandleAddressSpaceTypeAttribute(type, attr, state);
  6693. attr.setUsedAsTypeAttr();
  6694. break;
  6695. OBJC_POINTER_TYPE_ATTRS_CASELIST:
  6696. if (!handleObjCPointerTypeAttr(state, attr, type))
  6697. distributeObjCPointerTypeAttr(state, attr, type);
  6698. attr.setUsedAsTypeAttr();
  6699. break;
  6700. case ParsedAttr::AT_VectorSize:
  6701. HandleVectorSizeAttr(type, attr, state.getSema());
  6702. attr.setUsedAsTypeAttr();
  6703. break;
  6704. case ParsedAttr::AT_ExtVectorType:
  6705. HandleExtVectorTypeAttr(type, attr, state.getSema());
  6706. attr.setUsedAsTypeAttr();
  6707. break;
  6708. case ParsedAttr::AT_NeonVectorType:
  6709. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  6710. VectorType::NeonVector);
  6711. attr.setUsedAsTypeAttr();
  6712. break;
  6713. case ParsedAttr::AT_NeonPolyVectorType:
  6714. HandleNeonVectorTypeAttr(type, attr, state.getSema(),
  6715. VectorType::NeonPolyVector);
  6716. attr.setUsedAsTypeAttr();
  6717. break;
  6718. case ParsedAttr::AT_OpenCLAccess:
  6719. HandleOpenCLAccessAttr(type, attr, state.getSema());
  6720. attr.setUsedAsTypeAttr();
  6721. break;
  6722. case ParsedAttr::AT_LifetimeBound:
  6723. if (TAL == TAL_DeclChunk)
  6724. HandleLifetimeBoundAttr(state, type, attr);
  6725. break;
  6726. case ParsedAttr::AT_NoDeref: {
  6727. ASTContext &Ctx = state.getSema().Context;
  6728. type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
  6729. type, type);
  6730. attr.setUsedAsTypeAttr();
  6731. state.setParsedNoDeref(true);
  6732. break;
  6733. }
  6734. MS_TYPE_ATTRS_CASELIST:
  6735. if (!handleMSPointerTypeQualifierAttr(state, attr, type))
  6736. attr.setUsedAsTypeAttr();
  6737. break;
  6738. NULLABILITY_TYPE_ATTRS_CASELIST:
  6739. // Either add nullability here or try to distribute it. We
  6740. // don't want to distribute the nullability specifier past any
  6741. // dependent type, because that complicates the user model.
  6742. if (type->canHaveNullability() || type->isDependentType() ||
  6743. type->isArrayType() ||
  6744. !distributeNullabilityTypeAttr(state, type, attr)) {
  6745. unsigned endIndex;
  6746. if (TAL == TAL_DeclChunk)
  6747. endIndex = state.getCurrentChunkIndex();
  6748. else
  6749. endIndex = state.getDeclarator().getNumTypeObjects();
  6750. bool allowOnArrayType =
  6751. state.getDeclarator().isPrototypeContext() &&
  6752. !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
  6753. if (checkNullabilityTypeSpecifier(
  6754. state,
  6755. type,
  6756. attr,
  6757. allowOnArrayType)) {
  6758. attr.setInvalid();
  6759. }
  6760. attr.setUsedAsTypeAttr();
  6761. }
  6762. break;
  6763. case ParsedAttr::AT_ObjCKindOf:
  6764. // '__kindof' must be part of the decl-specifiers.
  6765. switch (TAL) {
  6766. case TAL_DeclSpec:
  6767. break;
  6768. case TAL_DeclChunk:
  6769. case TAL_DeclName:
  6770. state.getSema().Diag(attr.getLoc(),
  6771. diag::err_objc_kindof_wrong_position)
  6772. << FixItHint::CreateRemoval(attr.getLoc())
  6773. << FixItHint::CreateInsertion(
  6774. state.getDeclarator().getDeclSpec().getBeginLoc(),
  6775. "__kindof ");
  6776. break;
  6777. }
  6778. // Apply it regardless.
  6779. if (checkObjCKindOfType(state, type, attr))
  6780. attr.setInvalid();
  6781. break;
  6782. case ParsedAttr::AT_NoThrow:
  6783. // Exception Specifications aren't generally supported in C mode throughout
  6784. // clang, so revert to attribute-based handling for C.
  6785. if (!state.getSema().getLangOpts().CPlusPlus)
  6786. break;
  6787. LLVM_FALLTHROUGH;
  6788. FUNCTION_TYPE_ATTRS_CASELIST:
  6789. attr.setUsedAsTypeAttr();
  6790. // Never process function type attributes as part of the
  6791. // declaration-specifiers.
  6792. if (TAL == TAL_DeclSpec)
  6793. distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
  6794. // Otherwise, handle the possible delays.
  6795. else if (!handleFunctionTypeAttr(state, attr, type))
  6796. distributeFunctionTypeAttr(state, attr, type);
  6797. break;
  6798. }
  6799. // Handle attributes that are defined in a macro. We do not want this to be
  6800. // applied to ObjC builtin attributes.
  6801. if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
  6802. !type.getQualifiers().hasObjCLifetime() &&
  6803. !type.getQualifiers().hasObjCGCAttr() &&
  6804. attr.getKind() != ParsedAttr::AT_ObjCGC &&
  6805. attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
  6806. const IdentifierInfo *MacroII = attr.getMacroIdentifier();
  6807. type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
  6808. state.setExpansionLocForMacroQualifiedType(
  6809. cast<MacroQualifiedType>(type.getTypePtr()),
  6810. attr.getMacroExpansionLoc());
  6811. }
  6812. }
  6813. if (!state.getSema().getLangOpts().OpenCL ||
  6814. type.getAddressSpace() != LangAS::Default)
  6815. return;
  6816. deduceOpenCLImplicitAddrSpace(state, type, TAL);
  6817. }
  6818. void Sema::completeExprArrayBound(Expr *E) {
  6819. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  6820. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  6821. if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
  6822. auto *Def = Var->getDefinition();
  6823. if (!Def) {
  6824. SourceLocation PointOfInstantiation = E->getExprLoc();
  6825. runWithSufficientStackSpace(PointOfInstantiation, [&] {
  6826. InstantiateVariableDefinition(PointOfInstantiation, Var);
  6827. });
  6828. Def = Var->getDefinition();
  6829. // If we don't already have a point of instantiation, and we managed
  6830. // to instantiate a definition, this is the point of instantiation.
  6831. // Otherwise, we don't request an end-of-TU instantiation, so this is
  6832. // not a point of instantiation.
  6833. // FIXME: Is this really the right behavior?
  6834. if (Var->getPointOfInstantiation().isInvalid() && Def) {
  6835. assert(Var->getTemplateSpecializationKind() ==
  6836. TSK_ImplicitInstantiation &&
  6837. "explicit instantiation with no point of instantiation");
  6838. Var->setTemplateSpecializationKind(
  6839. Var->getTemplateSpecializationKind(), PointOfInstantiation);
  6840. }
  6841. }
  6842. // Update the type to the definition's type both here and within the
  6843. // expression.
  6844. if (Def) {
  6845. DRE->setDecl(Def);
  6846. QualType T = Def->getType();
  6847. DRE->setType(T);
  6848. // FIXME: Update the type on all intervening expressions.
  6849. E->setType(T);
  6850. }
  6851. // We still go on to try to complete the type independently, as it
  6852. // may also require instantiations or diagnostics if it remains
  6853. // incomplete.
  6854. }
  6855. }
  6856. }
  6857. }
  6858. /// Ensure that the type of the given expression is complete.
  6859. ///
  6860. /// This routine checks whether the expression \p E has a complete type. If the
  6861. /// expression refers to an instantiable construct, that instantiation is
  6862. /// performed as needed to complete its type. Furthermore
  6863. /// Sema::RequireCompleteType is called for the expression's type (or in the
  6864. /// case of a reference type, the referred-to type).
  6865. ///
  6866. /// \param E The expression whose type is required to be complete.
  6867. /// \param Diagnoser The object that will emit a diagnostic if the type is
  6868. /// incomplete.
  6869. ///
  6870. /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
  6871. /// otherwise.
  6872. bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
  6873. QualType T = E->getType();
  6874. // Incomplete array types may be completed by the initializer attached to
  6875. // their definitions. For static data members of class templates and for
  6876. // variable templates, we need to instantiate the definition to get this
  6877. // initializer and complete the type.
  6878. if (T->isIncompleteArrayType()) {
  6879. completeExprArrayBound(E);
  6880. T = E->getType();
  6881. }
  6882. // FIXME: Are there other cases which require instantiating something other
  6883. // than the type to complete the type of an expression?
  6884. return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
  6885. }
  6886. bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
  6887. BoundTypeDiagnoser<> Diagnoser(DiagID);
  6888. return RequireCompleteExprType(E, Diagnoser);
  6889. }
  6890. /// Ensure that the type T is a complete type.
  6891. ///
  6892. /// This routine checks whether the type @p T is complete in any
  6893. /// context where a complete type is required. If @p T is a complete
  6894. /// type, returns false. If @p T is a class template specialization,
  6895. /// this routine then attempts to perform class template
  6896. /// instantiation. If instantiation fails, or if @p T is incomplete
  6897. /// and cannot be completed, issues the diagnostic @p diag (giving it
  6898. /// the type @p T) and returns true.
  6899. ///
  6900. /// @param Loc The location in the source that the incomplete type
  6901. /// diagnostic should refer to.
  6902. ///
  6903. /// @param T The type that this routine is examining for completeness.
  6904. ///
  6905. /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
  6906. /// @c false otherwise.
  6907. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  6908. TypeDiagnoser &Diagnoser) {
  6909. if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
  6910. return true;
  6911. if (const TagType *Tag = T->getAs<TagType>()) {
  6912. if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
  6913. Tag->getDecl()->setCompleteDefinitionRequired();
  6914. Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
  6915. }
  6916. }
  6917. return false;
  6918. }
  6919. bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
  6920. llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
  6921. if (!Suggested)
  6922. return false;
  6923. // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
  6924. // and isolate from other C++ specific checks.
  6925. StructuralEquivalenceContext Ctx(
  6926. D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
  6927. StructuralEquivalenceKind::Default,
  6928. false /*StrictTypeSpelling*/, true /*Complain*/,
  6929. true /*ErrorOnTagTypeMismatch*/);
  6930. return Ctx.IsEquivalent(D, Suggested);
  6931. }
  6932. /// Determine whether there is any declaration of \p D that was ever a
  6933. /// definition (perhaps before module merging) and is currently visible.
  6934. /// \param D The definition of the entity.
  6935. /// \param Suggested Filled in with the declaration that should be made visible
  6936. /// in order to provide a definition of this entity.
  6937. /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
  6938. /// not defined. This only matters for enums with a fixed underlying
  6939. /// type, since in all other cases, a type is complete if and only if it
  6940. /// is defined.
  6941. bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
  6942. bool OnlyNeedComplete) {
  6943. // Easy case: if we don't have modules, all declarations are visible.
  6944. if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
  6945. return true;
  6946. // If this definition was instantiated from a template, map back to the
  6947. // pattern from which it was instantiated.
  6948. if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
  6949. // We're in the middle of defining it; this definition should be treated
  6950. // as visible.
  6951. return true;
  6952. } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  6953. if (auto *Pattern = RD->getTemplateInstantiationPattern())
  6954. RD = Pattern;
  6955. D = RD->getDefinition();
  6956. } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
  6957. if (auto *Pattern = ED->getTemplateInstantiationPattern())
  6958. ED = Pattern;
  6959. if (OnlyNeedComplete && ED->isFixed()) {
  6960. // If the enum has a fixed underlying type, and we're only looking for a
  6961. // complete type (not a definition), any visible declaration of it will
  6962. // do.
  6963. *Suggested = nullptr;
  6964. for (auto *Redecl : ED->redecls()) {
  6965. if (isVisible(Redecl))
  6966. return true;
  6967. if (Redecl->isThisDeclarationADefinition() ||
  6968. (Redecl->isCanonicalDecl() && !*Suggested))
  6969. *Suggested = Redecl;
  6970. }
  6971. return false;
  6972. }
  6973. D = ED->getDefinition();
  6974. } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6975. if (auto *Pattern = FD->getTemplateInstantiationPattern())
  6976. FD = Pattern;
  6977. D = FD->getDefinition();
  6978. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  6979. if (auto *Pattern = VD->getTemplateInstantiationPattern())
  6980. VD = Pattern;
  6981. D = VD->getDefinition();
  6982. }
  6983. assert(D && "missing definition for pattern of instantiated definition");
  6984. *Suggested = D;
  6985. auto DefinitionIsVisible = [&] {
  6986. // The (primary) definition might be in a visible module.
  6987. if (isVisible(D))
  6988. return true;
  6989. // A visible module might have a merged definition instead.
  6990. if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
  6991. : hasVisibleMergedDefinition(D)) {
  6992. if (CodeSynthesisContexts.empty() &&
  6993. !getLangOpts().ModulesLocalVisibility) {
  6994. // Cache the fact that this definition is implicitly visible because
  6995. // there is a visible merged definition.
  6996. D->setVisibleDespiteOwningModule();
  6997. }
  6998. return true;
  6999. }
  7000. return false;
  7001. };
  7002. if (DefinitionIsVisible())
  7003. return true;
  7004. // The external source may have additional definitions of this entity that are
  7005. // visible, so complete the redeclaration chain now and ask again.
  7006. if (auto *Source = Context.getExternalSource()) {
  7007. Source->CompleteRedeclChain(D);
  7008. return DefinitionIsVisible();
  7009. }
  7010. return false;
  7011. }
  7012. /// Locks in the inheritance model for the given class and all of its bases.
  7013. static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
  7014. RD = RD->getMostRecentNonInjectedDecl();
  7015. if (!RD->hasAttr<MSInheritanceAttr>()) {
  7016. MSInheritanceAttr::Spelling IM;
  7017. switch (S.MSPointerToMemberRepresentationMethod) {
  7018. case LangOptions::PPTMK_BestCase:
  7019. IM = RD->calculateInheritanceModel();
  7020. break;
  7021. case LangOptions::PPTMK_FullGeneralitySingleInheritance:
  7022. IM = MSInheritanceAttr::Keyword_single_inheritance;
  7023. break;
  7024. case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
  7025. IM = MSInheritanceAttr::Keyword_multiple_inheritance;
  7026. break;
  7027. case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
  7028. IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
  7029. break;
  7030. }
  7031. SourceRange Loc =
  7032. S.ImplicitMSInheritanceAttrLoc.isValid()
  7033. ? S.ImplicitMSInheritanceAttrLoc
  7034. : RD->getSourceRange();
  7035. RD->addAttr(MSInheritanceAttr::CreateImplicit(
  7036. S.getASTContext(),
  7037. /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
  7038. LangOptions::PPTMK_BestCase,
  7039. Loc, AttributeCommonInfo::AS_Microsoft, IM));
  7040. S.Consumer.AssignInheritanceModel(RD);
  7041. }
  7042. }
  7043. /// The implementation of RequireCompleteType
  7044. bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
  7045. TypeDiagnoser *Diagnoser) {
  7046. // FIXME: Add this assertion to make sure we always get instantiation points.
  7047. // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
  7048. // FIXME: Add this assertion to help us flush out problems with
  7049. // checking for dependent types and type-dependent expressions.
  7050. //
  7051. // assert(!T->isDependentType() &&
  7052. // "Can't ask whether a dependent type is complete");
  7053. if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
  7054. if (!MPTy->getClass()->isDependentType()) {
  7055. if (getLangOpts().CompleteMemberPointers &&
  7056. !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
  7057. RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
  7058. diag::err_memptr_incomplete))
  7059. return true;
  7060. // We lock in the inheritance model once somebody has asked us to ensure
  7061. // that a pointer-to-member type is complete.
  7062. if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
  7063. (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
  7064. assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
  7065. }
  7066. }
  7067. }
  7068. NamedDecl *Def = nullptr;
  7069. bool Incomplete = T->isIncompleteType(&Def);
  7070. // Check that any necessary explicit specializations are visible. For an
  7071. // enum, we just need the declaration, so don't check this.
  7072. if (Def && !isa<EnumDecl>(Def))
  7073. checkSpecializationVisibility(Loc, Def);
  7074. // If we have a complete type, we're done.
  7075. if (!Incomplete) {
  7076. // If we know about the definition but it is not visible, complain.
  7077. NamedDecl *SuggestedDef = nullptr;
  7078. if (Def &&
  7079. !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
  7080. // If the user is going to see an error here, recover by making the
  7081. // definition visible.
  7082. bool TreatAsComplete = Diagnoser && !isSFINAEContext();
  7083. if (Diagnoser && SuggestedDef)
  7084. diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
  7085. /*Recover*/TreatAsComplete);
  7086. return !TreatAsComplete;
  7087. } else if (Def && !TemplateInstCallbacks.empty()) {
  7088. CodeSynthesisContext TempInst;
  7089. TempInst.Kind = CodeSynthesisContext::Memoization;
  7090. TempInst.Template = Def;
  7091. TempInst.Entity = Def;
  7092. TempInst.PointOfInstantiation = Loc;
  7093. atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
  7094. atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
  7095. }
  7096. return false;
  7097. }
  7098. TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
  7099. ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
  7100. // Give the external source a chance to provide a definition of the type.
  7101. // This is kept separate from completing the redeclaration chain so that
  7102. // external sources such as LLDB can avoid synthesizing a type definition
  7103. // unless it's actually needed.
  7104. if (Tag || IFace) {
  7105. // Avoid diagnosing invalid decls as incomplete.
  7106. if (Def->isInvalidDecl())
  7107. return true;
  7108. // Give the external AST source a chance to complete the type.
  7109. if (auto *Source = Context.getExternalSource()) {
  7110. if (Tag && Tag->hasExternalLexicalStorage())
  7111. Source->CompleteType(Tag);
  7112. if (IFace && IFace->hasExternalLexicalStorage())
  7113. Source->CompleteType(IFace);
  7114. // If the external source completed the type, go through the motions
  7115. // again to ensure we're allowed to use the completed type.
  7116. if (!T->isIncompleteType())
  7117. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  7118. }
  7119. }
  7120. // If we have a class template specialization or a class member of a
  7121. // class template specialization, or an array with known size of such,
  7122. // try to instantiate it.
  7123. if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
  7124. bool Instantiated = false;
  7125. bool Diagnosed = false;
  7126. if (RD->isDependentContext()) {
  7127. // Don't try to instantiate a dependent class (eg, a member template of
  7128. // an instantiated class template specialization).
  7129. // FIXME: Can this ever happen?
  7130. } else if (auto *ClassTemplateSpec =
  7131. dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  7132. if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
  7133. runWithSufficientStackSpace(Loc, [&] {
  7134. Diagnosed = InstantiateClassTemplateSpecialization(
  7135. Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
  7136. /*Complain=*/Diagnoser);
  7137. });
  7138. Instantiated = true;
  7139. }
  7140. } else {
  7141. CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
  7142. if (!RD->isBeingDefined() && Pattern) {
  7143. MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
  7144. assert(MSI && "Missing member specialization information?");
  7145. // This record was instantiated from a class within a template.
  7146. if (MSI->getTemplateSpecializationKind() !=
  7147. TSK_ExplicitSpecialization) {
  7148. runWithSufficientStackSpace(Loc, [&] {
  7149. Diagnosed = InstantiateClass(Loc, RD, Pattern,
  7150. getTemplateInstantiationArgs(RD),
  7151. TSK_ImplicitInstantiation,
  7152. /*Complain=*/Diagnoser);
  7153. });
  7154. Instantiated = true;
  7155. }
  7156. }
  7157. }
  7158. if (Instantiated) {
  7159. // Instantiate* might have already complained that the template is not
  7160. // defined, if we asked it to.
  7161. if (Diagnoser && Diagnosed)
  7162. return true;
  7163. // If we instantiated a definition, check that it's usable, even if
  7164. // instantiation produced an error, so that repeated calls to this
  7165. // function give consistent answers.
  7166. if (!T->isIncompleteType())
  7167. return RequireCompleteTypeImpl(Loc, T, Diagnoser);
  7168. }
  7169. }
  7170. // FIXME: If we didn't instantiate a definition because of an explicit
  7171. // specialization declaration, check that it's visible.
  7172. if (!Diagnoser)
  7173. return true;
  7174. Diagnoser->diagnose(*this, Loc, T);
  7175. // If the type was a forward declaration of a class/struct/union
  7176. // type, produce a note.
  7177. if (Tag && !Tag->isInvalidDecl())
  7178. Diag(Tag->getLocation(),
  7179. Tag->isBeingDefined() ? diag::note_type_being_defined
  7180. : diag::note_forward_declaration)
  7181. << Context.getTagDeclType(Tag);
  7182. // If the Objective-C class was a forward declaration, produce a note.
  7183. if (IFace && !IFace->isInvalidDecl())
  7184. Diag(IFace->getLocation(), diag::note_forward_class);
  7185. // If we have external information that we can use to suggest a fix,
  7186. // produce a note.
  7187. if (ExternalSource)
  7188. ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
  7189. return true;
  7190. }
  7191. bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
  7192. unsigned DiagID) {
  7193. BoundTypeDiagnoser<> Diagnoser(DiagID);
  7194. return RequireCompleteType(Loc, T, Diagnoser);
  7195. }
  7196. /// Get diagnostic %select index for tag kind for
  7197. /// literal type diagnostic message.
  7198. /// WARNING: Indexes apply to particular diagnostics only!
  7199. ///
  7200. /// \returns diagnostic %select index.
  7201. static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
  7202. switch (Tag) {
  7203. case TTK_Struct: return 0;
  7204. case TTK_Interface: return 1;
  7205. case TTK_Class: return 2;
  7206. default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
  7207. }
  7208. }
  7209. /// Ensure that the type T is a literal type.
  7210. ///
  7211. /// This routine checks whether the type @p T is a literal type. If @p T is an
  7212. /// incomplete type, an attempt is made to complete it. If @p T is a literal
  7213. /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
  7214. /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
  7215. /// it the type @p T), along with notes explaining why the type is not a
  7216. /// literal type, and returns true.
  7217. ///
  7218. /// @param Loc The location in the source that the non-literal type
  7219. /// diagnostic should refer to.
  7220. ///
  7221. /// @param T The type that this routine is examining for literalness.
  7222. ///
  7223. /// @param Diagnoser Emits a diagnostic if T is not a literal type.
  7224. ///
  7225. /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
  7226. /// @c false otherwise.
  7227. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
  7228. TypeDiagnoser &Diagnoser) {
  7229. assert(!T->isDependentType() && "type should not be dependent");
  7230. QualType ElemType = Context.getBaseElementType(T);
  7231. if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
  7232. T->isLiteralType(Context))
  7233. return false;
  7234. Diagnoser.diagnose(*this, Loc, T);
  7235. if (T->isVariableArrayType())
  7236. return true;
  7237. const RecordType *RT = ElemType->getAs<RecordType>();
  7238. if (!RT)
  7239. return true;
  7240. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  7241. // A partially-defined class type can't be a literal type, because a literal
  7242. // class type must have a trivial destructor (which can't be checked until
  7243. // the class definition is complete).
  7244. if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
  7245. return true;
  7246. // [expr.prim.lambda]p3:
  7247. // This class type is [not] a literal type.
  7248. if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
  7249. Diag(RD->getLocation(), diag::note_non_literal_lambda);
  7250. return true;
  7251. }
  7252. // If the class has virtual base classes, then it's not an aggregate, and
  7253. // cannot have any constexpr constructors or a trivial default constructor,
  7254. // so is non-literal. This is better to diagnose than the resulting absence
  7255. // of constexpr constructors.
  7256. if (RD->getNumVBases()) {
  7257. Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
  7258. << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
  7259. for (const auto &I : RD->vbases())
  7260. Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
  7261. << I.getSourceRange();
  7262. } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
  7263. !RD->hasTrivialDefaultConstructor()) {
  7264. Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
  7265. } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
  7266. for (const auto &I : RD->bases()) {
  7267. if (!I.getType()->isLiteralType(Context)) {
  7268. Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
  7269. << RD << I.getType() << I.getSourceRange();
  7270. return true;
  7271. }
  7272. }
  7273. for (const auto *I : RD->fields()) {
  7274. if (!I->getType()->isLiteralType(Context) ||
  7275. I->getType().isVolatileQualified()) {
  7276. Diag(I->getLocation(), diag::note_non_literal_field)
  7277. << RD << I << I->getType()
  7278. << I->getType().isVolatileQualified();
  7279. return true;
  7280. }
  7281. }
  7282. } else if (getLangOpts().CPlusPlus2a ? !RD->hasConstexprDestructor()
  7283. : !RD->hasTrivialDestructor()) {
  7284. // All fields and bases are of literal types, so have trivial or constexpr
  7285. // destructors. If this class's destructor is non-trivial / non-constexpr,
  7286. // it must be user-declared.
  7287. CXXDestructorDecl *Dtor = RD->getDestructor();
  7288. assert(Dtor && "class has literal fields and bases but no dtor?");
  7289. if (!Dtor)
  7290. return true;
  7291. if (getLangOpts().CPlusPlus2a) {
  7292. Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
  7293. << RD;
  7294. } else {
  7295. Diag(Dtor->getLocation(), Dtor->isUserProvided()
  7296. ? diag::note_non_literal_user_provided_dtor
  7297. : diag::note_non_literal_nontrivial_dtor)
  7298. << RD;
  7299. if (!Dtor->isUserProvided())
  7300. SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
  7301. /*Diagnose*/ true);
  7302. }
  7303. }
  7304. return true;
  7305. }
  7306. bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
  7307. BoundTypeDiagnoser<> Diagnoser(DiagID);
  7308. return RequireLiteralType(Loc, T, Diagnoser);
  7309. }
  7310. /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
  7311. /// by the nested-name-specifier contained in SS, and that is (re)declared by
  7312. /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
  7313. QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
  7314. const CXXScopeSpec &SS, QualType T,
  7315. TagDecl *OwnedTagDecl) {
  7316. if (T.isNull())
  7317. return T;
  7318. NestedNameSpecifier *NNS;
  7319. if (SS.isValid())
  7320. NNS = SS.getScopeRep();
  7321. else {
  7322. if (Keyword == ETK_None)
  7323. return T;
  7324. NNS = nullptr;
  7325. }
  7326. return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
  7327. }
  7328. QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
  7329. assert(!E->hasPlaceholderType() && "unexpected placeholder");
  7330. if (!getLangOpts().CPlusPlus && E->refersToBitField())
  7331. Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
  7332. if (!E->isTypeDependent()) {
  7333. QualType T = E->getType();
  7334. if (const TagType *TT = T->getAs<TagType>())
  7335. DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
  7336. }
  7337. return Context.getTypeOfExprType(E);
  7338. }
  7339. /// getDecltypeForExpr - Given an expr, will return the decltype for
  7340. /// that expression, according to the rules in C++11
  7341. /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
  7342. static QualType getDecltypeForExpr(Sema &S, Expr *E) {
  7343. if (E->isTypeDependent())
  7344. return S.Context.DependentTy;
  7345. // C++11 [dcl.type.simple]p4:
  7346. // The type denoted by decltype(e) is defined as follows:
  7347. //
  7348. // - if e is an unparenthesized id-expression or an unparenthesized class
  7349. // member access (5.2.5), decltype(e) is the type of the entity named
  7350. // by e. If there is no such entity, or if e names a set of overloaded
  7351. // functions, the program is ill-formed;
  7352. //
  7353. // We apply the same rules for Objective-C ivar and property references.
  7354. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  7355. const ValueDecl *VD = DRE->getDecl();
  7356. return VD->getType();
  7357. } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
  7358. if (const ValueDecl *VD = ME->getMemberDecl())
  7359. if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
  7360. return VD->getType();
  7361. } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
  7362. return IR->getDecl()->getType();
  7363. } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
  7364. if (PR->isExplicitProperty())
  7365. return PR->getExplicitProperty()->getType();
  7366. } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
  7367. return PE->getType();
  7368. }
  7369. // C++11 [expr.lambda.prim]p18:
  7370. // Every occurrence of decltype((x)) where x is a possibly
  7371. // parenthesized id-expression that names an entity of automatic
  7372. // storage duration is treated as if x were transformed into an
  7373. // access to a corresponding data member of the closure type that
  7374. // would have been declared if x were an odr-use of the denoted
  7375. // entity.
  7376. using namespace sema;
  7377. if (S.getCurLambda()) {
  7378. if (isa<ParenExpr>(E)) {
  7379. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
  7380. if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
  7381. QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
  7382. if (!T.isNull())
  7383. return S.Context.getLValueReferenceType(T);
  7384. }
  7385. }
  7386. }
  7387. }
  7388. // C++11 [dcl.type.simple]p4:
  7389. // [...]
  7390. QualType T = E->getType();
  7391. switch (E->getValueKind()) {
  7392. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  7393. // type of e;
  7394. case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
  7395. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  7396. // type of e;
  7397. case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
  7398. // - otherwise, decltype(e) is the type of e.
  7399. case VK_RValue: break;
  7400. }
  7401. return T;
  7402. }
  7403. QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
  7404. bool AsUnevaluated) {
  7405. assert(!E->hasPlaceholderType() && "unexpected placeholder");
  7406. if (AsUnevaluated && CodeSynthesisContexts.empty() &&
  7407. E->HasSideEffects(Context, false)) {
  7408. // The expression operand for decltype is in an unevaluated expression
  7409. // context, so side effects could result in unintended consequences.
  7410. Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
  7411. }
  7412. return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
  7413. }
  7414. QualType Sema::BuildUnaryTransformType(QualType BaseType,
  7415. UnaryTransformType::UTTKind UKind,
  7416. SourceLocation Loc) {
  7417. switch (UKind) {
  7418. case UnaryTransformType::EnumUnderlyingType:
  7419. if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
  7420. Diag(Loc, diag::err_only_enums_have_underlying_types);
  7421. return QualType();
  7422. } else {
  7423. QualType Underlying = BaseType;
  7424. if (!BaseType->isDependentType()) {
  7425. // The enum could be incomplete if we're parsing its definition or
  7426. // recovering from an error.
  7427. NamedDecl *FwdDecl = nullptr;
  7428. if (BaseType->isIncompleteType(&FwdDecl)) {
  7429. Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
  7430. Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
  7431. return QualType();
  7432. }
  7433. EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
  7434. assert(ED && "EnumType has no EnumDecl");
  7435. DiagnoseUseOfDecl(ED, Loc);
  7436. Underlying = ED->getIntegerType();
  7437. assert(!Underlying.isNull());
  7438. }
  7439. return Context.getUnaryTransformType(BaseType, Underlying,
  7440. UnaryTransformType::EnumUnderlyingType);
  7441. }
  7442. }
  7443. llvm_unreachable("unknown unary transform type");
  7444. }
  7445. QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
  7446. if (!T->isDependentType()) {
  7447. // FIXME: It isn't entirely clear whether incomplete atomic types
  7448. // are allowed or not; for simplicity, ban them for the moment.
  7449. if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
  7450. return QualType();
  7451. int DisallowedKind = -1;
  7452. if (T->isArrayType())
  7453. DisallowedKind = 1;
  7454. else if (T->isFunctionType())
  7455. DisallowedKind = 2;
  7456. else if (T->isReferenceType())
  7457. DisallowedKind = 3;
  7458. else if (T->isAtomicType())
  7459. DisallowedKind = 4;
  7460. else if (T.hasQualifiers())
  7461. DisallowedKind = 5;
  7462. else if (!T.isTriviallyCopyableType(Context))
  7463. // Some other non-trivially-copyable type (probably a C++ class)
  7464. DisallowedKind = 6;
  7465. if (DisallowedKind != -1) {
  7466. Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
  7467. return QualType();
  7468. }
  7469. // FIXME: Do we need any handling for ARC here?
  7470. }
  7471. // Build the pointer type.
  7472. return Context.getAtomicType(T);
  7473. }