SemaType.cpp 296 KB

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