SemaType.cpp 298 KB

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