ASTContext.cpp 326 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883
  1. //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
  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 the ASTContext interface.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/AST/ASTContext.h"
  14. #include "CXXABI.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/CharUnits.h"
  18. #include "clang/AST/Comment.h"
  19. #include "clang/AST/CommentCommandTraits.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExternalASTSource.h"
  26. #include "clang/AST/Mangle.h"
  27. #include "clang/AST/MangleNumberingContext.h"
  28. #include "clang/AST/RecordLayout.h"
  29. #include "clang/AST/RecursiveASTVisitor.h"
  30. #include "clang/AST/TypeLoc.h"
  31. #include "clang/AST/VTableBuilder.h"
  32. #include "clang/Basic/Builtins.h"
  33. #include "clang/Basic/SourceManager.h"
  34. #include "clang/Basic/TargetInfo.h"
  35. #include "llvm/ADT/SmallString.h"
  36. #include "llvm/ADT/StringExtras.h"
  37. #include "llvm/ADT/Triple.h"
  38. #include "llvm/Support/Capacity.h"
  39. #include "llvm/Support/MathExtras.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <map>
  42. using namespace clang;
  43. unsigned ASTContext::NumImplicitDefaultConstructors;
  44. unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
  45. unsigned ASTContext::NumImplicitCopyConstructors;
  46. unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
  47. unsigned ASTContext::NumImplicitMoveConstructors;
  48. unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
  49. unsigned ASTContext::NumImplicitCopyAssignmentOperators;
  50. unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
  51. unsigned ASTContext::NumImplicitMoveAssignmentOperators;
  52. unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
  53. unsigned ASTContext::NumImplicitDestructors;
  54. unsigned ASTContext::NumImplicitDestructorsDeclared;
  55. enum FloatingRank {
  56. LitFloatRank, Min10FloatRank, Min16FloatRank, HalfRank, HalfFloatRank, FloatRank, DoubleRank, LongDoubleRank // HLSL Change - adds LitFloatRank, Min10FloatRank, HalfFloat, and Min16FloatRank
  57. };
  58. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  59. if (!CommentsLoaded && ExternalSource) {
  60. ExternalSource->ReadComments();
  61. #ifndef NDEBUG
  62. ArrayRef<RawComment *> RawComments = Comments.getComments();
  63. assert(std::is_sorted(RawComments.begin(), RawComments.end(),
  64. BeforeThanCompare<RawComment>(SourceMgr)));
  65. #endif
  66. CommentsLoaded = true;
  67. }
  68. assert(D);
  69. // User can not attach documentation to implicit declarations.
  70. if (D->isImplicit())
  71. return nullptr;
  72. // User can not attach documentation to implicit instantiations.
  73. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  74. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  75. return nullptr;
  76. }
  77. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  78. if (VD->isStaticDataMember() &&
  79. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  80. return nullptr;
  81. }
  82. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
  83. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  84. return nullptr;
  85. }
  86. if (const ClassTemplateSpecializationDecl *CTSD =
  87. dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  88. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  89. if (TSK == TSK_ImplicitInstantiation ||
  90. TSK == TSK_Undeclared)
  91. return nullptr;
  92. }
  93. if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  94. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  95. return nullptr;
  96. }
  97. if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
  98. // When tag declaration (but not definition!) is part of the
  99. // decl-specifier-seq of some other declaration, it doesn't get comment
  100. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  101. return nullptr;
  102. }
  103. // TODO: handle comments for function parameters properly.
  104. if (isa<ParmVarDecl>(D))
  105. return nullptr;
  106. // TODO: we could look up template parameter documentation in the template
  107. // documentation.
  108. if (isa<TemplateTypeParmDecl>(D) ||
  109. isa<NonTypeTemplateParmDecl>(D) ||
  110. isa<TemplateTemplateParmDecl>(D))
  111. return nullptr;
  112. ArrayRef<RawComment *> RawComments = Comments.getComments();
  113. // If there are no comments anywhere, we won't find anything.
  114. if (RawComments.empty())
  115. return nullptr;
  116. // Find declaration location.
  117. // For Objective-C declarations we generally don't expect to have multiple
  118. // declarators, thus use declaration starting location as the "declaration
  119. // location".
  120. // For all other declarations multiple declarators are used quite frequently,
  121. // so we use the location of the identifier as the "declaration location".
  122. SourceLocation DeclLoc;
  123. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  124. isa<ObjCPropertyDecl>(D) ||
  125. isa<RedeclarableTemplateDecl>(D) ||
  126. isa<ClassTemplateSpecializationDecl>(D))
  127. DeclLoc = D->getLocStart();
  128. else {
  129. DeclLoc = D->getLocation();
  130. if (DeclLoc.isMacroID()) {
  131. if (isa<TypedefDecl>(D)) {
  132. // If location of the typedef name is in a macro, it is because being
  133. // declared via a macro. Try using declaration's starting location as
  134. // the "declaration location".
  135. DeclLoc = D->getLocStart();
  136. } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
  137. // If location of the tag decl is inside a macro, but the spelling of
  138. // the tag name comes from a macro argument, it looks like a special
  139. // macro like NS_ENUM is being used to define the tag decl. In that
  140. // case, adjust the source location to the expansion loc so that we can
  141. // attach the comment to the tag decl.
  142. if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
  143. TD->isCompleteDefinition())
  144. DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
  145. }
  146. }
  147. }
  148. // If the declaration doesn't map directly to a location in a file, we
  149. // can't find the comment.
  150. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  151. return nullptr;
  152. // Find the comment that occurs just after this declaration.
  153. ArrayRef<RawComment *>::iterator Comment;
  154. {
  155. // When searching for comments during parsing, the comment we are looking
  156. // for is usually among the last two comments we parsed -- check them
  157. // first.
  158. RawComment CommentAtDeclLoc(
  159. SourceMgr, SourceRange(DeclLoc), false,
  160. LangOpts.CommentOpts.ParseAllComments);
  161. BeforeThanCompare<RawComment> Compare(SourceMgr);
  162. ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
  163. bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  164. if (!Found && RawComments.size() >= 2) {
  165. MaybeBeforeDecl--;
  166. Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
  167. }
  168. if (Found) {
  169. Comment = MaybeBeforeDecl + 1;
  170. assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
  171. &CommentAtDeclLoc, Compare));
  172. } else {
  173. // Slow path.
  174. Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
  175. &CommentAtDeclLoc, Compare);
  176. }
  177. }
  178. // Decompose the location for the declaration and find the beginning of the
  179. // file buffer.
  180. std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
  181. // First check whether we have a trailing comment.
  182. if (Comment != RawComments.end() &&
  183. (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
  184. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  185. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  186. std::pair<FileID, unsigned> CommentBeginDecomp
  187. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
  188. // Check that Doxygen trailing comment comes after the declaration, starts
  189. // on the same line and in the same file as the declaration.
  190. if (DeclLocDecomp.first == CommentBeginDecomp.first &&
  191. SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
  192. == SourceMgr.getLineNumber(CommentBeginDecomp.first,
  193. CommentBeginDecomp.second)) {
  194. return *Comment;
  195. }
  196. }
  197. // The comment just after the declaration was not a trailing comment.
  198. // Let's look at the previous comment.
  199. if (Comment == RawComments.begin())
  200. return nullptr;
  201. --Comment;
  202. // Check that we actually have a non-member Doxygen comment.
  203. if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
  204. return nullptr;
  205. // Decompose the end of the comment.
  206. std::pair<FileID, unsigned> CommentEndDecomp
  207. = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
  208. // If the comment and the declaration aren't in the same file, then they
  209. // aren't related.
  210. if (DeclLocDecomp.first != CommentEndDecomp.first)
  211. return nullptr;
  212. // Get the corresponding buffer.
  213. bool Invalid = false;
  214. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  215. &Invalid).data();
  216. if (Invalid)
  217. return nullptr;
  218. // Extract text between the comment and declaration.
  219. StringRef Text(Buffer + CommentEndDecomp.second,
  220. DeclLocDecomp.second - CommentEndDecomp.second);
  221. // There should be no other declarations or preprocessor directives between
  222. // comment and declaration.
  223. if (Text.find_first_of(";{}#@") != StringRef::npos)
  224. return nullptr;
  225. return *Comment;
  226. }
  227. namespace {
  228. /// If we have a 'templated' declaration for a template, adjust 'D' to
  229. /// refer to the actual template.
  230. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  231. const Decl *adjustDeclToTemplate(const Decl *D) {
  232. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  233. // Is this function declaration part of a function template?
  234. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  235. return FTD;
  236. // Nothing to do if function is not an implicit instantiation.
  237. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  238. return D;
  239. // Function is an implicit instantiation of a function template?
  240. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  241. return FTD;
  242. // Function is instantiated from a member definition of a class template?
  243. if (const FunctionDecl *MemberDecl =
  244. FD->getInstantiatedFromMemberFunction())
  245. return MemberDecl;
  246. return D;
  247. }
  248. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  249. // Static data member is instantiated from a member definition of a class
  250. // template?
  251. if (VD->isStaticDataMember())
  252. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  253. return MemberDecl;
  254. return D;
  255. }
  256. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
  257. // Is this class declaration part of a class template?
  258. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  259. return CTD;
  260. // Class is an implicit instantiation of a class template or partial
  261. // specialization?
  262. if (const ClassTemplateSpecializationDecl *CTSD =
  263. dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  264. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  265. return D;
  266. llvm::PointerUnion<ClassTemplateDecl *,
  267. ClassTemplatePartialSpecializationDecl *>
  268. PU = CTSD->getSpecializedTemplateOrPartial();
  269. return PU.is<ClassTemplateDecl*>() ?
  270. static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
  271. static_cast<const Decl*>(
  272. PU.get<ClassTemplatePartialSpecializationDecl *>());
  273. }
  274. // Class is instantiated from a member definition of a class template?
  275. if (const MemberSpecializationInfo *Info =
  276. CRD->getMemberSpecializationInfo())
  277. return Info->getInstantiatedFrom();
  278. return D;
  279. }
  280. if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
  281. // Enum is instantiated from a member definition of a class template?
  282. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  283. return MemberDecl;
  284. return D;
  285. }
  286. // FIXME: Adjust alias templates?
  287. return D;
  288. }
  289. } // unnamed namespace
  290. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  291. const Decl *D,
  292. const Decl **OriginalDecl) const {
  293. D = adjustDeclToTemplate(D);
  294. // Check whether we have cached a comment for this declaration already.
  295. {
  296. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  297. RedeclComments.find(D);
  298. if (Pos != RedeclComments.end()) {
  299. const RawCommentAndCacheFlags &Raw = Pos->second;
  300. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  301. if (OriginalDecl)
  302. *OriginalDecl = Raw.getOriginalDecl();
  303. return Raw.getRaw();
  304. }
  305. }
  306. }
  307. // Search for comments attached to declarations in the redeclaration chain.
  308. const RawComment *RC = nullptr;
  309. const Decl *OriginalDeclForRC = nullptr;
  310. for (auto I : D->redecls()) {
  311. llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
  312. RedeclComments.find(I);
  313. if (Pos != RedeclComments.end()) {
  314. const RawCommentAndCacheFlags &Raw = Pos->second;
  315. if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
  316. RC = Raw.getRaw();
  317. OriginalDeclForRC = Raw.getOriginalDecl();
  318. break;
  319. }
  320. } else {
  321. RC = getRawCommentForDeclNoCache(I);
  322. OriginalDeclForRC = I;
  323. RawCommentAndCacheFlags Raw;
  324. if (RC) {
  325. Raw.setKind(RawCommentAndCacheFlags::FromDecl);
  326. Raw.setRaw(RC);
  327. } else
  328. Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
  329. Raw.setOriginalDecl(I);
  330. RedeclComments[I] = Raw;
  331. if (RC)
  332. break;
  333. }
  334. }
  335. // If we found a comment, it should be a documentation comment.
  336. assert(!RC || RC->isDocumentation());
  337. if (OriginalDecl)
  338. *OriginalDecl = OriginalDeclForRC;
  339. // Update cache for every declaration in the redeclaration chain.
  340. RawCommentAndCacheFlags Raw;
  341. Raw.setRaw(RC);
  342. Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
  343. Raw.setOriginalDecl(OriginalDeclForRC);
  344. for (auto I : D->redecls()) {
  345. RawCommentAndCacheFlags &R = RedeclComments[I];
  346. if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
  347. R = Raw;
  348. }
  349. return RC;
  350. }
  351. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  352. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  353. const DeclContext *DC = ObjCMethod->getDeclContext();
  354. if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  355. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  356. if (!ID)
  357. return;
  358. // Add redeclared method here.
  359. for (const auto *Ext : ID->known_extensions()) {
  360. if (ObjCMethodDecl *RedeclaredMethod =
  361. Ext->getMethod(ObjCMethod->getSelector(),
  362. ObjCMethod->isInstanceMethod()))
  363. Redeclared.push_back(RedeclaredMethod);
  364. }
  365. }
  366. }
  367. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  368. const Decl *D) const {
  369. comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
  370. ThisDeclInfo->CommentDecl = D;
  371. ThisDeclInfo->IsFilled = false;
  372. ThisDeclInfo->fill();
  373. ThisDeclInfo->CommentDecl = FC->getDecl();
  374. if (!ThisDeclInfo->TemplateParameters)
  375. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  376. comments::FullComment *CFC =
  377. new (*this) comments::FullComment(FC->getBlocks(),
  378. ThisDeclInfo);
  379. return CFC;
  380. }
  381. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  382. const RawComment *RC = getRawCommentForDeclNoCache(D);
  383. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  384. }
  385. comments::FullComment *ASTContext::getCommentForDecl(
  386. const Decl *D,
  387. const Preprocessor *PP) const {
  388. if (D->isInvalidDecl())
  389. return nullptr;
  390. D = adjustDeclToTemplate(D);
  391. const Decl *Canonical = D->getCanonicalDecl();
  392. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  393. ParsedComments.find(Canonical);
  394. if (Pos != ParsedComments.end()) {
  395. if (Canonical != D) {
  396. comments::FullComment *FC = Pos->second;
  397. comments::FullComment *CFC = cloneFullComment(FC, D);
  398. return CFC;
  399. }
  400. return Pos->second;
  401. }
  402. const Decl *OriginalDecl;
  403. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  404. if (!RC) {
  405. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  406. SmallVector<const NamedDecl*, 8> Overridden;
  407. const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
  408. if (OMD && OMD->isPropertyAccessor())
  409. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  410. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  411. return cloneFullComment(FC, D);
  412. if (OMD)
  413. addRedeclaredMethods(OMD, Overridden);
  414. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  415. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  416. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  417. return cloneFullComment(FC, D);
  418. }
  419. else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
  420. // Attach any tag type's documentation to its typedef if latter
  421. // does not have one of its own.
  422. QualType QT = TD->getUnderlyingType();
  423. if (const TagType *TT = QT->getAs<TagType>())
  424. if (const Decl *TD = TT->getDecl())
  425. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  426. return cloneFullComment(FC, D);
  427. }
  428. else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  429. while (IC->getSuperClass()) {
  430. IC = IC->getSuperClass();
  431. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  432. return cloneFullComment(FC, D);
  433. }
  434. }
  435. else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  436. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  437. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  438. return cloneFullComment(FC, D);
  439. }
  440. else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  441. if (!(RD = RD->getDefinition()))
  442. return nullptr;
  443. // Check non-virtual bases.
  444. for (const auto &I : RD->bases()) {
  445. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  446. continue;
  447. QualType Ty = I.getType();
  448. if (Ty.isNull())
  449. continue;
  450. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  451. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  452. continue;
  453. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  454. return cloneFullComment(FC, D);
  455. }
  456. }
  457. // Check virtual bases.
  458. for (const auto &I : RD->vbases()) {
  459. if (I.getAccessSpecifier() != AS_public)
  460. continue;
  461. QualType Ty = I.getType();
  462. if (Ty.isNull())
  463. continue;
  464. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  465. if (!(VirtualBase= VirtualBase->getDefinition()))
  466. continue;
  467. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  468. return cloneFullComment(FC, D);
  469. }
  470. }
  471. }
  472. return nullptr;
  473. }
  474. // If the RawComment was attached to other redeclaration of this Decl, we
  475. // should parse the comment in context of that other Decl. This is important
  476. // because comments can contain references to parameter names which can be
  477. // different across redeclarations.
  478. if (D != OriginalDecl)
  479. return getCommentForDecl(OriginalDecl, PP);
  480. comments::FullComment *FC = RC->parse(*this, PP, D);
  481. ParsedComments[Canonical] = FC;
  482. return FC;
  483. }
  484. void
  485. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  486. TemplateTemplateParmDecl *Parm) {
  487. ID.AddInteger(Parm->getDepth());
  488. ID.AddInteger(Parm->getPosition());
  489. ID.AddBoolean(Parm->isParameterPack());
  490. TemplateParameterList *Params = Parm->getTemplateParameters();
  491. ID.AddInteger(Params->size());
  492. for (TemplateParameterList::const_iterator P = Params->begin(),
  493. PEnd = Params->end();
  494. P != PEnd; ++P) {
  495. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  496. ID.AddInteger(0);
  497. ID.AddBoolean(TTP->isParameterPack());
  498. continue;
  499. }
  500. if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  501. ID.AddInteger(1);
  502. ID.AddBoolean(NTTP->isParameterPack());
  503. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  504. if (NTTP->isExpandedParameterPack()) {
  505. ID.AddBoolean(true);
  506. ID.AddInteger(NTTP->getNumExpansionTypes());
  507. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  508. QualType T = NTTP->getExpansionType(I);
  509. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  510. }
  511. } else
  512. ID.AddBoolean(false);
  513. continue;
  514. }
  515. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
  516. ID.AddInteger(2);
  517. Profile(ID, TTP);
  518. }
  519. }
  520. TemplateTemplateParmDecl *
  521. ASTContext::getCanonicalTemplateTemplateParmDecl(
  522. TemplateTemplateParmDecl *TTP) const {
  523. // Check if we already have a canonical template template parameter.
  524. llvm::FoldingSetNodeID ID;
  525. CanonicalTemplateTemplateParm::Profile(ID, TTP);
  526. void *InsertPos = nullptr;
  527. CanonicalTemplateTemplateParm *Canonical
  528. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  529. if (Canonical)
  530. return Canonical->getParam();
  531. // Build a canonical template parameter list.
  532. TemplateParameterList *Params = TTP->getTemplateParameters();
  533. SmallVector<NamedDecl *, 4> CanonParams;
  534. CanonParams.reserve(Params->size());
  535. for (TemplateParameterList::const_iterator P = Params->begin(),
  536. PEnd = Params->end();
  537. P != PEnd; ++P) {
  538. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
  539. CanonParams.push_back(
  540. TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
  541. SourceLocation(),
  542. SourceLocation(),
  543. TTP->getDepth(),
  544. TTP->getIndex(), nullptr, false,
  545. TTP->isParameterPack()));
  546. else if (NonTypeTemplateParmDecl *NTTP
  547. = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  548. QualType T = getCanonicalType(NTTP->getType());
  549. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  550. NonTypeTemplateParmDecl *Param;
  551. if (NTTP->isExpandedParameterPack()) {
  552. SmallVector<QualType, 2> ExpandedTypes;
  553. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  554. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  555. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  556. ExpandedTInfos.push_back(
  557. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  558. }
  559. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  560. SourceLocation(),
  561. SourceLocation(),
  562. NTTP->getDepth(),
  563. NTTP->getPosition(), nullptr,
  564. T,
  565. TInfo,
  566. ExpandedTypes.data(),
  567. ExpandedTypes.size(),
  568. ExpandedTInfos.data());
  569. } else {
  570. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  571. SourceLocation(),
  572. SourceLocation(),
  573. NTTP->getDepth(),
  574. NTTP->getPosition(), nullptr,
  575. T,
  576. NTTP->isParameterPack(),
  577. TInfo);
  578. }
  579. CanonParams.push_back(Param);
  580. } else
  581. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  582. cast<TemplateTemplateParmDecl>(*P)));
  583. }
  584. TemplateTemplateParmDecl *CanonTTP
  585. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  586. SourceLocation(), TTP->getDepth(),
  587. TTP->getPosition(),
  588. TTP->isParameterPack(),
  589. nullptr,
  590. TemplateParameterList::Create(*this, SourceLocation(),
  591. SourceLocation(),
  592. CanonParams.data(),
  593. CanonParams.size(),
  594. SourceLocation()));
  595. // Get the new insert position for the node we care about.
  596. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  597. assert(!Canonical && "Shouldn't be in the map!");
  598. (void)Canonical;
  599. // Create the canonical template template parameter entry.
  600. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  601. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  602. return CanonTTP;
  603. }
  604. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  605. if (!LangOpts.CPlusPlus) return nullptr;
  606. switch (T.getCXXABI().getKind()) {
  607. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  608. case TargetCXXABI::iOS:
  609. case TargetCXXABI::iOS64:
  610. case TargetCXXABI::GenericAArch64:
  611. case TargetCXXABI::GenericMIPS:
  612. case TargetCXXABI::GenericItanium:
  613. return CreateItaniumCXXABI(*this);
  614. case TargetCXXABI::Microsoft:
  615. return CreateMicrosoftCXXABI(*this);
  616. }
  617. llvm_unreachable("Invalid CXXABI type!");
  618. }
  619. static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
  620. const LangOptions &LOpts) {
  621. if (LOpts.FakeAddressSpaceMap) {
  622. // The fake address space map must have a distinct entry for each
  623. // language-specific address space.
  624. static const unsigned FakeAddrSpaceMap[] = {
  625. 1, // opencl_global
  626. 2, // opencl_local
  627. 3, // opencl_constant
  628. 4, // opencl_generic
  629. 5, // cuda_device
  630. 6, // cuda_constant
  631. 7 // cuda_shared
  632. };
  633. return &FakeAddrSpaceMap;
  634. } else {
  635. return &T.getAddressSpaceMap();
  636. }
  637. }
  638. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  639. const LangOptions &LangOpts) {
  640. switch (LangOpts.getAddressSpaceMapMangling()) {
  641. case LangOptions::ASMM_Target:
  642. return TI.useAddressSpaceMapMangling();
  643. case LangOptions::ASMM_On:
  644. return true;
  645. case LangOptions::ASMM_Off:
  646. return false;
  647. }
  648. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  649. }
  650. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  651. IdentifierTable &idents, SelectorTable &sels,
  652. Builtin::Context &builtins)
  653. : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
  654. DependentTemplateSpecializationTypes(this_()),
  655. SubstTemplateTemplateParmPacks(this_()),
  656. GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
  657. UInt128Decl(nullptr), Float128StubDecl(nullptr),
  658. BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
  659. ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
  660. CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
  661. FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
  662. ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
  663. BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
  664. FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
  665. SourceMgr(SM), LangOpts(LOpts),
  666. SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
  667. AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
  668. Idents(idents), Selectors(sels), BuiltinInfo(builtins),
  669. DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
  670. Comments(SM), CommentsLoaded(false),
  671. CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
  672. TUDecl = TranslationUnitDecl::Create(*this);
  673. }
  674. ASTContext::~ASTContext() {
  675. ReleaseParentMapEntries();
  676. // Release the DenseMaps associated with DeclContext objects.
  677. // FIXME: Is this the ideal solution?
  678. ReleaseDeclContextMaps();
  679. // Call all of the deallocation functions on all of their targets.
  680. for (DeallocationMap::const_iterator I = Deallocations.begin(),
  681. E = Deallocations.end(); I != E; ++I)
  682. for (unsigned J = 0, N = I->second.size(); J != N; ++J)
  683. (I->first)((I->second)[J]);
  684. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  685. // because they can contain DenseMaps.
  686. for (llvm::DenseMap<const ObjCContainerDecl*,
  687. const ASTRecordLayout*>::iterator
  688. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  689. // Increment in loop to prevent using deallocated memory.
  690. if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
  691. R->Destroy(*this);
  692. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  693. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  694. // Increment in loop to prevent using deallocated memory.
  695. if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
  696. R->Destroy(*this);
  697. }
  698. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  699. AEnd = DeclAttrs.end();
  700. A != AEnd; ++A)
  701. A->second->~AttrVec();
  702. llvm::DeleteContainerSeconds(MangleNumberingContexts);
  703. }
  704. void ASTContext::ReleaseParentMapEntries() {
  705. if (!AllParents) return;
  706. for (const auto &Entry : *AllParents) {
  707. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  708. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  709. } else {
  710. assert(Entry.second.is<ParentVector *>());
  711. delete Entry.second.get<ParentVector *>();
  712. }
  713. }
  714. }
  715. void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
  716. Deallocations[Callback].push_back(Data);
  717. }
  718. void
  719. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  720. ExternalSource = Source;
  721. }
  722. void ASTContext::PrintStats() const {
  723. llvm::errs() << "\n*** AST Context Stats:\n";
  724. llvm::errs() << " " << Types.size() << " types total.\n";
  725. unsigned counts[] = {
  726. #define TYPE(Name, Parent) 0,
  727. #define ABSTRACT_TYPE(Name, Parent)
  728. #include "clang/AST/TypeNodes.def"
  729. 0 // Extra
  730. };
  731. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  732. Type *T = Types[i];
  733. // HLSL Change Starts - guard against overflows; we can probably prove this is fine, but this is not a sensitive (or retail!) codepath
  734. #if 0
  735. counts[(unsigned)T->getTypeClass()]++;
  736. #else
  737. unsigned offset = (unsigned)T->getTypeClass();
  738. if (offset < _countof(counts)) counts[offset]++;
  739. #endif
  740. // HLSL Change Ends
  741. }
  742. unsigned Idx = 0;
  743. unsigned TotalBytes = 0;
  744. #define TYPE(Name, Parent) \
  745. if (counts[Idx]) \
  746. llvm::errs() << " " << counts[Idx] << " " << #Name \
  747. << " types\n"; \
  748. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  749. ++Idx;
  750. #define ABSTRACT_TYPE(Name, Parent)
  751. #include "clang/AST/TypeNodes.def"
  752. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  753. // Implicit special member functions.
  754. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  755. << NumImplicitDefaultConstructors
  756. << " implicit default constructors created\n";
  757. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  758. << NumImplicitCopyConstructors
  759. << " implicit copy constructors created\n";
  760. if (getLangOpts().CPlusPlus)
  761. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  762. << NumImplicitMoveConstructors
  763. << " implicit move constructors created\n";
  764. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  765. << NumImplicitCopyAssignmentOperators
  766. << " implicit copy assignment operators created\n";
  767. if (getLangOpts().CPlusPlus)
  768. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  769. << NumImplicitMoveAssignmentOperators
  770. << " implicit move assignment operators created\n";
  771. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  772. << NumImplicitDestructors
  773. << " implicit destructors created\n";
  774. if (ExternalSource) {
  775. llvm::errs() << "\n";
  776. ExternalSource->PrintStats();
  777. }
  778. BumpAlloc.PrintStats();
  779. }
  780. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  781. bool NotifyListeners) {
  782. if (NotifyListeners)
  783. if (auto *Listener = getASTMutationListener())
  784. Listener->RedefinedHiddenDefinition(ND, M);
  785. if (getLangOpts().ModulesLocalVisibility)
  786. MergedDefModules[ND].push_back(M);
  787. else
  788. ND->setHidden(false);
  789. }
  790. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  791. auto It = MergedDefModules.find(ND);
  792. if (It == MergedDefModules.end())
  793. return;
  794. auto &Merged = It->second;
  795. llvm::DenseSet<Module*> Found;
  796. for (Module *&M : Merged)
  797. if (!Found.insert(M).second)
  798. M = nullptr;
  799. Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
  800. }
  801. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  802. if (!ExternCContext)
  803. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  804. return ExternCContext;
  805. }
  806. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  807. RecordDecl::TagKind TK) const {
  808. SourceLocation Loc;
  809. RecordDecl *NewDecl;
  810. if (getLangOpts().CPlusPlus)
  811. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  812. Loc, &Idents.get(Name));
  813. else
  814. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  815. &Idents.get(Name));
  816. NewDecl->setImplicit();
  817. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  818. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  819. return NewDecl;
  820. }
  821. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  822. StringRef Name) const {
  823. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  824. TypedefDecl *NewDecl = TypedefDecl::Create(
  825. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  826. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  827. NewDecl->setImplicit();
  828. return NewDecl;
  829. }
  830. TypedefDecl *ASTContext::getInt128Decl() const {
  831. if (!Int128Decl)
  832. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  833. return Int128Decl;
  834. }
  835. TypedefDecl *ASTContext::getUInt128Decl() const {
  836. if (!UInt128Decl)
  837. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  838. return UInt128Decl;
  839. }
  840. TypeDecl *ASTContext::getFloat128StubType() const {
  841. assert(LangOpts.CPlusPlus && "should only be called for c++");
  842. if (!Float128StubDecl)
  843. Float128StubDecl = buildImplicitRecord("__float128");
  844. return Float128StubDecl;
  845. }
  846. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  847. BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
  848. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  849. Types.push_back(Ty);
  850. }
  851. void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
  852. assert((!this->Target || this->Target == &Target) &&
  853. "Incorrect target reinitialization");
  854. assert(VoidTy.isNull() && "Context reinitialized?");
  855. this->Target = &Target;
  856. ABI.reset(createCXXABI(Target));
  857. AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
  858. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  859. // C99 6.2.5p19.
  860. InitBuiltinType(VoidTy, BuiltinType::Void);
  861. // C99 6.2.5p2.
  862. InitBuiltinType(BoolTy, BuiltinType::Bool);
  863. // C99 6.2.5p3.
  864. if (LangOpts.CharIsSigned)
  865. InitBuiltinType(CharTy, BuiltinType::Char_S);
  866. else
  867. InitBuiltinType(CharTy, BuiltinType::Char_U);
  868. // C99 6.2.5p4.
  869. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  870. InitBuiltinType(ShortTy, BuiltinType::Short);
  871. InitBuiltinType(IntTy, BuiltinType::Int);
  872. InitBuiltinType(LongTy, BuiltinType::Long);
  873. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  874. // C99 6.2.5p6.
  875. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  876. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  877. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  878. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  879. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  880. // C99 6.2.5p10.
  881. InitBuiltinType(FloatTy, BuiltinType::Float);
  882. InitBuiltinType(DoubleTy, BuiltinType::Double);
  883. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  884. // GNU extension, 128-bit integers.
  885. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  886. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  887. // C++ 3.9.1p5
  888. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  889. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  890. else // -fshort-wchar makes wchar_t be unsigned.
  891. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  892. if (LangOpts.CPlusPlus && LangOpts.WChar)
  893. WideCharTy = WCharTy;
  894. else {
  895. // C99 (or C++ using -fno-wchar).
  896. WideCharTy = getFromTargetType(Target.getWCharType());
  897. }
  898. WIntTy = getFromTargetType(Target.getWIntType());
  899. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  900. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  901. else // C99
  902. Char16Ty = getFromTargetType(Target.getChar16Type());
  903. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  904. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  905. else // C99
  906. Char32Ty = getFromTargetType(Target.getChar32Type());
  907. // Placeholder type for type-dependent expressions whose type is
  908. // completely unknown. No code should ever check a type against
  909. // DependentTy and users should never see it; however, it is here to
  910. // help diagnose failures to properly check for type-dependent
  911. // expressions.
  912. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  913. // Placeholder type for functions.
  914. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  915. // Placeholder type for bound members.
  916. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  917. // Placeholder type for pseudo-objects.
  918. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  919. // "any" type; useful for debugger-like clients.
  920. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  921. // Placeholder type for unbridged ARC casts.
  922. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  923. // Placeholder type for builtin functions.
  924. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  925. // C99 6.2.5p11.
  926. FloatComplexTy = getComplexType(FloatTy);
  927. DoubleComplexTy = getComplexType(DoubleTy);
  928. LongDoubleComplexTy = getComplexType(LongDoubleTy);
  929. // Builtin types for 'id', 'Class', and 'SEL'.
  930. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  931. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  932. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  933. if (LangOpts.OpenCL) {
  934. InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
  935. InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
  936. InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
  937. InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
  938. InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
  939. InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
  940. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  941. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  942. }
  943. // Builtin type for __objc_yes and __objc_no
  944. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  945. SignedCharTy : BoolTy);
  946. ObjCConstantStringType = QualType();
  947. ObjCSuperType = QualType();
  948. // void * type
  949. VoidPtrTy = getPointerType(VoidTy);
  950. // nullptr type (C++0x 2.14.7)
  951. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  952. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  953. InitBuiltinType(HalfTy, BuiltinType::Half);
  954. // Builtin type used to help define __builtin_va_list.
  955. VaListTagTy = QualType();
  956. // HLSL Change Starts
  957. if (LangOpts.HLSL) {
  958. InitBuiltinType(Min12IntTy, BuiltinType::Min12Int);
  959. InitBuiltinType(Min16IntTy, BuiltinType::Min16Int);
  960. InitBuiltinType(Min16UIntTy, BuiltinType::Min16UInt);
  961. InitBuiltinType(Min16FloatTy, BuiltinType::Min16Float);
  962. InitBuiltinType(Min10FloatTy, BuiltinType::Min10Float);
  963. InitBuiltinType(HalfFloatTy, BuiltinType::HalfFloat);
  964. InitBuiltinType(LitIntTy, BuiltinType::LitInt);
  965. InitBuiltinType(LitFloatTy, BuiltinType::LitFloat);
  966. hlsl::InitializeASTContextForHLSL(*this); // Previously in constructor, guarded by !DelayInitialization
  967. }
  968. // HLSL Change Ends
  969. }
  970. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  971. return SourceMgr.getDiagnostics();
  972. }
  973. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  974. AttrVec *&Result = DeclAttrs[D];
  975. if (!Result) {
  976. void *Mem = Allocate(sizeof(AttrVec));
  977. Result = new (Mem) AttrVec;
  978. }
  979. return *Result;
  980. }
  981. /// \brief Erase the attributes corresponding to the given declaration.
  982. void ASTContext::eraseDeclAttrs(const Decl *D) {
  983. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  984. if (Pos != DeclAttrs.end()) {
  985. Pos->second->~AttrVec();
  986. DeclAttrs.erase(Pos);
  987. }
  988. }
  989. // FIXME: Remove ?
  990. MemberSpecializationInfo *
  991. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  992. assert(Var->isStaticDataMember() && "Not a static data member");
  993. return getTemplateOrSpecializationInfo(Var)
  994. .dyn_cast<MemberSpecializationInfo *>();
  995. }
  996. ASTContext::TemplateOrSpecializationInfo
  997. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  998. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  999. TemplateOrInstantiation.find(Var);
  1000. if (Pos == TemplateOrInstantiation.end())
  1001. return TemplateOrSpecializationInfo();
  1002. return Pos->second;
  1003. }
  1004. void
  1005. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1006. TemplateSpecializationKind TSK,
  1007. SourceLocation PointOfInstantiation) {
  1008. assert(Inst->isStaticDataMember() && "Not a static data member");
  1009. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1010. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1011. Tmpl, TSK, PointOfInstantiation));
  1012. }
  1013. void
  1014. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1015. TemplateOrSpecializationInfo TSI) {
  1016. assert(!TemplateOrInstantiation[Inst] &&
  1017. "Already noted what the variable was instantiated from");
  1018. TemplateOrInstantiation[Inst] = TSI;
  1019. }
  1020. FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
  1021. const FunctionDecl *FD){
  1022. assert(FD && "Specialization is 0");
  1023. llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
  1024. = ClassScopeSpecializationPattern.find(FD);
  1025. if (Pos == ClassScopeSpecializationPattern.end())
  1026. return nullptr;
  1027. return Pos->second;
  1028. }
  1029. void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
  1030. FunctionDecl *Pattern) {
  1031. assert(FD && "Specialization is 0");
  1032. assert(Pattern && "Class scope specialization pattern is 0");
  1033. ClassScopeSpecializationPattern[FD] = Pattern;
  1034. }
  1035. NamedDecl *
  1036. ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
  1037. llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
  1038. = InstantiatedFromUsingDecl.find(UUD);
  1039. if (Pos == InstantiatedFromUsingDecl.end())
  1040. return nullptr;
  1041. return Pos->second;
  1042. }
  1043. void
  1044. ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
  1045. assert((isa<UsingDecl>(Pattern) ||
  1046. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1047. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1048. "pattern decl is not a using decl");
  1049. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1050. InstantiatedFromUsingDecl[Inst] = Pattern;
  1051. }
  1052. UsingShadowDecl *
  1053. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1054. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1055. = InstantiatedFromUsingShadowDecl.find(Inst);
  1056. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1057. return nullptr;
  1058. return Pos->second;
  1059. }
  1060. void
  1061. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1062. UsingShadowDecl *Pattern) {
  1063. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1064. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1065. }
  1066. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1067. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1068. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1069. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1070. return nullptr;
  1071. return Pos->second;
  1072. }
  1073. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1074. FieldDecl *Tmpl) {
  1075. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1076. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1077. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1078. "Already noted what unnamed field was instantiated from");
  1079. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1080. }
  1081. ASTContext::overridden_cxx_method_iterator
  1082. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1083. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1084. = OverriddenMethods.find(Method->getCanonicalDecl());
  1085. if (Pos == OverriddenMethods.end())
  1086. return nullptr;
  1087. return Pos->second.begin();
  1088. }
  1089. ASTContext::overridden_cxx_method_iterator
  1090. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1091. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1092. = OverriddenMethods.find(Method->getCanonicalDecl());
  1093. if (Pos == OverriddenMethods.end())
  1094. return nullptr;
  1095. return Pos->second.end();
  1096. }
  1097. unsigned
  1098. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1099. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
  1100. = OverriddenMethods.find(Method->getCanonicalDecl());
  1101. if (Pos == OverriddenMethods.end())
  1102. return 0;
  1103. return Pos->second.size();
  1104. }
  1105. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1106. const CXXMethodDecl *Overridden) {
  1107. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1108. OverriddenMethods[Method].push_back(Overridden);
  1109. }
  1110. void ASTContext::getOverriddenMethods(
  1111. const NamedDecl *D,
  1112. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1113. assert(D);
  1114. if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1115. Overridden.append(overridden_methods_begin(CXXMethod),
  1116. overridden_methods_end(CXXMethod));
  1117. return;
  1118. }
  1119. const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
  1120. if (!Method)
  1121. return;
  1122. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1123. Method->getOverriddenMethods(OverDecls);
  1124. Overridden.append(OverDecls.begin(), OverDecls.end());
  1125. }
  1126. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1127. assert(!Import->NextLocalImport && "Import declaration already in the chain");
  1128. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1129. if (!FirstLocalImport) {
  1130. FirstLocalImport = Import;
  1131. LastLocalImport = Import;
  1132. return;
  1133. }
  1134. LastLocalImport->NextLocalImport = Import;
  1135. LastLocalImport = Import;
  1136. }
  1137. //===----------------------------------------------------------------------===//
  1138. // Type Sizing and Analysis
  1139. //===----------------------------------------------------------------------===//
  1140. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1141. /// scalar floating point type.
  1142. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1143. const BuiltinType *BT = T->getAs<BuiltinType>();
  1144. assert(BT && "Not a floating point type!");
  1145. switch (BT->getKind()) {
  1146. default: llvm_unreachable("Not a floating point type!");
  1147. // HLSL Change Starts
  1148. case BuiltinType::Min10Float:
  1149. case BuiltinType::Min16Float:
  1150. // HLSL Change Ends
  1151. case BuiltinType::Half: return Target->getHalfFormat();
  1152. case BuiltinType::HalfFloat: // HLSL Change
  1153. case BuiltinType::Float: return Target->getFloatFormat();
  1154. case BuiltinType::Double: return Target->getDoubleFormat();
  1155. case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
  1156. case BuiltinType::LitFloat: return Target->getDoubleFormat(); // HLSL Change
  1157. }
  1158. }
  1159. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1160. unsigned Align = Target->getCharWidth();
  1161. bool UseAlignAttrOnly = false;
  1162. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1163. Align = AlignFromAttr;
  1164. // __attribute__((aligned)) can increase or decrease alignment
  1165. // *except* on a struct or struct member, where it only increases
  1166. // alignment unless 'packed' is also specified.
  1167. //
  1168. // It is an error for alignas to decrease alignment, so we can
  1169. // ignore that possibility; Sema should diagnose it.
  1170. if (isa<FieldDecl>(D)) {
  1171. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1172. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1173. } else {
  1174. UseAlignAttrOnly = true;
  1175. }
  1176. }
  1177. else if (isa<FieldDecl>(D))
  1178. UseAlignAttrOnly =
  1179. D->hasAttr<PackedAttr>() ||
  1180. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1181. // If we're using the align attribute only, just ignore everything
  1182. // else about the declaration and its type.
  1183. if (UseAlignAttrOnly) {
  1184. // do nothing
  1185. } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
  1186. QualType T = VD->getType();
  1187. if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
  1188. if (ForAlignof)
  1189. T = RT->getPointeeType();
  1190. else
  1191. T = getPointerType(RT->getPointeeType());
  1192. }
  1193. QualType BaseT = getBaseElementType(T);
  1194. if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
  1195. // Adjust alignments of declarations with array type by the
  1196. // large-array alignment on the target.
  1197. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1198. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1199. if (!ForAlignof && MinWidth) {
  1200. if (isa<VariableArrayType>(arrayType))
  1201. Align = std::max(Align, Target->getLargeArrayAlign());
  1202. else if (isa<ConstantArrayType>(arrayType) &&
  1203. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1204. Align = std::max(Align, Target->getLargeArrayAlign());
  1205. }
  1206. }
  1207. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1208. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1209. if (VD->hasGlobalStorage() && !ForAlignof)
  1210. Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
  1211. }
  1212. }
  1213. // Fields can be subject to extra alignment constraints, like if
  1214. // the field is packed, the struct is packed, or the struct has a
  1215. // a max-field-alignment constraint (#pragma pack). So calculate
  1216. // the actual alignment of the field within the struct, and then
  1217. // (as we're expected to) constrain that by the alignment of the type.
  1218. if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
  1219. const RecordDecl *Parent = Field->getParent();
  1220. // We can only produce a sensible answer if the record is valid.
  1221. if (!Parent->isInvalidDecl()) {
  1222. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1223. // Start with the record's overall alignment.
  1224. unsigned FieldAlign = toBits(Layout.getAlignment());
  1225. // Use the GCD of that and the offset within the record.
  1226. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1227. if (Offset > 0) {
  1228. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1229. // which means we get to do this crazy thing instead of Euclid's.
  1230. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1231. if (LowBitOfOffset < FieldAlign)
  1232. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1233. }
  1234. Align = std::min(Align, FieldAlign);
  1235. }
  1236. }
  1237. }
  1238. return toCharUnitsFromBits(Align);
  1239. }
  1240. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1241. // chars. If the type is a record, its data size is returned. This is
  1242. // the size of the memcpy that's performed when assigning this type
  1243. // using a trivial copy/move assignment operator.
  1244. std::pair<CharUnits, CharUnits>
  1245. ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1246. std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
  1247. // In C++, objects can sometimes be allocated into the tail padding
  1248. // of a base-class subobject. We decide whether that's possible
  1249. // during class layout, so here we can just trust the layout results.
  1250. if (getLangOpts().CPlusPlus) {
  1251. if (const RecordType *RT = T->getAs<RecordType>()) {
  1252. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1253. sizeAndAlign.first = layout.getDataSize();
  1254. }
  1255. }
  1256. return sizeAndAlign;
  1257. }
  1258. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1259. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1260. std::pair<CharUnits, CharUnits>
  1261. static getConstantArrayInfoInChars(const ASTContext &Context,
  1262. const ConstantArrayType *CAT) {
  1263. std::pair<CharUnits, CharUnits> EltInfo =
  1264. Context.getTypeInfoInChars(CAT->getElementType());
  1265. uint64_t Size = CAT->getSize().getZExtValue();
  1266. assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
  1267. (uint64_t)(-1)/Size) &&
  1268. "Overflow in array type char size evaluation");
  1269. uint64_t Width = EltInfo.first.getQuantity() * Size;
  1270. unsigned Align = EltInfo.second.getQuantity();
  1271. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1272. Context.getTargetInfo().getPointerWidth(0) == 64)
  1273. Width = llvm::RoundUpToAlignment(Width, Align);
  1274. return std::make_pair(CharUnits::fromQuantity(Width),
  1275. CharUnits::fromQuantity(Align));
  1276. }
  1277. std::pair<CharUnits, CharUnits>
  1278. ASTContext::getTypeInfoInChars(const Type *T) const {
  1279. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
  1280. return getConstantArrayInfoInChars(*this, CAT);
  1281. TypeInfo Info = getTypeInfo(T);
  1282. return std::make_pair(toCharUnitsFromBits(Info.Width),
  1283. toCharUnitsFromBits(Info.Align));
  1284. }
  1285. std::pair<CharUnits, CharUnits>
  1286. ASTContext::getTypeInfoInChars(QualType T) const {
  1287. return getTypeInfoInChars(T.getTypePtr());
  1288. }
  1289. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1290. return getTypeInfo(T).AlignIsRequired;
  1291. }
  1292. bool ASTContext::isAlignmentRequired(QualType T) const {
  1293. return isAlignmentRequired(T.getTypePtr());
  1294. }
  1295. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1296. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1297. if (I != MemoizedTypeInfo.end())
  1298. return I->second;
  1299. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1300. TypeInfo TI = getTypeInfoImpl(T);
  1301. MemoizedTypeInfo[T] = TI;
  1302. return TI;
  1303. }
  1304. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1305. /// method does not work on incomplete types.
  1306. ///
  1307. /// FIXME: Pointers into different addr spaces could have different sizes and
  1308. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1309. /// should take a QualType, &c.
  1310. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1311. uint64_t Width = 0;
  1312. unsigned Align = 8;
  1313. bool AlignIsRequired = false;
  1314. // HLSL Change Starts
  1315. if (getLangOpts().HLSL) {
  1316. if (const ExtVectorType *Ty =
  1317. hlsl::ConvertHLSLVecMatTypeToExtVectorType(*this, QualType(T, 0))) {
  1318. T = Ty;
  1319. }
  1320. }
  1321. // HLSL Change Ends
  1322. switch (T->getTypeClass()) {
  1323. #define TYPE(Class, Base)
  1324. #define ABSTRACT_TYPE(Class, Base)
  1325. #define NON_CANONICAL_TYPE(Class, Base)
  1326. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1327. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1328. case Type::Class: \
  1329. assert(!T->isDependentType() && "should not see dependent types here"); \
  1330. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1331. #include "clang/AST/TypeNodes.def"
  1332. llvm_unreachable("Should not see dependent types");
  1333. case Type::FunctionNoProto:
  1334. case Type::FunctionProto:
  1335. // GCC extension: alignof(function) = 32 bits
  1336. Width = 0;
  1337. Align = 32;
  1338. break;
  1339. case Type::IncompleteArray:
  1340. case Type::VariableArray:
  1341. Width = 0;
  1342. Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
  1343. break;
  1344. case Type::ConstantArray: {
  1345. const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
  1346. TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
  1347. uint64_t Size = CAT->getSize().getZExtValue();
  1348. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1349. "Overflow in array type bit size evaluation");
  1350. Width = EltInfo.Width * Size;
  1351. Align = EltInfo.Align;
  1352. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1353. getTargetInfo().getPointerWidth(0) == 64)
  1354. Width = llvm::RoundUpToAlignment(Width, Align);
  1355. break;
  1356. }
  1357. case Type::ExtVector:
  1358. case Type::Vector: {
  1359. const VectorType *VT = cast<VectorType>(T);
  1360. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1361. Width = EltInfo.Width * VT->getNumElements();
  1362. Align = Width;
  1363. // HLSL Change Begins.
  1364. // Vector align to its element.
  1365. if (getLangOpts().HLSL) {
  1366. Align = EltInfo.Align;
  1367. Width = Align * VT->getNumElements();
  1368. }
  1369. // HLSL Change Ends.
  1370. // If the alignment is not a power of 2, round up to the next power of 2.
  1371. // This happens for non-power-of-2 length vectors.
  1372. if (Align & (Align-1)) {
  1373. Align = llvm::NextPowerOf2(Align);
  1374. Width = llvm::RoundUpToAlignment(Width, Align);
  1375. }
  1376. // Adjust the alignment based on the target max.
  1377. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1378. if (TargetVectorAlign && TargetVectorAlign < Align)
  1379. Align = TargetVectorAlign;
  1380. break;
  1381. }
  1382. case Type::Builtin:
  1383. switch (cast<BuiltinType>(T)->getKind()) {
  1384. default: llvm_unreachable("Unknown builtin type!");
  1385. case BuiltinType::Void:
  1386. // GCC extension: alignof(void) = 8 bits.
  1387. Width = 0;
  1388. Align = 8;
  1389. break;
  1390. case BuiltinType::Bool:
  1391. Width = Target->getBoolWidth();
  1392. Align = Target->getBoolAlign();
  1393. break;
  1394. case BuiltinType::Char_S:
  1395. case BuiltinType::Char_U:
  1396. case BuiltinType::UChar:
  1397. case BuiltinType::SChar:
  1398. Width = Target->getCharWidth();
  1399. Align = Target->getCharAlign();
  1400. break;
  1401. case BuiltinType::WChar_S:
  1402. case BuiltinType::WChar_U:
  1403. Width = Target->getWCharWidth();
  1404. Align = Target->getWCharAlign();
  1405. break;
  1406. case BuiltinType::Char16:
  1407. Width = Target->getChar16Width();
  1408. Align = Target->getChar16Align();
  1409. break;
  1410. case BuiltinType::Char32:
  1411. Width = Target->getChar32Width();
  1412. Align = Target->getChar32Align();
  1413. break;
  1414. case BuiltinType::Min16UInt: // HLSL Change
  1415. case BuiltinType::UShort:
  1416. case BuiltinType::Short:
  1417. Width = Target->getShortWidth();
  1418. Align = Target->getShortAlign();
  1419. break;
  1420. case BuiltinType::UInt:
  1421. case BuiltinType::Int:
  1422. Width = Target->getIntWidth();
  1423. Align = Target->getIntAlign();
  1424. break;
  1425. case BuiltinType::ULong:
  1426. case BuiltinType::Long:
  1427. Width = Target->getLongWidth();
  1428. Align = Target->getLongAlign();
  1429. break;
  1430. case BuiltinType::ULongLong:
  1431. case BuiltinType::LongLong:
  1432. Width = Target->getLongLongWidth();
  1433. Align = Target->getLongLongAlign();
  1434. break;
  1435. case BuiltinType::Int128:
  1436. case BuiltinType::UInt128:
  1437. Width = 128;
  1438. Align = 128; // int128_t is 128-bit aligned on all targets.
  1439. break;
  1440. case BuiltinType::Half:
  1441. Width = Target->getHalfWidth();
  1442. Align = Target->getHalfAlign();
  1443. break;
  1444. case BuiltinType::HalfFloat: // HLSL Change
  1445. case BuiltinType::Float:
  1446. Width = Target->getFloatWidth();
  1447. Align = Target->getFloatAlign();
  1448. break;
  1449. case BuiltinType::Double:
  1450. Width = Target->getDoubleWidth();
  1451. Align = Target->getDoubleAlign();
  1452. break;
  1453. // HLSL Change Starts
  1454. case BuiltinType::Min10Float:
  1455. case BuiltinType::Min16Float:
  1456. Width = 16;
  1457. Align = 16;
  1458. break;
  1459. case BuiltinType::Min12Int:
  1460. case BuiltinType::Min16Int:
  1461. Width = 16;
  1462. Align = 16;
  1463. break;
  1464. // Treat literals as largest size possible here, as it will be used
  1465. // to determine MaxWidth in GetExprRange
  1466. case BuiltinType::LitFloat:
  1467. Width = 64;
  1468. Align = 64;
  1469. break;
  1470. case BuiltinType::LitInt:
  1471. Width = 64;
  1472. Align = 64;
  1473. break;
  1474. // HLSL Change Ends
  1475. case BuiltinType::LongDouble:
  1476. Width = Target->getLongDoubleWidth();
  1477. Align = Target->getLongDoubleAlign();
  1478. break;
  1479. case BuiltinType::NullPtr:
  1480. Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
  1481. Align = Target->getPointerAlign(0); // == sizeof(void*)
  1482. break;
  1483. case BuiltinType::ObjCId:
  1484. case BuiltinType::ObjCClass:
  1485. case BuiltinType::ObjCSel:
  1486. Width = Target->getPointerWidth(0);
  1487. Align = Target->getPointerAlign(0);
  1488. break;
  1489. case BuiltinType::OCLSampler:
  1490. // Samplers are modeled as integers.
  1491. Width = Target->getIntWidth();
  1492. Align = Target->getIntAlign();
  1493. break;
  1494. case BuiltinType::OCLEvent:
  1495. case BuiltinType::OCLImage1d:
  1496. case BuiltinType::OCLImage1dArray:
  1497. case BuiltinType::OCLImage1dBuffer:
  1498. case BuiltinType::OCLImage2d:
  1499. case BuiltinType::OCLImage2dArray:
  1500. case BuiltinType::OCLImage3d:
  1501. // Currently these types are pointers to opaque types.
  1502. Width = Target->getPointerWidth(0);
  1503. Align = Target->getPointerAlign(0);
  1504. break;
  1505. }
  1506. break;
  1507. case Type::ObjCObjectPointer:
  1508. Width = Target->getPointerWidth(0);
  1509. Align = Target->getPointerAlign(0);
  1510. break;
  1511. case Type::BlockPointer: {
  1512. unsigned AS = getTargetAddressSpace(
  1513. cast<BlockPointerType>(T)->getPointeeType());
  1514. Width = Target->getPointerWidth(AS);
  1515. Align = Target->getPointerAlign(AS);
  1516. break;
  1517. }
  1518. case Type::LValueReference:
  1519. case Type::RValueReference: {
  1520. // alignof and sizeof should never enter this code path here, so we go
  1521. // the pointer route.
  1522. unsigned AS = getTargetAddressSpace(
  1523. cast<ReferenceType>(T)->getPointeeType());
  1524. Width = Target->getPointerWidth(AS);
  1525. Align = Target->getPointerAlign(AS);
  1526. break;
  1527. }
  1528. case Type::Pointer: {
  1529. unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
  1530. Width = Target->getPointerWidth(AS);
  1531. Align = Target->getPointerAlign(AS);
  1532. break;
  1533. }
  1534. case Type::MemberPointer: {
  1535. const MemberPointerType *MPT = cast<MemberPointerType>(T);
  1536. std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
  1537. break;
  1538. }
  1539. case Type::Complex: {
  1540. // Complex types have the same alignment as their elements, but twice the
  1541. // size.
  1542. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  1543. Width = EltInfo.Width * 2;
  1544. Align = EltInfo.Align;
  1545. break;
  1546. }
  1547. case Type::ObjCObject:
  1548. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  1549. case Type::Adjusted:
  1550. case Type::Decayed:
  1551. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  1552. case Type::ObjCInterface: {
  1553. const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
  1554. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1555. Width = toBits(Layout.getSize());
  1556. Align = toBits(Layout.getAlignment());
  1557. break;
  1558. }
  1559. case Type::Record:
  1560. case Type::Enum: {
  1561. const TagType *TT = cast<TagType>(T);
  1562. if (TT->getDecl()->isInvalidDecl()) {
  1563. Width = 8;
  1564. Align = 8;
  1565. break;
  1566. }
  1567. if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
  1568. const EnumDecl *ED = ET->getDecl();
  1569. TypeInfo Info =
  1570. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  1571. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  1572. Info.Align = AttrAlign;
  1573. Info.AlignIsRequired = true;
  1574. }
  1575. return Info;
  1576. }
  1577. const RecordType *RT = cast<RecordType>(TT);
  1578. const RecordDecl *RD = RT->getDecl();
  1579. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1580. Width = toBits(Layout.getSize());
  1581. Align = toBits(Layout.getAlignment());
  1582. AlignIsRequired = RD->hasAttr<AlignedAttr>();
  1583. break;
  1584. }
  1585. case Type::SubstTemplateTypeParm:
  1586. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  1587. getReplacementType().getTypePtr());
  1588. case Type::Auto: {
  1589. const AutoType *A = cast<AutoType>(T);
  1590. assert(!A->getDeducedType().isNull() &&
  1591. "cannot request the size of an undeduced or dependent auto type");
  1592. return getTypeInfo(A->getDeducedType().getTypePtr());
  1593. }
  1594. case Type::Paren:
  1595. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  1596. case Type::Typedef: {
  1597. const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
  1598. TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
  1599. // If the typedef has an aligned attribute on it, it overrides any computed
  1600. // alignment we have. This violates the GCC documentation (which says that
  1601. // attribute(aligned) can only round up) but matches its implementation.
  1602. if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
  1603. Align = AttrAlign;
  1604. AlignIsRequired = true;
  1605. } else {
  1606. Align = Info.Align;
  1607. AlignIsRequired = Info.AlignIsRequired;
  1608. }
  1609. Width = Info.Width;
  1610. break;
  1611. }
  1612. case Type::Elaborated:
  1613. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  1614. case Type::Attributed:
  1615. return getTypeInfo(
  1616. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  1617. case Type::Atomic: {
  1618. // Start with the base type information.
  1619. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  1620. Width = Info.Width;
  1621. Align = Info.Align;
  1622. // If the size of the type doesn't exceed the platform's max
  1623. // atomic promotion width, make the size and alignment more
  1624. // favorable to atomic operations:
  1625. if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
  1626. // Round the size up to a power of 2.
  1627. if (!llvm::isPowerOf2_64(Width))
  1628. Width = llvm::NextPowerOf2(Width);
  1629. // Set the alignment equal to the size.
  1630. Align = static_cast<unsigned>(Width);
  1631. }
  1632. }
  1633. }
  1634. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  1635. return TypeInfo(Width, Align, AlignIsRequired);
  1636. }
  1637. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  1638. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  1639. // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
  1640. if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
  1641. getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
  1642. getTargetInfo().getABI() == "elfv1-qpx" &&
  1643. T->isSpecificBuiltinType(BuiltinType::Double))
  1644. SimdAlign = 256;
  1645. return SimdAlign;
  1646. }
  1647. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  1648. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  1649. return CharUnits::fromQuantity(BitSize / getCharWidth());
  1650. }
  1651. /// toBits - Convert a size in characters to a size in characters.
  1652. int64_t ASTContext::toBits(CharUnits CharSize) const {
  1653. return CharSize.getQuantity() * getCharWidth();
  1654. }
  1655. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  1656. /// This method does not work on incomplete types.
  1657. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  1658. return getTypeInfoInChars(T).first;
  1659. }
  1660. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  1661. return getTypeInfoInChars(T).first;
  1662. }
  1663. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  1664. /// characters. This method does not work on incomplete types.
  1665. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  1666. return toCharUnitsFromBits(getTypeAlign(T));
  1667. }
  1668. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  1669. return toCharUnitsFromBits(getTypeAlign(T));
  1670. }
  1671. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  1672. /// type for the current target in bits. This can be different than the ABI
  1673. /// alignment in cases where it is beneficial for performance to overalign
  1674. /// a data type.
  1675. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  1676. TypeInfo TI = getTypeInfo(T);
  1677. unsigned ABIAlign = TI.Align;
  1678. T = T->getBaseElementTypeUnsafe();
  1679. // The preferred alignment of member pointers is that of a pointer.
  1680. if (T->isMemberPointerType())
  1681. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  1682. if (Target->getTriple().getArch() == llvm::Triple::xcore)
  1683. return ABIAlign; // Never overalign on XCore.
  1684. // Double and long long should be naturally aligned if possible.
  1685. if (const ComplexType *CT = T->getAs<ComplexType>())
  1686. T = CT->getElementType().getTypePtr();
  1687. if (const EnumType *ET = T->getAs<EnumType>())
  1688. T = ET->getDecl()->getIntegerType().getTypePtr();
  1689. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  1690. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  1691. T->isSpecificBuiltinType(BuiltinType::ULongLong))
  1692. // Don't increase the alignment if an alignment attribute was specified on a
  1693. // typedef declaration.
  1694. if (!TI.AlignIsRequired)
  1695. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  1696. return ABIAlign;
  1697. }
  1698. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  1699. /// for __attribute__((aligned)) on this target, to be used if no alignment
  1700. /// value is specified.
  1701. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
  1702. return getTargetInfo().getDefaultAlignForAttributeAligned();
  1703. }
  1704. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  1705. /// to a global variable of the specified type.
  1706. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  1707. return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
  1708. }
  1709. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  1710. /// should be given to a global variable of the specified type.
  1711. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  1712. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  1713. }
  1714. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  1715. CharUnits Offset = CharUnits::Zero();
  1716. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  1717. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  1718. Offset += Layout->getBaseClassOffset(Base);
  1719. Layout = &getASTRecordLayout(Base);
  1720. }
  1721. return Offset;
  1722. }
  1723. /// DeepCollectObjCIvars -
  1724. /// This routine first collects all declared, but not synthesized, ivars in
  1725. /// super class and then collects all ivars, including those synthesized for
  1726. /// current class. This routine is used for implementation of current class
  1727. /// when all ivars, declared and synthesized are known.
  1728. ///
  1729. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  1730. bool leafClass,
  1731. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  1732. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  1733. DeepCollectObjCIvars(SuperClass, false, Ivars);
  1734. if (!leafClass) {
  1735. for (const auto *I : OI->ivars())
  1736. Ivars.push_back(I);
  1737. } else {
  1738. ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  1739. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  1740. Iv= Iv->getNextIvar())
  1741. Ivars.push_back(Iv);
  1742. }
  1743. }
  1744. /// CollectInheritedProtocols - Collect all protocols in current class and
  1745. /// those inherited by it.
  1746. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  1747. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  1748. if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  1749. // We can use protocol_iterator here instead of
  1750. // all_referenced_protocol_iterator since we are walking all categories.
  1751. for (auto *Proto : OI->all_referenced_protocols()) {
  1752. CollectInheritedProtocols(Proto, Protocols);
  1753. }
  1754. // Categories of this Interface.
  1755. for (const auto *Cat : OI->visible_categories())
  1756. CollectInheritedProtocols(Cat, Protocols);
  1757. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  1758. while (SD) {
  1759. CollectInheritedProtocols(SD, Protocols);
  1760. SD = SD->getSuperClass();
  1761. }
  1762. } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  1763. for (auto *Proto : OC->protocols()) {
  1764. CollectInheritedProtocols(Proto, Protocols);
  1765. }
  1766. } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  1767. // Insert the protocol.
  1768. if (!Protocols.insert(
  1769. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  1770. return;
  1771. for (auto *Proto : OP->protocols())
  1772. CollectInheritedProtocols(Proto, Protocols);
  1773. }
  1774. }
  1775. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  1776. unsigned count = 0;
  1777. // Count ivars declared in class extension.
  1778. for (const auto *Ext : OI->known_extensions())
  1779. count += Ext->ivar_size();
  1780. // Count ivar defined in this class's implementation. This
  1781. // includes synthesized ivars.
  1782. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  1783. count += ImplDecl->ivar_size();
  1784. return count;
  1785. }
  1786. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  1787. if (!E)
  1788. return false;
  1789. // nullptr_t is always treated as null.
  1790. if (E->getType()->isNullPtrType()) return true;
  1791. if (E->getType()->isAnyPointerType() &&
  1792. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  1793. Expr::NPC_ValueDependentIsNull))
  1794. return true;
  1795. // Unfortunately, __null has type 'int'.
  1796. if (isa<GNUNullExpr>(E)) return true;
  1797. return false;
  1798. }
  1799. /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
  1800. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  1801. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  1802. I = ObjCImpls.find(D);
  1803. if (I != ObjCImpls.end())
  1804. return cast<ObjCImplementationDecl>(I->second);
  1805. return nullptr;
  1806. }
  1807. /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
  1808. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  1809. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  1810. I = ObjCImpls.find(D);
  1811. if (I != ObjCImpls.end())
  1812. return cast<ObjCCategoryImplDecl>(I->second);
  1813. return nullptr;
  1814. }
  1815. /// \brief Set the implementation of ObjCInterfaceDecl.
  1816. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  1817. ObjCImplementationDecl *ImplD) {
  1818. assert(IFaceD && ImplD && "Passed null params");
  1819. ObjCImpls[IFaceD] = ImplD;
  1820. }
  1821. /// \brief Set the implementation of ObjCCategoryDecl.
  1822. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  1823. ObjCCategoryImplDecl *ImplD) {
  1824. assert(CatD && ImplD && "Passed null params");
  1825. ObjCImpls[CatD] = ImplD;
  1826. }
  1827. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  1828. const NamedDecl *ND) const {
  1829. if (const ObjCInterfaceDecl *ID =
  1830. dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  1831. return ID;
  1832. if (const ObjCCategoryDecl *CD =
  1833. dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  1834. return CD->getClassInterface();
  1835. if (const ObjCImplDecl *IMD =
  1836. dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  1837. return IMD->getClassInterface();
  1838. return nullptr;
  1839. }
  1840. /// \brief Get the copy initialization expression of VarDecl,or NULL if
  1841. /// none exists.
  1842. Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
  1843. assert(VD && "Passed null params");
  1844. assert(VD->hasAttr<BlocksAttr>() &&
  1845. "getBlockVarCopyInits - not __block var");
  1846. llvm::DenseMap<const VarDecl*, Expr*>::iterator
  1847. I = BlockVarCopyInits.find(VD);
  1848. return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
  1849. }
  1850. /// \brief Set the copy inialization expression of a block var decl.
  1851. void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
  1852. assert(VD && Init && "Passed null params");
  1853. assert(VD->hasAttr<BlocksAttr>() &&
  1854. "setBlockVarCopyInits - not __block var");
  1855. BlockVarCopyInits[VD] = Init;
  1856. }
  1857. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  1858. unsigned DataSize) const {
  1859. if (!DataSize)
  1860. DataSize = TypeLoc::getFullDataSizeForType(T);
  1861. else
  1862. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  1863. "incorrect data size provided to CreateTypeSourceInfo!");
  1864. TypeSourceInfo *TInfo =
  1865. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  1866. new (TInfo) TypeSourceInfo(T);
  1867. return TInfo;
  1868. }
  1869. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  1870. SourceLocation L) const {
  1871. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  1872. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  1873. return DI;
  1874. }
  1875. const ASTRecordLayout &
  1876. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  1877. return getObjCLayout(D, nullptr);
  1878. }
  1879. const ASTRecordLayout &
  1880. ASTContext::getASTObjCImplementationLayout(
  1881. const ObjCImplementationDecl *D) const {
  1882. return getObjCLayout(D->getClassInterface(), D);
  1883. }
  1884. //===----------------------------------------------------------------------===//
  1885. // Type creation/memoization methods
  1886. //===----------------------------------------------------------------------===//
  1887. QualType
  1888. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  1889. unsigned fastQuals = quals.getFastQualifiers();
  1890. quals.removeFastQualifiers();
  1891. // Check if we've already instantiated this type.
  1892. llvm::FoldingSetNodeID ID;
  1893. ExtQuals::Profile(ID, baseType, quals);
  1894. void *insertPos = nullptr;
  1895. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  1896. assert(eq->getQualifiers() == quals);
  1897. return QualType(eq, fastQuals);
  1898. }
  1899. // If the base type is not canonical, make the appropriate canonical type.
  1900. QualType canon;
  1901. if (!baseType->isCanonicalUnqualified()) {
  1902. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  1903. canonSplit.Quals.addConsistentQualifiers(quals);
  1904. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  1905. // Re-find the insert position.
  1906. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  1907. }
  1908. ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  1909. ExtQualNodes.InsertNode(eq, insertPos);
  1910. return QualType(eq, fastQuals);
  1911. }
  1912. QualType
  1913. ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
  1914. QualType CanT = getCanonicalType(T);
  1915. if (CanT.getAddressSpace() == AddressSpace)
  1916. return T;
  1917. // If we are composing extended qualifiers together, merge together
  1918. // into one ExtQuals node.
  1919. QualifierCollector Quals;
  1920. const Type *TypeNode = Quals.strip(T);
  1921. // If this type already has an address space specified, it cannot get
  1922. // another one.
  1923. assert(!Quals.hasAddressSpace() &&
  1924. "Type cannot be in multiple addr spaces!");
  1925. Quals.addAddressSpace(AddressSpace);
  1926. return getExtQualType(TypeNode, Quals);
  1927. }
  1928. QualType ASTContext::getObjCGCQualType(QualType T,
  1929. Qualifiers::GC GCAttr) const {
  1930. QualType CanT = getCanonicalType(T);
  1931. if (CanT.getObjCGCAttr() == GCAttr)
  1932. return T;
  1933. if (const PointerType *ptr = T->getAs<PointerType>()) {
  1934. QualType Pointee = ptr->getPointeeType();
  1935. if (Pointee->isAnyPointerType()) {
  1936. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  1937. return getPointerType(ResultType);
  1938. }
  1939. }
  1940. // If we are composing extended qualifiers together, merge together
  1941. // into one ExtQuals node.
  1942. QualifierCollector Quals;
  1943. const Type *TypeNode = Quals.strip(T);
  1944. // If this type already has an ObjCGC specified, it cannot get
  1945. // another one.
  1946. assert(!Quals.hasObjCGCAttr() &&
  1947. "Type cannot have multiple ObjCGCs!");
  1948. Quals.addObjCGCAttr(GCAttr);
  1949. return getExtQualType(TypeNode, Quals);
  1950. }
  1951. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  1952. FunctionType::ExtInfo Info) {
  1953. if (T->getExtInfo() == Info)
  1954. return T;
  1955. QualType Result;
  1956. if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  1957. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  1958. } else {
  1959. const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
  1960. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  1961. EPI.ExtInfo = Info;
  1962. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI, FPT->getParamMods());
  1963. }
  1964. return cast<FunctionType>(Result.getTypePtr());
  1965. }
  1966. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  1967. QualType ResultType) {
  1968. FD = FD->getMostRecentDecl();
  1969. while (true) {
  1970. const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
  1971. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  1972. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI, FPT->getParamMods()));
  1973. if (FunctionDecl *Next = FD->getPreviousDecl())
  1974. FD = Next;
  1975. else
  1976. break;
  1977. }
  1978. if (ASTMutationListener *L = getASTMutationListener())
  1979. L->DeducedReturnType(FD, ResultType);
  1980. }
  1981. /// Get a function type and produce the equivalent function type with the
  1982. /// specified exception specification. Type sugar that can be present on a
  1983. /// declaration of a function with an exception specification is permitted
  1984. /// and preserved. Other type sugar (for instance, typedefs) is not.
  1985. static QualType getFunctionTypeWithExceptionSpec(
  1986. ASTContext &Context, QualType Orig,
  1987. const FunctionProtoType::ExceptionSpecInfo &ESI) {
  1988. // Might have some parens.
  1989. if (auto *PT = dyn_cast<ParenType>(Orig))
  1990. return Context.getParenType(
  1991. getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
  1992. // Might have a calling-convention attribute.
  1993. if (auto *AT = dyn_cast<AttributedType>(Orig))
  1994. return Context.getAttributedType(
  1995. AT->getAttrKind(),
  1996. getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
  1997. getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
  1998. ESI));
  1999. // Anything else must be a function type. Rebuild it with the new exception
  2000. // specification.
  2001. const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
  2002. return Context.getFunctionType(
  2003. Proto->getReturnType(), Proto->getParamTypes(),
  2004. Proto->getExtProtoInfo().withExceptionSpec(ESI),
  2005. Proto->getParamMods()); // HLSL Change
  2006. }
  2007. void ASTContext::adjustExceptionSpec(
  2008. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  2009. bool AsWritten) {
  2010. // Update the type.
  2011. QualType Updated =
  2012. getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
  2013. FD->setType(Updated);
  2014. if (!AsWritten)
  2015. return;
  2016. // Update the type in the type source information too.
  2017. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2018. // If the type and the type-as-written differ, we may need to update
  2019. // the type-as-written too.
  2020. if (TSInfo->getType() != FD->getType())
  2021. Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
  2022. // FIXME: When we get proper type location information for exceptions,
  2023. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2024. // up the TypeSourceInfo;
  2025. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2026. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2027. "TypeLoc size mismatch from updating exception specification");
  2028. TSInfo->overrideType(Updated);
  2029. }
  2030. }
  2031. /// getComplexType - Return the uniqued reference to the type for a complex
  2032. /// number with the specified element type.
  2033. QualType ASTContext::getComplexType(QualType T) const {
  2034. // Unique pointers, to guarantee there is only one pointer of a particular
  2035. // structure.
  2036. llvm::FoldingSetNodeID ID;
  2037. ComplexType::Profile(ID, T);
  2038. void *InsertPos = nullptr;
  2039. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2040. return QualType(CT, 0);
  2041. // If the pointee type isn't canonical, this won't be a canonical type either,
  2042. // so fill in the canonical type field.
  2043. QualType Canonical;
  2044. if (!T.isCanonical()) {
  2045. Canonical = getComplexType(getCanonicalType(T));
  2046. // Get the new insert position for the node we care about.
  2047. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2048. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2049. }
  2050. ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2051. Types.push_back(New);
  2052. ComplexTypes.InsertNode(New, InsertPos);
  2053. return QualType(New, 0);
  2054. }
  2055. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2056. /// the specified type.
  2057. QualType ASTContext::getPointerType(QualType T) const {
  2058. // Unique pointers, to guarantee there is only one pointer of a particular
  2059. // structure.
  2060. llvm::FoldingSetNodeID ID;
  2061. PointerType::Profile(ID, T);
  2062. void *InsertPos = nullptr;
  2063. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2064. return QualType(PT, 0);
  2065. // If the pointee type isn't canonical, this won't be a canonical type either,
  2066. // so fill in the canonical type field.
  2067. QualType Canonical;
  2068. if (!T.isCanonical()) {
  2069. Canonical = getPointerType(getCanonicalType(T));
  2070. // Get the new insert position for the node we care about.
  2071. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2072. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2073. }
  2074. PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2075. Types.push_back(New);
  2076. PointerTypes.InsertNode(New, InsertPos);
  2077. return QualType(New, 0);
  2078. }
  2079. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2080. llvm::FoldingSetNodeID ID;
  2081. AdjustedType::Profile(ID, Orig, New);
  2082. void *InsertPos = nullptr;
  2083. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2084. if (AT)
  2085. return QualType(AT, 0);
  2086. QualType Canonical = getCanonicalType(New);
  2087. // Get the new insert position for the node we care about.
  2088. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2089. assert(!AT && "Shouldn't be in the map!");
  2090. AT = new (*this, TypeAlignment)
  2091. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2092. Types.push_back(AT);
  2093. AdjustedTypes.InsertNode(AT, InsertPos);
  2094. return QualType(AT, 0);
  2095. }
  2096. QualType ASTContext::getDecayedType(QualType T) const {
  2097. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2098. if (getLangOpts().HLSL) return T; // HLSL Change - no decay for arrays (or anything for that matter)
  2099. QualType Decayed;
  2100. // C99 6.7.5.3p7:
  2101. // A declaration of a parameter as "array of type" shall be
  2102. // adjusted to "qualified pointer to type", where the type
  2103. // qualifiers (if any) are those specified within the [ and ] of
  2104. // the array type derivation.
  2105. if (T->isArrayType())
  2106. Decayed = getArrayDecayedType(T);
  2107. // C99 6.7.5.3p8:
  2108. // A declaration of a parameter as "function returning type"
  2109. // shall be adjusted to "pointer to function returning type", as
  2110. // in 6.3.2.1.
  2111. if (T->isFunctionType())
  2112. Decayed = getPointerType(T);
  2113. llvm::FoldingSetNodeID ID;
  2114. AdjustedType::Profile(ID, T, Decayed);
  2115. void *InsertPos = nullptr;
  2116. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2117. if (AT)
  2118. return QualType(AT, 0);
  2119. QualType Canonical = getCanonicalType(Decayed);
  2120. // Get the new insert position for the node we care about.
  2121. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2122. assert(!AT && "Shouldn't be in the map!");
  2123. AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
  2124. Types.push_back(AT);
  2125. AdjustedTypes.InsertNode(AT, InsertPos);
  2126. return QualType(AT, 0);
  2127. }
  2128. /// getBlockPointerType - Return the uniqued reference to the type for
  2129. /// a pointer to the specified block.
  2130. QualType ASTContext::getBlockPointerType(QualType T) const {
  2131. assert(T->isFunctionType() && "block of function types only");
  2132. assert(!getLangOpts().HLSL && "HLSL does not support blocks");
  2133. // Unique pointers, to guarantee there is only one block of a particular
  2134. // structure.
  2135. llvm::FoldingSetNodeID ID;
  2136. BlockPointerType::Profile(ID, T);
  2137. void *InsertPos = nullptr;
  2138. if (BlockPointerType *PT =
  2139. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2140. return QualType(PT, 0);
  2141. // If the block pointee type isn't canonical, this won't be a canonical
  2142. // type either so fill in the canonical type field.
  2143. QualType Canonical;
  2144. if (!T.isCanonical()) {
  2145. Canonical = getBlockPointerType(getCanonicalType(T));
  2146. // Get the new insert position for the node we care about.
  2147. BlockPointerType *NewIP =
  2148. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2149. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2150. }
  2151. BlockPointerType *New
  2152. = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2153. Types.push_back(New);
  2154. BlockPointerTypes.InsertNode(New, InsertPos);
  2155. return QualType(New, 0);
  2156. }
  2157. /// getLValueReferenceType - Return the uniqued reference to the type for an
  2158. /// lvalue reference to the specified type.
  2159. QualType
  2160. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  2161. assert(getCanonicalType(T) != OverloadTy &&
  2162. "Unresolved overloaded function type");
  2163. // Unique pointers, to guarantee there is only one pointer of a particular
  2164. // structure.
  2165. llvm::FoldingSetNodeID ID;
  2166. ReferenceType::Profile(ID, T, SpelledAsLValue);
  2167. void *InsertPos = nullptr;
  2168. if (LValueReferenceType *RT =
  2169. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2170. return QualType(RT, 0);
  2171. const ReferenceType *InnerRef = T->getAs<ReferenceType>();
  2172. // If the referencee type isn't canonical, this won't be a canonical type
  2173. // either, so fill in the canonical type field.
  2174. QualType Canonical;
  2175. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  2176. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2177. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  2178. // Get the new insert position for the node we care about.
  2179. LValueReferenceType *NewIP =
  2180. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2181. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2182. }
  2183. LValueReferenceType *New
  2184. = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  2185. SpelledAsLValue);
  2186. Types.push_back(New);
  2187. LValueReferenceTypes.InsertNode(New, InsertPos);
  2188. return QualType(New, 0);
  2189. }
  2190. /// getRValueReferenceType - Return the uniqued reference to the type for an
  2191. /// rvalue reference to the specified type.
  2192. QualType ASTContext::getRValueReferenceType(QualType T) const {
  2193. // Unique pointers, to guarantee there is only one pointer of a particular
  2194. // structure.
  2195. llvm::FoldingSetNodeID ID;
  2196. ReferenceType::Profile(ID, T, false);
  2197. void *InsertPos = nullptr;
  2198. if (RValueReferenceType *RT =
  2199. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2200. return QualType(RT, 0);
  2201. const ReferenceType *InnerRef = T->getAs<ReferenceType>();
  2202. // If the referencee type isn't canonical, this won't be a canonical type
  2203. // either, so fill in the canonical type field.
  2204. QualType Canonical;
  2205. if (InnerRef || !T.isCanonical()) {
  2206. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2207. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  2208. // Get the new insert position for the node we care about.
  2209. RValueReferenceType *NewIP =
  2210. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2211. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2212. }
  2213. RValueReferenceType *New
  2214. = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  2215. Types.push_back(New);
  2216. RValueReferenceTypes.InsertNode(New, InsertPos);
  2217. return QualType(New, 0);
  2218. }
  2219. /// getMemberPointerType - Return the uniqued reference to the type for a
  2220. /// member pointer to the specified type, in the specified class.
  2221. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  2222. // Unique pointers, to guarantee there is only one pointer of a particular
  2223. // structure.
  2224. llvm::FoldingSetNodeID ID;
  2225. MemberPointerType::Profile(ID, T, Cls);
  2226. void *InsertPos = nullptr;
  2227. if (MemberPointerType *PT =
  2228. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2229. return QualType(PT, 0);
  2230. // If the pointee or class type isn't canonical, this won't be a canonical
  2231. // type either, so fill in the canonical type field.
  2232. QualType Canonical;
  2233. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  2234. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  2235. // Get the new insert position for the node we care about.
  2236. MemberPointerType *NewIP =
  2237. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2238. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2239. }
  2240. MemberPointerType *New
  2241. = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  2242. Types.push_back(New);
  2243. MemberPointerTypes.InsertNode(New, InsertPos);
  2244. return QualType(New, 0);
  2245. }
  2246. /// getConstantArrayType - Return the unique reference to the type for an
  2247. /// array of the specified element type.
  2248. QualType ASTContext::getConstantArrayType(QualType EltTy,
  2249. const llvm::APInt &ArySizeIn,
  2250. ArrayType::ArraySizeModifier ASM,
  2251. unsigned IndexTypeQuals) const {
  2252. assert((EltTy->isDependentType() ||
  2253. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  2254. "Constant array of VLAs is illegal!");
  2255. // Convert the array size into a canonical width matching the pointer size for
  2256. // the target.
  2257. llvm::APInt ArySize(ArySizeIn);
  2258. ArySize =
  2259. ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
  2260. llvm::FoldingSetNodeID ID;
  2261. ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
  2262. void *InsertPos = nullptr;
  2263. if (ConstantArrayType *ATP =
  2264. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  2265. return QualType(ATP, 0);
  2266. // If the element type isn't canonical or has qualifiers, this won't
  2267. // be a canonical type either, so fill in the canonical type field.
  2268. QualType Canon;
  2269. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2270. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2271. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
  2272. ASM, IndexTypeQuals);
  2273. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2274. // Get the new insert position for the node we care about.
  2275. ConstantArrayType *NewIP =
  2276. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  2277. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2278. }
  2279. ConstantArrayType *New = new(*this,TypeAlignment)
  2280. ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
  2281. ConstantArrayTypes.InsertNode(New, InsertPos);
  2282. Types.push_back(New);
  2283. return QualType(New, 0);
  2284. }
  2285. /// getVariableArrayDecayedType - Turns the given type, which may be
  2286. /// variably-modified, into the corresponding type with all the known
  2287. /// sizes replaced with [*].
  2288. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  2289. // Vastly most common case.
  2290. if (!type->isVariablyModifiedType()) return type;
  2291. QualType result;
  2292. SplitQualType split = type.getSplitDesugaredType();
  2293. const Type *ty = split.Ty;
  2294. switch (ty->getTypeClass()) {
  2295. #define TYPE(Class, Base)
  2296. #define ABSTRACT_TYPE(Class, Base)
  2297. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2298. #include "clang/AST/TypeNodes.def"
  2299. llvm_unreachable("didn't desugar past all non-canonical types?");
  2300. // These types should never be variably-modified.
  2301. case Type::Builtin:
  2302. case Type::Complex:
  2303. case Type::Vector:
  2304. case Type::ExtVector:
  2305. case Type::DependentSizedExtVector:
  2306. case Type::ObjCObject:
  2307. case Type::ObjCInterface:
  2308. case Type::ObjCObjectPointer:
  2309. case Type::Record:
  2310. case Type::Enum:
  2311. case Type::UnresolvedUsing:
  2312. case Type::TypeOfExpr:
  2313. case Type::TypeOf:
  2314. case Type::Decltype:
  2315. case Type::UnaryTransform:
  2316. case Type::DependentName:
  2317. case Type::InjectedClassName:
  2318. case Type::TemplateSpecialization:
  2319. case Type::DependentTemplateSpecialization:
  2320. case Type::TemplateTypeParm:
  2321. case Type::SubstTemplateTypeParmPack:
  2322. case Type::Auto:
  2323. case Type::PackExpansion:
  2324. llvm_unreachable("type should never be variably-modified");
  2325. // These types can be variably-modified but should never need to
  2326. // further decay.
  2327. case Type::FunctionNoProto:
  2328. case Type::FunctionProto:
  2329. case Type::BlockPointer:
  2330. case Type::MemberPointer:
  2331. return type;
  2332. // These types can be variably-modified. All these modifications
  2333. // preserve structure except as noted by comments.
  2334. // TODO: if we ever care about optimizing VLAs, there are no-op
  2335. // optimizations available here.
  2336. case Type::Pointer:
  2337. result = getPointerType(getVariableArrayDecayedType(
  2338. cast<PointerType>(ty)->getPointeeType()));
  2339. break;
  2340. case Type::LValueReference: {
  2341. const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
  2342. result = getLValueReferenceType(
  2343. getVariableArrayDecayedType(lv->getPointeeType()),
  2344. lv->isSpelledAsLValue());
  2345. break;
  2346. }
  2347. case Type::RValueReference: {
  2348. const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
  2349. result = getRValueReferenceType(
  2350. getVariableArrayDecayedType(lv->getPointeeType()));
  2351. break;
  2352. }
  2353. case Type::Atomic: {
  2354. const AtomicType *at = cast<AtomicType>(ty);
  2355. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  2356. break;
  2357. }
  2358. case Type::ConstantArray: {
  2359. const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
  2360. result = getConstantArrayType(
  2361. getVariableArrayDecayedType(cat->getElementType()),
  2362. cat->getSize(),
  2363. cat->getSizeModifier(),
  2364. cat->getIndexTypeCVRQualifiers());
  2365. break;
  2366. }
  2367. case Type::DependentSizedArray: {
  2368. const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
  2369. result = getDependentSizedArrayType(
  2370. getVariableArrayDecayedType(dat->getElementType()),
  2371. dat->getSizeExpr(),
  2372. dat->getSizeModifier(),
  2373. dat->getIndexTypeCVRQualifiers(),
  2374. dat->getBracketsRange());
  2375. break;
  2376. }
  2377. // Turn incomplete types into [*] types.
  2378. case Type::IncompleteArray: {
  2379. const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
  2380. result = getVariableArrayType(
  2381. getVariableArrayDecayedType(iat->getElementType()),
  2382. /*size*/ nullptr,
  2383. ArrayType::Normal,
  2384. iat->getIndexTypeCVRQualifiers(),
  2385. SourceRange());
  2386. break;
  2387. }
  2388. // Turn VLA types into [*] types.
  2389. case Type::VariableArray: {
  2390. const VariableArrayType *vat = cast<VariableArrayType>(ty);
  2391. result = getVariableArrayType(
  2392. getVariableArrayDecayedType(vat->getElementType()),
  2393. /*size*/ nullptr,
  2394. ArrayType::Star,
  2395. vat->getIndexTypeCVRQualifiers(),
  2396. vat->getBracketsRange());
  2397. break;
  2398. }
  2399. }
  2400. // Apply the top-level qualifiers from the original.
  2401. return getQualifiedType(result, split.Quals);
  2402. }
  2403. /// getVariableArrayType - Returns a non-unique reference to the type for a
  2404. /// variable array of the specified element type.
  2405. QualType ASTContext::getVariableArrayType(QualType EltTy,
  2406. Expr *NumElts,
  2407. ArrayType::ArraySizeModifier ASM,
  2408. unsigned IndexTypeQuals,
  2409. SourceRange Brackets) const {
  2410. // Since we don't unique expressions, it isn't possible to unique VLA's
  2411. // that have an expression provided for their size.
  2412. QualType Canon;
  2413. // Be sure to pull qualifiers off the element type.
  2414. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2415. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2416. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  2417. IndexTypeQuals, Brackets);
  2418. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2419. }
  2420. VariableArrayType *New = new(*this, TypeAlignment)
  2421. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  2422. VariableArrayTypes.push_back(New);
  2423. Types.push_back(New);
  2424. return QualType(New, 0);
  2425. }
  2426. /// getDependentSizedArrayType - Returns a non-unique reference to
  2427. /// the type for a dependently-sized array of the specified element
  2428. /// type.
  2429. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  2430. Expr *numElements,
  2431. ArrayType::ArraySizeModifier ASM,
  2432. unsigned elementTypeQuals,
  2433. SourceRange brackets) const {
  2434. assert((!numElements || numElements->isTypeDependent() ||
  2435. numElements->isValueDependent()) &&
  2436. "Size must be type- or value-dependent!");
  2437. // Dependently-sized array types that do not have a specified number
  2438. // of elements will have their sizes deduced from a dependent
  2439. // initializer. We do no canonicalization here at all, which is okay
  2440. // because they can't be used in most locations.
  2441. if (!numElements) {
  2442. DependentSizedArrayType *newType
  2443. = new (*this, TypeAlignment)
  2444. DependentSizedArrayType(*this, elementType, QualType(),
  2445. numElements, ASM, elementTypeQuals,
  2446. brackets);
  2447. Types.push_back(newType);
  2448. return QualType(newType, 0);
  2449. }
  2450. // Otherwise, we actually build a new type every time, but we
  2451. // also build a canonical type.
  2452. SplitQualType canonElementType = getCanonicalType(elementType).split();
  2453. void *insertPos = nullptr;
  2454. llvm::FoldingSetNodeID ID;
  2455. DependentSizedArrayType::Profile(ID, *this,
  2456. QualType(canonElementType.Ty, 0),
  2457. ASM, elementTypeQuals, numElements);
  2458. // Look for an existing type with these properties.
  2459. DependentSizedArrayType *canonTy =
  2460. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2461. // If we don't have one, build one.
  2462. if (!canonTy) {
  2463. canonTy = new (*this, TypeAlignment)
  2464. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  2465. QualType(), numElements, ASM, elementTypeQuals,
  2466. brackets);
  2467. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  2468. Types.push_back(canonTy);
  2469. }
  2470. // Apply qualifiers from the element type to the array.
  2471. QualType canon = getQualifiedType(QualType(canonTy,0),
  2472. canonElementType.Quals);
  2473. // If we didn't need extra canonicalization for the element type,
  2474. // then just use that as our result.
  2475. if (QualType(canonElementType.Ty, 0) == elementType)
  2476. return canon;
  2477. // Otherwise, we need to build a type which follows the spelling
  2478. // of the element type.
  2479. DependentSizedArrayType *sugaredType
  2480. = new (*this, TypeAlignment)
  2481. DependentSizedArrayType(*this, elementType, canon, numElements,
  2482. ASM, elementTypeQuals, brackets);
  2483. Types.push_back(sugaredType);
  2484. return QualType(sugaredType, 0);
  2485. }
  2486. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  2487. ArrayType::ArraySizeModifier ASM,
  2488. unsigned elementTypeQuals) const {
  2489. llvm::FoldingSetNodeID ID;
  2490. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  2491. void *insertPos = nullptr;
  2492. if (IncompleteArrayType *iat =
  2493. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  2494. return QualType(iat, 0);
  2495. // If the element type isn't canonical, this won't be a canonical type
  2496. // either, so fill in the canonical type field. We also have to pull
  2497. // qualifiers off the element type.
  2498. QualType canon;
  2499. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  2500. SplitQualType canonSplit = getCanonicalType(elementType).split();
  2501. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  2502. ASM, elementTypeQuals);
  2503. canon = getQualifiedType(canon, canonSplit.Quals);
  2504. // Get the new insert position for the node we care about.
  2505. IncompleteArrayType *existing =
  2506. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2507. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  2508. }
  2509. IncompleteArrayType *newType = new (*this, TypeAlignment)
  2510. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  2511. IncompleteArrayTypes.InsertNode(newType, insertPos);
  2512. Types.push_back(newType);
  2513. return QualType(newType, 0);
  2514. }
  2515. /// getVectorType - Return the unique reference to a vector type of
  2516. /// the specified element type and size. VectorType must be a built-in type.
  2517. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  2518. VectorType::VectorKind VecKind) const {
  2519. assert(vecType->isBuiltinType());
  2520. // Check if we've already instantiated a vector of this type.
  2521. llvm::FoldingSetNodeID ID;
  2522. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  2523. void *InsertPos = nullptr;
  2524. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  2525. return QualType(VTP, 0);
  2526. // If the element type isn't canonical, this won't be a canonical type either,
  2527. // so fill in the canonical type field.
  2528. QualType Canonical;
  2529. if (!vecType.isCanonical()) {
  2530. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  2531. // Get the new insert position for the node we care about.
  2532. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2533. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2534. }
  2535. VectorType *New = new (*this, TypeAlignment)
  2536. VectorType(vecType, NumElts, Canonical, VecKind);
  2537. VectorTypes.InsertNode(New, InsertPos);
  2538. Types.push_back(New);
  2539. return QualType(New, 0);
  2540. }
  2541. /// getExtVectorType - Return the unique reference to an extended vector type of
  2542. /// the specified element type and size. VectorType must be a built-in type.
  2543. QualType
  2544. ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
  2545. assert(vecType->isBuiltinType() || vecType->isDependentType());
  2546. // Check if we've already instantiated a vector of this type.
  2547. llvm::FoldingSetNodeID ID;
  2548. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  2549. VectorType::GenericVector);
  2550. void *InsertPos = nullptr;
  2551. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  2552. return QualType(VTP, 0);
  2553. // If the element type isn't canonical, this won't be a canonical type either,
  2554. // so fill in the canonical type field.
  2555. QualType Canonical;
  2556. if (!vecType.isCanonical()) {
  2557. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  2558. // Get the new insert position for the node we care about.
  2559. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2560. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2561. }
  2562. ExtVectorType *New = new (*this, TypeAlignment)
  2563. ExtVectorType(vecType, NumElts, Canonical);
  2564. VectorTypes.InsertNode(New, InsertPos);
  2565. Types.push_back(New);
  2566. return QualType(New, 0);
  2567. }
  2568. QualType
  2569. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  2570. Expr *SizeExpr,
  2571. SourceLocation AttrLoc) const {
  2572. llvm::FoldingSetNodeID ID;
  2573. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  2574. SizeExpr);
  2575. void *InsertPos = nullptr;
  2576. DependentSizedExtVectorType *Canon
  2577. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2578. DependentSizedExtVectorType *New;
  2579. if (Canon) {
  2580. // We already have a canonical version of this array type; use it as
  2581. // the canonical type for a newly-built type.
  2582. New = new (*this, TypeAlignment)
  2583. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  2584. SizeExpr, AttrLoc);
  2585. } else {
  2586. QualType CanonVecTy = getCanonicalType(vecType);
  2587. if (CanonVecTy == vecType) {
  2588. New = new (*this, TypeAlignment)
  2589. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  2590. AttrLoc);
  2591. DependentSizedExtVectorType *CanonCheck
  2592. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  2593. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  2594. (void)CanonCheck;
  2595. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  2596. } else {
  2597. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  2598. SourceLocation());
  2599. New = new (*this, TypeAlignment)
  2600. DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
  2601. }
  2602. }
  2603. Types.push_back(New);
  2604. return QualType(New, 0);
  2605. }
  2606. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  2607. ///
  2608. QualType
  2609. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  2610. const FunctionType::ExtInfo &Info) const {
  2611. const CallingConv CallConv = Info.getCC();
  2612. // Unique functions, to guarantee there is only one function of a particular
  2613. // structure.
  2614. llvm::FoldingSetNodeID ID;
  2615. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  2616. void *InsertPos = nullptr;
  2617. if (FunctionNoProtoType *FT =
  2618. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  2619. return QualType(FT, 0);
  2620. QualType Canonical;
  2621. if (!ResultTy.isCanonical()) {
  2622. Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
  2623. // Get the new insert position for the node we care about.
  2624. FunctionNoProtoType *NewIP =
  2625. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  2626. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2627. }
  2628. FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
  2629. FunctionNoProtoType *New = new (*this, TypeAlignment)
  2630. FunctionNoProtoType(ResultTy, Canonical, newInfo);
  2631. Types.push_back(New);
  2632. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  2633. return QualType(New, 0);
  2634. }
  2635. /// \brief Determine whether \p T is canonical as the result type of a function.
  2636. static bool isCanonicalResultType(QualType T) {
  2637. return T.isCanonical() &&
  2638. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  2639. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  2640. }
  2641. QualType
  2642. ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
  2643. const FunctionProtoType::ExtProtoInfo &EPI,
  2644. ArrayRef<hlsl::ParameterModifier> ParamMods) const { // HLSL Change - param mods
  2645. size_t NumArgs = ArgArray.size();
  2646. // Unique functions, to guarantee there is only one function of a particular
  2647. // structure.
  2648. llvm::FoldingSetNodeID ID;
  2649. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI, ParamMods, // HLSL Change - param mods
  2650. *this);
  2651. void *InsertPos = nullptr;
  2652. if (FunctionProtoType *FTP =
  2653. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  2654. return QualType(FTP, 0);
  2655. // Determine whether the type being created is already canonical or not.
  2656. bool isCanonical =
  2657. EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
  2658. !EPI.HasTrailingReturn;
  2659. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  2660. if (!ArgArray[i].isCanonicalAsParam() &&
  2661. // HLSL Change Begins.
  2662. // Don't decay array to pointer.
  2663. // But do need to get canonical version of array.
  2664. !(getLangOpts().HLSL && ArgArray[i]->isArrayType() &&
  2665. ArgArray[i].isCanonical()))
  2666. // HLSL Change Ends.
  2667. isCanonical = false;
  2668. // If this type isn't canonical, get the canonical version of it.
  2669. // The exception spec is not part of the canonical type.
  2670. QualType Canonical;
  2671. if (!isCanonical) {
  2672. SmallVector<QualType, 16> CanonicalArgs;
  2673. CanonicalArgs.reserve(NumArgs);
  2674. for (unsigned i = 0; i != NumArgs; ++i)
  2675. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  2676. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  2677. CanonicalEPI.HasTrailingReturn = false;
  2678. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  2679. // Result types do not have ARC lifetime qualifiers.
  2680. QualType CanResultTy = getCanonicalType(ResultTy);
  2681. if (ResultTy.getQualifiers().hasObjCLifetime()) {
  2682. Qualifiers Qs = CanResultTy.getQualifiers();
  2683. Qs.removeObjCLifetime();
  2684. CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
  2685. }
  2686. Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI, ParamMods); // HLSL Change - param mods
  2687. // Get the new insert position for the node we care about.
  2688. FunctionProtoType *NewIP =
  2689. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  2690. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2691. }
  2692. // FunctionProtoType objects are allocated with extra bytes after
  2693. // them for three variable size arrays at the end:
  2694. // - parameter types
  2695. // - exception types
  2696. // - consumed-arguments flags
  2697. // Instead of the exception types, there could be a noexcept
  2698. // expression, or information used to resolve the exception
  2699. // specification.
  2700. size_t Size = sizeof(FunctionProtoType) +
  2701. NumArgs * sizeof(QualType);
  2702. if (EPI.ExceptionSpec.Type == EST_Dynamic) {
  2703. Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
  2704. } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
  2705. Size += sizeof(Expr*);
  2706. } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
  2707. Size += 2 * sizeof(FunctionDecl*);
  2708. } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
  2709. Size += sizeof(FunctionDecl*);
  2710. }
  2711. // HLSL Change Starts
  2712. if (getLangOpts().HLSL) {
  2713. assert((Size == sizeof(FunctionProtoType) + NumArgs * sizeof(QualType)) && "else exception spec was added");
  2714. Size += NumArgs * sizeof(hlsl::ParameterModifier);
  2715. }
  2716. // HLSL Change Ends
  2717. if (EPI.ConsumedParameters)
  2718. Size += NumArgs * sizeof(bool);
  2719. FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
  2720. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  2721. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI, ParamMods); // HLSL - param mods
  2722. Types.push_back(FTP);
  2723. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  2724. return QualType(FTP, 0);
  2725. }
  2726. #ifndef NDEBUG
  2727. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  2728. if (!isa<CXXRecordDecl>(D)) return false;
  2729. const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
  2730. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  2731. return true;
  2732. if (RD->getDescribedClassTemplate() &&
  2733. !isa<ClassTemplateSpecializationDecl>(RD))
  2734. return true;
  2735. return false;
  2736. }
  2737. #endif
  2738. /// getInjectedClassNameType - Return the unique reference to the
  2739. /// injected class name type for the specified templated declaration.
  2740. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  2741. QualType TST) const {
  2742. assert(NeedsInjectedClassNameType(Decl));
  2743. if (Decl->TypeForDecl) {
  2744. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  2745. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  2746. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  2747. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  2748. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  2749. } else {
  2750. Type *newType =
  2751. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  2752. Decl->TypeForDecl = newType;
  2753. Types.push_back(newType);
  2754. }
  2755. return QualType(Decl->TypeForDecl, 0);
  2756. }
  2757. /// getTypeDeclType - Return the unique reference to the type for the
  2758. /// specified type declaration.
  2759. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  2760. assert(Decl && "Passed null for Decl param");
  2761. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  2762. if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  2763. return getTypedefType(Typedef);
  2764. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  2765. "Template type parameter types are always available.");
  2766. if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
  2767. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  2768. assert(!NeedsInjectedClassNameType(Record));
  2769. return getRecordType(Record);
  2770. } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
  2771. assert(Enum->isFirstDecl() && "enum has previous declaration");
  2772. return getEnumType(Enum);
  2773. } else if (const UnresolvedUsingTypenameDecl *Using =
  2774. dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  2775. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
  2776. Decl->TypeForDecl = newType;
  2777. Types.push_back(newType);
  2778. } else
  2779. llvm_unreachable("TypeDecl without a type?");
  2780. return QualType(Decl->TypeForDecl, 0);
  2781. }
  2782. /// getTypedefType - Return the unique reference to the type for the
  2783. /// specified typedef name decl.
  2784. QualType
  2785. ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  2786. QualType Canonical) const {
  2787. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2788. if (Canonical.isNull())
  2789. Canonical = getCanonicalType(Decl->getUnderlyingType());
  2790. TypedefType *newType = new(*this, TypeAlignment)
  2791. TypedefType(Type::Typedef, Decl, Canonical);
  2792. Decl->TypeForDecl = newType;
  2793. Types.push_back(newType);
  2794. return QualType(newType, 0);
  2795. }
  2796. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  2797. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2798. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  2799. if (PrevDecl->TypeForDecl)
  2800. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  2801. RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
  2802. Decl->TypeForDecl = newType;
  2803. Types.push_back(newType);
  2804. return QualType(newType, 0);
  2805. }
  2806. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  2807. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  2808. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  2809. if (PrevDecl->TypeForDecl)
  2810. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  2811. EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
  2812. Decl->TypeForDecl = newType;
  2813. Types.push_back(newType);
  2814. return QualType(newType, 0);
  2815. }
  2816. QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
  2817. QualType modifiedType,
  2818. QualType equivalentType) {
  2819. llvm::FoldingSetNodeID id;
  2820. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  2821. void *insertPos = nullptr;
  2822. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  2823. if (type) return QualType(type, 0);
  2824. QualType canon = getCanonicalType(equivalentType);
  2825. type = new (*this, TypeAlignment)
  2826. AttributedType(canon, attrKind, modifiedType, equivalentType);
  2827. Types.push_back(type);
  2828. AttributedTypes.InsertNode(type, insertPos);
  2829. return QualType(type, 0);
  2830. }
  2831. /// \brief Retrieve a substitution-result type.
  2832. QualType
  2833. ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
  2834. QualType Replacement) const {
  2835. assert(Replacement.isCanonical()
  2836. && "replacement types must always be canonical");
  2837. llvm::FoldingSetNodeID ID;
  2838. SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
  2839. void *InsertPos = nullptr;
  2840. SubstTemplateTypeParmType *SubstParm
  2841. = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2842. if (!SubstParm) {
  2843. SubstParm = new (*this, TypeAlignment)
  2844. SubstTemplateTypeParmType(Parm, Replacement);
  2845. Types.push_back(SubstParm);
  2846. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  2847. }
  2848. return QualType(SubstParm, 0);
  2849. }
  2850. /// \brief Retrieve a
  2851. QualType ASTContext::getSubstTemplateTypeParmPackType(
  2852. const TemplateTypeParmType *Parm,
  2853. const TemplateArgument &ArgPack) {
  2854. #ifndef NDEBUG
  2855. for (const auto &P : ArgPack.pack_elements()) {
  2856. assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
  2857. assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
  2858. }
  2859. #endif
  2860. llvm::FoldingSetNodeID ID;
  2861. SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
  2862. void *InsertPos = nullptr;
  2863. if (SubstTemplateTypeParmPackType *SubstParm
  2864. = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  2865. return QualType(SubstParm, 0);
  2866. QualType Canon;
  2867. if (!Parm->isCanonicalUnqualified()) {
  2868. Canon = getCanonicalType(QualType(Parm, 0));
  2869. Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
  2870. ArgPack);
  2871. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  2872. }
  2873. SubstTemplateTypeParmPackType *SubstParm
  2874. = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
  2875. ArgPack);
  2876. Types.push_back(SubstParm);
  2877. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  2878. return QualType(SubstParm, 0);
  2879. }
  2880. /// \brief Retrieve the template type parameter type for a template
  2881. /// parameter or parameter pack with the given depth, index, and (optionally)
  2882. /// name.
  2883. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  2884. bool ParameterPack,
  2885. TemplateTypeParmDecl *TTPDecl) const {
  2886. llvm::FoldingSetNodeID ID;
  2887. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  2888. void *InsertPos = nullptr;
  2889. TemplateTypeParmType *TypeParm
  2890. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2891. if (TypeParm)
  2892. return QualType(TypeParm, 0);
  2893. if (TTPDecl) {
  2894. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  2895. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  2896. TemplateTypeParmType *TypeCheck
  2897. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  2898. assert(!TypeCheck && "Template type parameter canonical type broken");
  2899. (void)TypeCheck;
  2900. } else
  2901. TypeParm = new (*this, TypeAlignment)
  2902. TemplateTypeParmType(Depth, Index, ParameterPack);
  2903. Types.push_back(TypeParm);
  2904. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  2905. return QualType(TypeParm, 0);
  2906. }
  2907. TypeSourceInfo *
  2908. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  2909. SourceLocation NameLoc,
  2910. const TemplateArgumentListInfo &Args,
  2911. QualType Underlying) const {
  2912. assert(!Name.getAsDependentTemplateName() &&
  2913. "No dependent template names here!");
  2914. QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
  2915. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  2916. TemplateSpecializationTypeLoc TL =
  2917. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  2918. TL.setTemplateKeywordLoc(SourceLocation());
  2919. TL.setTemplateNameLoc(NameLoc);
  2920. TL.setLAngleLoc(Args.getLAngleLoc());
  2921. TL.setRAngleLoc(Args.getRAngleLoc());
  2922. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  2923. TL.setArgLocInfo(i, Args[i].getLocInfo());
  2924. return DI;
  2925. }
  2926. QualType
  2927. ASTContext::getTemplateSpecializationType(TemplateName Template,
  2928. const TemplateArgumentListInfo &Args,
  2929. QualType Underlying) const {
  2930. assert(!Template.getAsDependentTemplateName() &&
  2931. "No dependent template names here!");
  2932. unsigned NumArgs = Args.size();
  2933. SmallVector<TemplateArgument, 4> ArgVec;
  2934. ArgVec.reserve(NumArgs);
  2935. for (unsigned i = 0; i != NumArgs; ++i)
  2936. ArgVec.push_back(Args[i].getArgument());
  2937. return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
  2938. Underlying);
  2939. }
  2940. #ifndef NDEBUG
  2941. static bool hasAnyPackExpansions(const TemplateArgument *Args,
  2942. unsigned NumArgs) {
  2943. for (unsigned I = 0; I != NumArgs; ++I)
  2944. if (Args[I].isPackExpansion())
  2945. return true;
  2946. return true;
  2947. }
  2948. #endif
  2949. QualType
  2950. ASTContext::getTemplateSpecializationType(TemplateName Template,
  2951. const TemplateArgument *Args,
  2952. unsigned NumArgs,
  2953. QualType Underlying) const {
  2954. assert(!Template.getAsDependentTemplateName() &&
  2955. "No dependent template names here!");
  2956. // Look through qualified template names.
  2957. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  2958. Template = TemplateName(QTN->getTemplateDecl());
  2959. bool IsTypeAlias =
  2960. Template.getAsTemplateDecl() &&
  2961. isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
  2962. QualType CanonType;
  2963. if (!Underlying.isNull())
  2964. CanonType = getCanonicalType(Underlying);
  2965. else {
  2966. // We can get here with an alias template when the specialization contains
  2967. // a pack expansion that does not match up with a parameter pack.
  2968. assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
  2969. "Caller must compute aliased type");
  2970. IsTypeAlias = false;
  2971. CanonType = getCanonicalTemplateSpecializationType(Template, Args,
  2972. NumArgs);
  2973. }
  2974. // Allocate the (non-canonical) template specialization type, but don't
  2975. // try to unique it: these types typically have location information that
  2976. // we don't unique and don't want to lose.
  2977. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  2978. sizeof(TemplateArgument) * NumArgs +
  2979. (IsTypeAlias? sizeof(QualType) : 0),
  2980. TypeAlignment);
  2981. TemplateSpecializationType *Spec
  2982. = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
  2983. IsTypeAlias ? Underlying : QualType());
  2984. Types.push_back(Spec);
  2985. return QualType(Spec, 0);
  2986. }
  2987. QualType
  2988. ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
  2989. const TemplateArgument *Args,
  2990. unsigned NumArgs) const {
  2991. assert(!Template.getAsDependentTemplateName() &&
  2992. "No dependent template names here!");
  2993. // Look through qualified template names.
  2994. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  2995. Template = TemplateName(QTN->getTemplateDecl());
  2996. // Build the canonical template specialization type.
  2997. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  2998. SmallVector<TemplateArgument, 4> CanonArgs;
  2999. CanonArgs.reserve(NumArgs);
  3000. for (unsigned I = 0; I != NumArgs; ++I)
  3001. CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
  3002. // Determine whether this canonical template specialization type already
  3003. // exists.
  3004. llvm::FoldingSetNodeID ID;
  3005. TemplateSpecializationType::Profile(ID, CanonTemplate,
  3006. CanonArgs.data(), NumArgs, *this);
  3007. void *InsertPos = nullptr;
  3008. TemplateSpecializationType *Spec
  3009. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3010. if (!Spec) {
  3011. // Allocate a new canonical template specialization type.
  3012. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  3013. sizeof(TemplateArgument) * NumArgs),
  3014. TypeAlignment);
  3015. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  3016. CanonArgs.data(), NumArgs,
  3017. QualType(), QualType());
  3018. Types.push_back(Spec);
  3019. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  3020. }
  3021. assert(Spec->isDependentType() &&
  3022. "Non-dependent template-id type must have a canonical type");
  3023. return QualType(Spec, 0);
  3024. }
  3025. QualType
  3026. ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3027. NestedNameSpecifier *NNS,
  3028. QualType NamedType) const {
  3029. llvm::FoldingSetNodeID ID;
  3030. ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
  3031. void *InsertPos = nullptr;
  3032. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3033. if (T)
  3034. return QualType(T, 0);
  3035. QualType Canon = NamedType;
  3036. if (!Canon.isCanonical()) {
  3037. Canon = getCanonicalType(NamedType);
  3038. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3039. assert(!CheckT && "Elaborated canonical type broken");
  3040. (void)CheckT;
  3041. }
  3042. T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
  3043. Types.push_back(T);
  3044. ElaboratedTypes.InsertNode(T, InsertPos);
  3045. return QualType(T, 0);
  3046. }
  3047. QualType
  3048. ASTContext::getParenType(QualType InnerType) const {
  3049. llvm::FoldingSetNodeID ID;
  3050. ParenType::Profile(ID, InnerType);
  3051. void *InsertPos = nullptr;
  3052. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3053. if (T)
  3054. return QualType(T, 0);
  3055. QualType Canon = InnerType;
  3056. if (!Canon.isCanonical()) {
  3057. Canon = getCanonicalType(InnerType);
  3058. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3059. assert(!CheckT && "Paren canonical type broken");
  3060. (void)CheckT;
  3061. }
  3062. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  3063. Types.push_back(T);
  3064. ParenTypes.InsertNode(T, InsertPos);
  3065. return QualType(T, 0);
  3066. }
  3067. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  3068. NestedNameSpecifier *NNS,
  3069. const IdentifierInfo *Name,
  3070. QualType Canon) const {
  3071. if (Canon.isNull()) {
  3072. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3073. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3074. if (Keyword == ETK_None)
  3075. CanonKeyword = ETK_Typename;
  3076. if (CanonNNS != NNS || CanonKeyword != Keyword)
  3077. Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
  3078. }
  3079. llvm::FoldingSetNodeID ID;
  3080. DependentNameType::Profile(ID, Keyword, NNS, Name);
  3081. void *InsertPos = nullptr;
  3082. DependentNameType *T
  3083. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  3084. if (T)
  3085. return QualType(T, 0);
  3086. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  3087. Types.push_back(T);
  3088. DependentNameTypes.InsertNode(T, InsertPos);
  3089. return QualType(T, 0);
  3090. }
  3091. QualType
  3092. ASTContext::getDependentTemplateSpecializationType(
  3093. ElaboratedTypeKeyword Keyword,
  3094. NestedNameSpecifier *NNS,
  3095. const IdentifierInfo *Name,
  3096. const TemplateArgumentListInfo &Args) const {
  3097. // TODO: avoid this copy
  3098. SmallVector<TemplateArgument, 16> ArgCopy;
  3099. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  3100. ArgCopy.push_back(Args[I].getArgument());
  3101. return getDependentTemplateSpecializationType(Keyword, NNS, Name,
  3102. ArgCopy.size(),
  3103. ArgCopy.data());
  3104. }
  3105. QualType
  3106. ASTContext::getDependentTemplateSpecializationType(
  3107. ElaboratedTypeKeyword Keyword,
  3108. NestedNameSpecifier *NNS,
  3109. const IdentifierInfo *Name,
  3110. unsigned NumArgs,
  3111. const TemplateArgument *Args) const {
  3112. assert((!NNS || NNS->isDependent()) &&
  3113. "nested-name-specifier must be dependent");
  3114. llvm::FoldingSetNodeID ID;
  3115. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  3116. Name, NumArgs, Args);
  3117. void *InsertPos = nullptr;
  3118. DependentTemplateSpecializationType *T
  3119. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3120. if (T)
  3121. return QualType(T, 0);
  3122. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3123. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3124. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  3125. bool AnyNonCanonArgs = false;
  3126. SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
  3127. for (unsigned I = 0; I != NumArgs; ++I) {
  3128. CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
  3129. if (!CanonArgs[I].structurallyEquals(Args[I]))
  3130. AnyNonCanonArgs = true;
  3131. }
  3132. QualType Canon;
  3133. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  3134. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  3135. Name, NumArgs,
  3136. CanonArgs.data());
  3137. // Find the insert position again.
  3138. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3139. }
  3140. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  3141. sizeof(TemplateArgument) * NumArgs),
  3142. TypeAlignment);
  3143. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  3144. Name, NumArgs, Args, Canon);
  3145. Types.push_back(T);
  3146. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  3147. return QualType(T, 0);
  3148. }
  3149. QualType ASTContext::getPackExpansionType(QualType Pattern,
  3150. Optional<unsigned> NumExpansions) {
  3151. llvm::FoldingSetNodeID ID;
  3152. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  3153. assert(Pattern->containsUnexpandedParameterPack() &&
  3154. "Pack expansions must expand one or more parameter packs");
  3155. void *InsertPos = nullptr;
  3156. PackExpansionType *T
  3157. = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3158. if (T)
  3159. return QualType(T, 0);
  3160. QualType Canon;
  3161. if (!Pattern.isCanonical()) {
  3162. Canon = getCanonicalType(Pattern);
  3163. // The canonical type might not contain an unexpanded parameter pack, if it
  3164. // contains an alias template specialization which ignores one of its
  3165. // parameters.
  3166. if (Canon->containsUnexpandedParameterPack()) {
  3167. Canon = getPackExpansionType(Canon, NumExpansions);
  3168. // Find the insert position again, in case we inserted an element into
  3169. // PackExpansionTypes and invalidated our insert position.
  3170. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3171. }
  3172. }
  3173. T = new (*this, TypeAlignment)
  3174. PackExpansionType(Pattern, Canon, NumExpansions);
  3175. Types.push_back(T);
  3176. PackExpansionTypes.InsertNode(T, InsertPos);
  3177. return QualType(T, 0);
  3178. }
  3179. /// CmpProtocolNames - Comparison predicate for sorting protocols
  3180. /// alphabetically.
  3181. static int __cdecl CmpProtocolNames(ObjCProtocolDecl *const *LHS, // HLSL Change - __cdecl
  3182. ObjCProtocolDecl *const *RHS) {
  3183. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  3184. }
  3185. static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
  3186. unsigned NumProtocols) {
  3187. if (NumProtocols == 0) return true;
  3188. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  3189. return false;
  3190. for (unsigned i = 1; i != NumProtocols; ++i)
  3191. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  3192. Protocols[i]->getCanonicalDecl() != Protocols[i])
  3193. return false;
  3194. return true;
  3195. }
  3196. static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
  3197. unsigned &NumProtocols) {
  3198. ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
  3199. // Sort protocols, keyed by name.
  3200. llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
  3201. // Canonicalize.
  3202. for (unsigned I = 0, N = NumProtocols; I != N; ++I)
  3203. Protocols[I] = Protocols[I]->getCanonicalDecl();
  3204. // Remove duplicates.
  3205. ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
  3206. NumProtocols = ProtocolsEnd-Protocols;
  3207. }
  3208. QualType ASTContext::getObjCObjectType(QualType BaseType,
  3209. ObjCProtocolDecl * const *Protocols,
  3210. unsigned NumProtocols) const {
  3211. return getObjCObjectType(BaseType, { },
  3212. llvm::makeArrayRef(Protocols, NumProtocols),
  3213. /*isKindOf=*/false);
  3214. }
  3215. QualType ASTContext::getObjCObjectType(
  3216. QualType baseType,
  3217. ArrayRef<QualType> typeArgs,
  3218. ArrayRef<ObjCProtocolDecl *> protocols,
  3219. bool isKindOf) const {
  3220. // If the base type is an interface and there aren't any protocols or
  3221. // type arguments to add, then the interface type will do just fine.
  3222. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  3223. isa<ObjCInterfaceType>(baseType))
  3224. return baseType;
  3225. // Look in the folding set for an existing type.
  3226. llvm::FoldingSetNodeID ID;
  3227. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  3228. void *InsertPos = nullptr;
  3229. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  3230. return QualType(QT, 0);
  3231. // Determine the type arguments to be used for canonicalization,
  3232. // which may be explicitly specified here or written on the base
  3233. // type.
  3234. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  3235. if (effectiveTypeArgs.empty()) {
  3236. if (auto baseObject = baseType->getAs<ObjCObjectType>())
  3237. effectiveTypeArgs = baseObject->getTypeArgs();
  3238. }
  3239. // Build the canonical type, which has the canonical base type and a
  3240. // sorted-and-uniqued list of protocols and the type arguments
  3241. // canonicalized.
  3242. QualType canonical;
  3243. bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
  3244. effectiveTypeArgs.end(),
  3245. [&](QualType type) {
  3246. return type.isCanonical();
  3247. });
  3248. bool protocolsSorted = areSortedAndUniqued(protocols.data(),
  3249. protocols.size());
  3250. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  3251. // Determine the canonical type arguments.
  3252. ArrayRef<QualType> canonTypeArgs;
  3253. SmallVector<QualType, 4> canonTypeArgsVec;
  3254. if (!typeArgsAreCanonical) {
  3255. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  3256. for (auto typeArg : effectiveTypeArgs)
  3257. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  3258. canonTypeArgs = canonTypeArgsVec;
  3259. } else {
  3260. canonTypeArgs = effectiveTypeArgs;
  3261. }
  3262. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  3263. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  3264. if (!protocolsSorted) {
  3265. canonProtocolsVec.insert(canonProtocolsVec.begin(),
  3266. protocols.begin(),
  3267. protocols.end());
  3268. unsigned uniqueCount = protocols.size();
  3269. SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
  3270. canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
  3271. } else {
  3272. canonProtocols = protocols;
  3273. }
  3274. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  3275. canonProtocols, isKindOf);
  3276. // Regenerate InsertPos.
  3277. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  3278. }
  3279. unsigned size = sizeof(ObjCObjectTypeImpl);
  3280. size += typeArgs.size() * sizeof(QualType);
  3281. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  3282. void *mem = Allocate(size, TypeAlignment);
  3283. ObjCObjectTypeImpl *T =
  3284. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  3285. isKindOf);
  3286. Types.push_back(T);
  3287. ObjCObjectTypes.InsertNode(T, InsertPos);
  3288. return QualType(T, 0);
  3289. }
  3290. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  3291. /// protocol list adopt all protocols in QT's qualified-id protocol
  3292. /// list.
  3293. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  3294. ObjCInterfaceDecl *IC) {
  3295. if (!QT->isObjCQualifiedIdType())
  3296. return false;
  3297. if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
  3298. // If both the right and left sides have qualifiers.
  3299. for (auto *Proto : OPT->quals()) {
  3300. if (!IC->ClassImplementsProtocol(Proto, false))
  3301. return false;
  3302. }
  3303. return true;
  3304. }
  3305. return false;
  3306. }
  3307. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  3308. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  3309. /// of protocols.
  3310. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  3311. ObjCInterfaceDecl *IDecl) {
  3312. if (!QT->isObjCQualifiedIdType())
  3313. return false;
  3314. const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
  3315. if (!OPT)
  3316. return false;
  3317. if (!IDecl->hasDefinition())
  3318. return false;
  3319. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  3320. CollectInheritedProtocols(IDecl, InheritedProtocols);
  3321. if (InheritedProtocols.empty())
  3322. return false;
  3323. // Check that if every protocol in list of id<plist> conforms to a protcol
  3324. // of IDecl's, then bridge casting is ok.
  3325. bool Conforms = false;
  3326. for (auto *Proto : OPT->quals()) {
  3327. Conforms = false;
  3328. for (auto *PI : InheritedProtocols) {
  3329. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  3330. Conforms = true;
  3331. break;
  3332. }
  3333. }
  3334. if (!Conforms)
  3335. break;
  3336. }
  3337. if (Conforms)
  3338. return true;
  3339. for (auto *PI : InheritedProtocols) {
  3340. // If both the right and left sides have qualifiers.
  3341. bool Adopts = false;
  3342. for (auto *Proto : OPT->quals()) {
  3343. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  3344. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  3345. break;
  3346. }
  3347. if (!Adopts)
  3348. return false;
  3349. }
  3350. return true;
  3351. }
  3352. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  3353. /// the given object type.
  3354. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  3355. llvm::FoldingSetNodeID ID;
  3356. ObjCObjectPointerType::Profile(ID, ObjectT);
  3357. void *InsertPos = nullptr;
  3358. if (ObjCObjectPointerType *QT =
  3359. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  3360. return QualType(QT, 0);
  3361. // Find the canonical object type.
  3362. QualType Canonical;
  3363. if (!ObjectT.isCanonical()) {
  3364. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  3365. // Regenerate InsertPos.
  3366. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  3367. }
  3368. // No match.
  3369. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  3370. ObjCObjectPointerType *QType =
  3371. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  3372. Types.push_back(QType);
  3373. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  3374. return QualType(QType, 0);
  3375. }
  3376. /// getObjCInterfaceType - Return the unique reference to the type for the
  3377. /// specified ObjC interface decl. The list of protocols is optional.
  3378. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  3379. ObjCInterfaceDecl *PrevDecl) const {
  3380. if (Decl->TypeForDecl)
  3381. return QualType(Decl->TypeForDecl, 0);
  3382. if (PrevDecl) {
  3383. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  3384. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  3385. return QualType(PrevDecl->TypeForDecl, 0);
  3386. }
  3387. // Prefer the definition, if there is one.
  3388. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  3389. Decl = Def;
  3390. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  3391. ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
  3392. Decl->TypeForDecl = T;
  3393. Types.push_back(T);
  3394. return QualType(T, 0);
  3395. }
  3396. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  3397. /// TypeOfExprType AST's (since expression's are never shared). For example,
  3398. /// multiple declarations that refer to "typeof(x)" all contain different
  3399. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  3400. /// on canonical type's (which are always unique).
  3401. QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
  3402. TypeOfExprType *toe;
  3403. if (tofExpr->isTypeDependent()) {
  3404. llvm::FoldingSetNodeID ID;
  3405. DependentTypeOfExprType::Profile(ID, *this, tofExpr);
  3406. void *InsertPos = nullptr;
  3407. DependentTypeOfExprType *Canon
  3408. = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  3409. if (Canon) {
  3410. // We already have a "canonical" version of an identical, dependent
  3411. // typeof(expr) type. Use that as our canonical type.
  3412. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
  3413. QualType((TypeOfExprType*)Canon, 0));
  3414. } else {
  3415. // Build a new, canonical typeof(expr) type.
  3416. Canon
  3417. = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
  3418. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  3419. toe = Canon;
  3420. }
  3421. } else {
  3422. QualType Canonical = getCanonicalType(tofExpr->getType());
  3423. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
  3424. }
  3425. Types.push_back(toe);
  3426. return QualType(toe, 0);
  3427. }
  3428. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  3429. /// TypeOfType nodes. The only motivation to unique these nodes would be
  3430. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  3431. /// an issue. This doesn't affect the type checker, since it operates
  3432. /// on canonical types (which are always unique).
  3433. QualType ASTContext::getTypeOfType(QualType tofType) const {
  3434. QualType Canonical = getCanonicalType(tofType);
  3435. TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
  3436. Types.push_back(tot);
  3437. return QualType(tot, 0);
  3438. }
  3439. /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
  3440. /// nodes. This would never be helpful, since each such type has its own
  3441. /// expression, and would not give a significant memory saving, since there
  3442. /// is an Expr tree under each such type.
  3443. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  3444. DecltypeType *dt;
  3445. // C++11 [temp.type]p2:
  3446. // If an expression e involves a template parameter, decltype(e) denotes a
  3447. // unique dependent type. Two such decltype-specifiers refer to the same
  3448. // type only if their expressions are equivalent (14.5.6.1).
  3449. if (e->isInstantiationDependent()) {
  3450. llvm::FoldingSetNodeID ID;
  3451. DependentDecltypeType::Profile(ID, *this, e);
  3452. void *InsertPos = nullptr;
  3453. DependentDecltypeType *Canon
  3454. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3455. if (!Canon) {
  3456. // Build a new, canonical typeof(expr) type.
  3457. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  3458. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  3459. }
  3460. dt = new (*this, TypeAlignment)
  3461. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  3462. } else {
  3463. dt = new (*this, TypeAlignment)
  3464. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  3465. }
  3466. Types.push_back(dt);
  3467. return QualType(dt, 0);
  3468. }
  3469. /// getUnaryTransformationType - We don't unique these, since the memory
  3470. /// savings are minimal and these are rare.
  3471. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  3472. QualType UnderlyingType,
  3473. UnaryTransformType::UTTKind Kind)
  3474. const {
  3475. UnaryTransformType *Ty =
  3476. new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
  3477. Kind,
  3478. UnderlyingType->isDependentType() ?
  3479. QualType() : getCanonicalType(UnderlyingType));
  3480. Types.push_back(Ty);
  3481. return QualType(Ty, 0);
  3482. }
  3483. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  3484. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  3485. /// canonical deduced-but-dependent 'auto' type.
  3486. QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
  3487. bool IsDependent) const {
  3488. if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
  3489. return getAutoDeductType();
  3490. // Look in the folding set for an existing type.
  3491. void *InsertPos = nullptr;
  3492. llvm::FoldingSetNodeID ID;
  3493. AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
  3494. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3495. return QualType(AT, 0);
  3496. AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
  3497. IsDecltypeAuto,
  3498. IsDependent);
  3499. Types.push_back(AT);
  3500. if (InsertPos)
  3501. AutoTypes.InsertNode(AT, InsertPos);
  3502. return QualType(AT, 0);
  3503. }
  3504. /// getAtomicType - Return the uniqued reference to the atomic type for
  3505. /// the given value type.
  3506. QualType ASTContext::getAtomicType(QualType T) const {
  3507. // Unique pointers, to guarantee there is only one pointer of a particular
  3508. // structure.
  3509. llvm::FoldingSetNodeID ID;
  3510. AtomicType::Profile(ID, T);
  3511. void *InsertPos = nullptr;
  3512. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  3513. return QualType(AT, 0);
  3514. // If the atomic value type isn't canonical, this won't be a canonical type
  3515. // either, so fill in the canonical type field.
  3516. QualType Canonical;
  3517. if (!T.isCanonical()) {
  3518. Canonical = getAtomicType(getCanonicalType(T));
  3519. // Get the new insert position for the node we care about.
  3520. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  3521. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3522. }
  3523. AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  3524. Types.push_back(New);
  3525. AtomicTypes.InsertNode(New, InsertPos);
  3526. return QualType(New, 0);
  3527. }
  3528. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  3529. QualType ASTContext::getAutoDeductType() const {
  3530. if (AutoDeductTy.isNull())
  3531. AutoDeductTy = QualType(
  3532. new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
  3533. /*dependent*/false),
  3534. 0);
  3535. return AutoDeductTy;
  3536. }
  3537. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  3538. QualType ASTContext::getAutoRRefDeductType() const {
  3539. if (AutoRRefDeductTy.isNull())
  3540. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  3541. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  3542. return AutoRRefDeductTy;
  3543. }
  3544. /// getTagDeclType - Return the unique reference to the type for the
  3545. /// specified TagDecl (struct/union/class/enum) decl.
  3546. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  3547. assert (Decl);
  3548. // FIXME: What is the design on getTagDeclType when it requires casting
  3549. // away const? mutable?
  3550. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  3551. }
  3552. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  3553. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  3554. /// needs to agree with the definition in <stddef.h>.
  3555. CanQualType ASTContext::getSizeType() const {
  3556. return getFromTargetType(Target->getSizeType());
  3557. }
  3558. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  3559. CanQualType ASTContext::getIntMaxType() const {
  3560. return getFromTargetType(Target->getIntMaxType());
  3561. }
  3562. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  3563. CanQualType ASTContext::getUIntMaxType() const {
  3564. return getFromTargetType(Target->getUIntMaxType());
  3565. }
  3566. /// getSignedWCharType - Return the type of "signed wchar_t".
  3567. /// Used when in C++, as a GCC extension.
  3568. QualType ASTContext::getSignedWCharType() const {
  3569. // FIXME: derive from "Target" ?
  3570. return WCharTy;
  3571. }
  3572. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  3573. /// Used when in C++, as a GCC extension.
  3574. QualType ASTContext::getUnsignedWCharType() const {
  3575. // FIXME: derive from "Target" ?
  3576. return UnsignedIntTy;
  3577. }
  3578. QualType ASTContext::getIntPtrType() const {
  3579. return getFromTargetType(Target->getIntPtrType());
  3580. }
  3581. QualType ASTContext::getUIntPtrType() const {
  3582. return getCorrespondingUnsignedType(getIntPtrType());
  3583. }
  3584. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  3585. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  3586. QualType ASTContext::getPointerDiffType() const {
  3587. return getFromTargetType(Target->getPtrDiffType(0));
  3588. }
  3589. /// \brief Return the unique type for "pid_t" defined in
  3590. /// <sys/types.h>. We need this to compute the correct type for vfork().
  3591. QualType ASTContext::getProcessIDType() const {
  3592. return getFromTargetType(Target->getProcessIDType());
  3593. }
  3594. //===----------------------------------------------------------------------===//
  3595. // Type Operators
  3596. //===----------------------------------------------------------------------===//
  3597. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  3598. // Push qualifiers into arrays, and then discard any remaining
  3599. // qualifiers.
  3600. T = getCanonicalType(T);
  3601. T = getVariableArrayDecayedType(T);
  3602. const Type *Ty = T.getTypePtr();
  3603. QualType Result;
  3604. if (isa<ArrayType>(Ty)) {
  3605. // HLSL Change Starts
  3606. if (getLangOpts().HLSL)
  3607. Result = QualType(Ty, 0);
  3608. else
  3609. // HLSL Change Ends
  3610. Result = getArrayDecayedType(QualType(Ty, 0));
  3611. } else if (isa<FunctionType>(Ty)) {
  3612. Result = getPointerType(QualType(Ty, 0));
  3613. } else {
  3614. Result = QualType(Ty, 0);
  3615. }
  3616. return CanQualType::CreateUnsafe(Result);
  3617. }
  3618. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  3619. Qualifiers &quals) {
  3620. SplitQualType splitType = type.getSplitUnqualifiedType();
  3621. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  3622. // the unqualified desugared type and then drops it on the floor.
  3623. // We then have to strip that sugar back off with
  3624. // getUnqualifiedDesugaredType(), which is silly.
  3625. const ArrayType *AT =
  3626. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  3627. // If we don't have an array, just use the results in splitType.
  3628. if (!AT) {
  3629. quals = splitType.Quals;
  3630. return QualType(splitType.Ty, 0);
  3631. }
  3632. // Otherwise, recurse on the array's element type.
  3633. QualType elementType = AT->getElementType();
  3634. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  3635. // If that didn't change the element type, AT has no qualifiers, so we
  3636. // can just use the results in splitType.
  3637. if (elementType == unqualElementType) {
  3638. assert(quals.empty()); // from the recursive call
  3639. quals = splitType.Quals;
  3640. return QualType(splitType.Ty, 0);
  3641. }
  3642. // Otherwise, add in the qualifiers from the outermost type, then
  3643. // build the type back up.
  3644. quals.addConsistentQualifiers(splitType.Quals);
  3645. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
  3646. return getConstantArrayType(unqualElementType, CAT->getSize(),
  3647. CAT->getSizeModifier(), 0);
  3648. }
  3649. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  3650. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  3651. }
  3652. if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
  3653. return getVariableArrayType(unqualElementType,
  3654. VAT->getSizeExpr(),
  3655. VAT->getSizeModifier(),
  3656. VAT->getIndexTypeCVRQualifiers(),
  3657. VAT->getBracketsRange());
  3658. }
  3659. const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
  3660. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  3661. DSAT->getSizeModifier(), 0,
  3662. SourceRange());
  3663. }
  3664. /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
  3665. /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
  3666. /// they point to and return true. If T1 and T2 aren't pointer types
  3667. /// or pointer-to-member types, or if they are not similar at this
  3668. /// level, returns false and leaves T1 and T2 unchanged. Top-level
  3669. /// qualifiers on T1 and T2 are ignored. This function will typically
  3670. /// be called in a loop that successively "unwraps" pointer and
  3671. /// pointer-to-member types to compare them at each level.
  3672. bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
  3673. const PointerType *T1PtrType = T1->getAs<PointerType>(),
  3674. *T2PtrType = T2->getAs<PointerType>();
  3675. if (T1PtrType && T2PtrType) {
  3676. T1 = T1PtrType->getPointeeType();
  3677. T2 = T2PtrType->getPointeeType();
  3678. return true;
  3679. }
  3680. const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
  3681. *T2MPType = T2->getAs<MemberPointerType>();
  3682. if (T1MPType && T2MPType &&
  3683. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  3684. QualType(T2MPType->getClass(), 0))) {
  3685. T1 = T1MPType->getPointeeType();
  3686. T2 = T2MPType->getPointeeType();
  3687. return true;
  3688. }
  3689. if (getLangOpts().ObjC1) {
  3690. const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
  3691. *T2OPType = T2->getAs<ObjCObjectPointerType>();
  3692. if (T1OPType && T2OPType) {
  3693. T1 = T1OPType->getPointeeType();
  3694. T2 = T2OPType->getPointeeType();
  3695. return true;
  3696. }
  3697. }
  3698. // FIXME: Block pointers, too?
  3699. return false;
  3700. }
  3701. DeclarationNameInfo
  3702. ASTContext::getNameForTemplate(TemplateName Name,
  3703. SourceLocation NameLoc) const {
  3704. switch (Name.getKind()) {
  3705. case TemplateName::QualifiedTemplate:
  3706. case TemplateName::Template:
  3707. // DNInfo work in progress: CHECKME: what about DNLoc?
  3708. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  3709. NameLoc);
  3710. case TemplateName::OverloadedTemplate: {
  3711. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  3712. // DNInfo work in progress: CHECKME: what about DNLoc?
  3713. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  3714. }
  3715. case TemplateName::DependentTemplate: {
  3716. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  3717. DeclarationName DName;
  3718. if (DTN->isIdentifier()) {
  3719. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  3720. return DeclarationNameInfo(DName, NameLoc);
  3721. } else {
  3722. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  3723. // DNInfo work in progress: FIXME: source locations?
  3724. DeclarationNameLoc DNLoc;
  3725. DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
  3726. DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
  3727. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  3728. }
  3729. }
  3730. case TemplateName::SubstTemplateTemplateParm: {
  3731. SubstTemplateTemplateParmStorage *subst
  3732. = Name.getAsSubstTemplateTemplateParm();
  3733. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  3734. NameLoc);
  3735. }
  3736. case TemplateName::SubstTemplateTemplateParmPack: {
  3737. SubstTemplateTemplateParmPackStorage *subst
  3738. = Name.getAsSubstTemplateTemplateParmPack();
  3739. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  3740. NameLoc);
  3741. }
  3742. }
  3743. llvm_unreachable("bad template name kind!");
  3744. }
  3745. TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
  3746. switch (Name.getKind()) {
  3747. case TemplateName::QualifiedTemplate:
  3748. case TemplateName::Template: {
  3749. TemplateDecl *Template = Name.getAsTemplateDecl();
  3750. if (TemplateTemplateParmDecl *TTP
  3751. = dyn_cast<TemplateTemplateParmDecl>(Template))
  3752. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  3753. // The canonical template name is the canonical template declaration.
  3754. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  3755. }
  3756. case TemplateName::OverloadedTemplate:
  3757. llvm_unreachable("cannot canonicalize overloaded template");
  3758. case TemplateName::DependentTemplate: {
  3759. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  3760. assert(DTN && "Non-dependent template names must refer to template decls.");
  3761. return DTN->CanonicalTemplateName;
  3762. }
  3763. case TemplateName::SubstTemplateTemplateParm: {
  3764. SubstTemplateTemplateParmStorage *subst
  3765. = Name.getAsSubstTemplateTemplateParm();
  3766. return getCanonicalTemplateName(subst->getReplacement());
  3767. }
  3768. case TemplateName::SubstTemplateTemplateParmPack: {
  3769. SubstTemplateTemplateParmPackStorage *subst
  3770. = Name.getAsSubstTemplateTemplateParmPack();
  3771. TemplateTemplateParmDecl *canonParameter
  3772. = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
  3773. TemplateArgument canonArgPack
  3774. = getCanonicalTemplateArgument(subst->getArgumentPack());
  3775. return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
  3776. }
  3777. }
  3778. llvm_unreachable("bad template name!");
  3779. }
  3780. bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
  3781. X = getCanonicalTemplateName(X);
  3782. Y = getCanonicalTemplateName(Y);
  3783. return X.getAsVoidPointer() == Y.getAsVoidPointer();
  3784. }
  3785. TemplateArgument
  3786. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  3787. switch (Arg.getKind()) {
  3788. case TemplateArgument::Null:
  3789. return Arg;
  3790. case TemplateArgument::Expression:
  3791. return Arg;
  3792. case TemplateArgument::Declaration: {
  3793. ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  3794. return TemplateArgument(D, Arg.getParamTypeForDecl());
  3795. }
  3796. case TemplateArgument::NullPtr:
  3797. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  3798. /*isNullPtr*/true);
  3799. case TemplateArgument::Template:
  3800. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  3801. case TemplateArgument::TemplateExpansion:
  3802. return TemplateArgument(getCanonicalTemplateName(
  3803. Arg.getAsTemplateOrTemplatePattern()),
  3804. Arg.getNumTemplateExpansions());
  3805. case TemplateArgument::Integral:
  3806. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  3807. case TemplateArgument::Type:
  3808. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  3809. case TemplateArgument::Pack: {
  3810. if (Arg.pack_size() == 0)
  3811. return Arg;
  3812. TemplateArgument *CanonArgs
  3813. = new (*this) TemplateArgument[Arg.pack_size()];
  3814. unsigned Idx = 0;
  3815. for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
  3816. AEnd = Arg.pack_end();
  3817. A != AEnd; (void)++A, ++Idx)
  3818. CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
  3819. return TemplateArgument(CanonArgs, Arg.pack_size());
  3820. }
  3821. }
  3822. // Silence GCC warning
  3823. llvm_unreachable("Unhandled template argument kind");
  3824. }
  3825. NestedNameSpecifier *
  3826. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  3827. if (!NNS)
  3828. return nullptr;
  3829. switch (NNS->getKind()) {
  3830. case NestedNameSpecifier::Identifier:
  3831. // Canonicalize the prefix but keep the identifier the same.
  3832. return NestedNameSpecifier::Create(*this,
  3833. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  3834. NNS->getAsIdentifier());
  3835. case NestedNameSpecifier::Namespace:
  3836. // A namespace is canonical; build a nested-name-specifier with
  3837. // this namespace and no prefix.
  3838. return NestedNameSpecifier::Create(*this, nullptr,
  3839. NNS->getAsNamespace()->getOriginalNamespace());
  3840. case NestedNameSpecifier::NamespaceAlias:
  3841. // A namespace is canonical; build a nested-name-specifier with
  3842. // this namespace and no prefix.
  3843. return NestedNameSpecifier::Create(*this, nullptr,
  3844. NNS->getAsNamespaceAlias()->getNamespace()
  3845. ->getOriginalNamespace());
  3846. case NestedNameSpecifier::TypeSpec:
  3847. case NestedNameSpecifier::TypeSpecWithTemplate: {
  3848. QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
  3849. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  3850. // break it apart into its prefix and identifier, then reconsititute those
  3851. // as the canonical nested-name-specifier. This is required to canonicalize
  3852. // a dependent nested-name-specifier involving typedefs of dependent-name
  3853. // types, e.g.,
  3854. // typedef typename T::type T1;
  3855. // typedef typename T1::type T2;
  3856. if (const DependentNameType *DNT = T->getAs<DependentNameType>())
  3857. return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
  3858. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  3859. // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
  3860. // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
  3861. // first place?
  3862. return NestedNameSpecifier::Create(*this, nullptr, false,
  3863. const_cast<Type *>(T.getTypePtr()));
  3864. }
  3865. case NestedNameSpecifier::Global:
  3866. case NestedNameSpecifier::Super:
  3867. // The global specifier and __super specifer are canonical and unique.
  3868. return NNS;
  3869. }
  3870. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  3871. }
  3872. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  3873. // Handle the non-qualified case efficiently.
  3874. if (!T.hasLocalQualifiers()) {
  3875. // Handle the common positive case fast.
  3876. if (const ArrayType *AT = dyn_cast<ArrayType>(T))
  3877. return AT;
  3878. }
  3879. // Handle the common negative case fast.
  3880. if (!isa<ArrayType>(T.getCanonicalType()))
  3881. return nullptr;
  3882. // Apply any qualifiers from the array type to the element type. This
  3883. // implements C99 6.7.3p8: "If the specification of an array type includes
  3884. // any type qualifiers, the element type is so qualified, not the array type."
  3885. // If we get here, we either have type qualifiers on the type, or we have
  3886. // sugar such as a typedef in the way. If we have type qualifiers on the type
  3887. // we must propagate them down into the element type.
  3888. SplitQualType split = T.getSplitDesugaredType();
  3889. Qualifiers qs = split.Quals;
  3890. // If we have a simple case, just return now.
  3891. const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
  3892. if (!ATy || qs.empty())
  3893. return ATy;
  3894. // Otherwise, we have an array and we have qualifiers on it. Push the
  3895. // qualifiers into the array element type and return a new array type.
  3896. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  3897. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
  3898. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  3899. CAT->getSizeModifier(),
  3900. CAT->getIndexTypeCVRQualifiers()));
  3901. if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
  3902. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  3903. IAT->getSizeModifier(),
  3904. IAT->getIndexTypeCVRQualifiers()));
  3905. if (const DependentSizedArrayType *DSAT
  3906. = dyn_cast<DependentSizedArrayType>(ATy))
  3907. return cast<ArrayType>(
  3908. getDependentSizedArrayType(NewEltTy,
  3909. DSAT->getSizeExpr(),
  3910. DSAT->getSizeModifier(),
  3911. DSAT->getIndexTypeCVRQualifiers(),
  3912. DSAT->getBracketsRange()));
  3913. const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
  3914. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  3915. VAT->getSizeExpr(),
  3916. VAT->getSizeModifier(),
  3917. VAT->getIndexTypeCVRQualifiers(),
  3918. VAT->getBracketsRange()));
  3919. }
  3920. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  3921. if (T->isArrayType() || T->isFunctionType())
  3922. return getDecayedType(T);
  3923. return T;
  3924. }
  3925. QualType ASTContext::getSignatureParameterType(QualType T) const {
  3926. T = getVariableArrayDecayedType(T);
  3927. T = getAdjustedParameterType(T);
  3928. return T.getUnqualifiedType();
  3929. }
  3930. QualType ASTContext::getExceptionObjectType(QualType T) const {
  3931. // C++ [except.throw]p3:
  3932. // A throw-expression initializes a temporary object, called the exception
  3933. // object, the type of which is determined by removing any top-level
  3934. // cv-qualifiers from the static type of the operand of throw and adjusting
  3935. // the type from "array of T" or "function returning T" to "pointer to T"
  3936. // or "pointer to function returning T", [...]
  3937. T = getVariableArrayDecayedType(T);
  3938. if (T->isArrayType() || T->isFunctionType())
  3939. T = getDecayedType(T);
  3940. return T.getUnqualifiedType();
  3941. }
  3942. /// getArrayDecayedType - Return the properly qualified result of decaying the
  3943. /// specified array type to a pointer. This operation is non-trivial when
  3944. /// handling typedefs etc. The canonical type of "T" must be an array type,
  3945. /// this returns a pointer to a properly qualified element of the array.
  3946. ///
  3947. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  3948. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  3949. // Get the element type with 'getAsArrayType' so that we don't lose any
  3950. // typedefs in the element type of the array. This also handles propagation
  3951. // of type qualifiers from the array type into the element type if present
  3952. // (C99 6.7.3p8).
  3953. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  3954. assert(PrettyArrayType && "Not an array type!");
  3955. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  3956. // int x[restrict 4] -> int *restrict
  3957. return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
  3958. }
  3959. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  3960. return getBaseElementType(array->getElementType());
  3961. }
  3962. QualType ASTContext::getBaseElementType(QualType type) const {
  3963. Qualifiers qs;
  3964. while (true) {
  3965. SplitQualType split = type.getSplitDesugaredType();
  3966. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  3967. if (!array) break;
  3968. type = array->getElementType();
  3969. qs.addConsistentQualifiers(split.Quals);
  3970. }
  3971. return getQualifiedType(type, qs);
  3972. }
  3973. /// getConstantArrayElementCount - Returns number of constant array elements.
  3974. uint64_t
  3975. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  3976. uint64_t ElementCount = 1;
  3977. do {
  3978. ElementCount *= CA->getSize().getZExtValue();
  3979. CA = dyn_cast_or_null<ConstantArrayType>(
  3980. CA->getElementType()->getAsArrayTypeUnsafe());
  3981. } while (CA);
  3982. return ElementCount;
  3983. }
  3984. /// getFloatingRank - Return a relative rank for floating point types.
  3985. /// This routine will assert if passed a built-in type that isn't a float.
  3986. static FloatingRank getFloatingRank(QualType T) {
  3987. if (const ComplexType *CT = T->getAs<ComplexType>())
  3988. return getFloatingRank(CT->getElementType());
  3989. assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
  3990. switch (T->getAs<BuiltinType>()->getKind()) {
  3991. default: llvm_unreachable("getFloatingRank(): not a floating type");
  3992. case BuiltinType::Half: return HalfRank;
  3993. case BuiltinType::Float: return FloatRank;
  3994. case BuiltinType::Double: return DoubleRank;
  3995. case BuiltinType::LongDouble: return LongDoubleRank;
  3996. // HLSL Changes begin
  3997. case BuiltinType::Min10Float: return Min10FloatRank;
  3998. case BuiltinType::Min16Float: return Min16FloatRank;
  3999. case BuiltinType::HalfFloat: return HalfFloatRank;
  4000. case BuiltinType::LitFloat: return LitFloatRank;
  4001. // HLSL Changes end
  4002. }
  4003. }
  4004. /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
  4005. /// point or a complex type (based on typeDomain/typeSize).
  4006. /// 'typeDomain' is a real floating point or complex type.
  4007. /// 'typeSize' is a real floating point or complex type.
  4008. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
  4009. QualType Domain) const {
  4010. FloatingRank EltRank = getFloatingRank(Size);
  4011. if (Domain->isComplexType()) {
  4012. switch (EltRank) {
  4013. case FloatRank: return FloatComplexTy;
  4014. case DoubleRank: return DoubleComplexTy;
  4015. case LongDoubleRank: return LongDoubleComplexTy;
  4016. // HLSL Changes begin
  4017. case HalfRank:
  4018. case LitFloatRank:
  4019. case Min10FloatRank:
  4020. case Min16FloatRank:
  4021. case HalfFloatRank:
  4022. llvm_unreachable("Complex type is not supported in HLSL.");
  4023. // HLSL Changes end
  4024. }
  4025. }
  4026. assert(Domain->isRealFloatingType() && "Unknown domain!");
  4027. switch (EltRank) {
  4028. case LitFloatRank: return LitFloatTy; // HLSL Change
  4029. case Min10FloatRank: return Min10FloatTy; // HLSL Change
  4030. case HalfRank: return HalfTy;
  4031. case FloatRank: return FloatTy;
  4032. case DoubleRank: return DoubleTy;
  4033. case LongDoubleRank: return LongDoubleTy;
  4034. }
  4035. llvm_unreachable("getFloatingRank(): illegal value for rank");
  4036. }
  4037. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  4038. /// point types, ignoring the domain of the type (i.e. 'double' ==
  4039. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4040. /// LHS < RHS, return -1.
  4041. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  4042. FloatingRank LHSR = getFloatingRank(LHS);
  4043. FloatingRank RHSR = getFloatingRank(RHS);
  4044. if (LHSR == RHSR)
  4045. return 0;
  4046. if (LHSR > RHSR)
  4047. return 1;
  4048. return -1;
  4049. }
  4050. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  4051. /// routine will assert if passed a built-in type that isn't an integer or enum,
  4052. /// or if it is not canonicalized.
  4053. unsigned ASTContext::getIntegerRank(const Type *T) const {
  4054. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  4055. switch (cast<BuiltinType>(T)->getKind()) {
  4056. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  4057. case BuiltinType::Bool:
  4058. return 1 + (getIntWidth(BoolTy) << 3);
  4059. case BuiltinType::Char_S:
  4060. case BuiltinType::Char_U:
  4061. case BuiltinType::SChar:
  4062. case BuiltinType::UChar:
  4063. return 2 + (getIntWidth(CharTy) << 3);
  4064. case BuiltinType::Short:
  4065. case BuiltinType::UShort:
  4066. return 3 + (getIntWidth(ShortTy) << 3);
  4067. case BuiltinType::LitInt: // HLSL Change
  4068. case BuiltinType::Int:
  4069. case BuiltinType::UInt:
  4070. return 4 + (getIntWidth(IntTy) << 3);
  4071. case BuiltinType::Long:
  4072. case BuiltinType::ULong:
  4073. return 5 + (getIntWidth(LongTy) << 3);
  4074. case BuiltinType::LongLong:
  4075. case BuiltinType::ULongLong:
  4076. return 6 + (getIntWidth(LongLongTy) << 3);
  4077. case BuiltinType::Int128:
  4078. case BuiltinType::UInt128:
  4079. return 7 + (getIntWidth(Int128Ty) << 3);
  4080. }
  4081. }
  4082. /// \brief Whether this is a promotable bitfield reference according
  4083. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  4084. ///
  4085. /// \returns the type this bit-field will promote to, or NULL if no
  4086. /// promotion occurs.
  4087. QualType ASTContext::isPromotableBitField(Expr *E) const {
  4088. if (E->isTypeDependent() || E->isValueDependent())
  4089. return QualType();
  4090. // FIXME: We should not do this unless E->refersToBitField() is true. This
  4091. // matters in C where getSourceBitField() will find bit-fields for various
  4092. // cases where the source expression is not a bit-field designator.
  4093. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  4094. if (!Field)
  4095. return QualType();
  4096. QualType FT = Field->getType();
  4097. uint64_t BitWidth = Field->getBitWidthValue(*this);
  4098. uint64_t IntSize = getTypeSize(IntTy);
  4099. // C++ [conv.prom]p5:
  4100. // A prvalue for an integral bit-field can be converted to a prvalue of type
  4101. // int if int can represent all the values of the bit-field; otherwise, it
  4102. // can be converted to unsigned int if unsigned int can represent all the
  4103. // values of the bit-field. If the bit-field is larger yet, no integral
  4104. // promotion applies to it.
  4105. // C11 6.3.1.1/2:
  4106. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  4107. // If an int can represent all values of the original type (as restricted by
  4108. // the width, for a bit-field), the value is converted to an int; otherwise,
  4109. // it is converted to an unsigned int.
  4110. //
  4111. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  4112. // We perform that promotion here to match GCC and C++.
  4113. if (BitWidth < IntSize)
  4114. return IntTy;
  4115. if (BitWidth == IntSize)
  4116. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  4117. // Types bigger than int are not subject to promotions, and therefore act
  4118. // like the base type. GCC has some weird bugs in this area that we
  4119. // deliberately do not follow (GCC follows a pre-standard resolution to
  4120. // C's DR315 which treats bit-width as being part of the type, and this leaks
  4121. // into their semantics in some cases).
  4122. return QualType();
  4123. }
  4124. /// getPromotedIntegerType - Returns the type that Promotable will
  4125. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  4126. /// integer type.
  4127. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  4128. assert(!Promotable.isNull());
  4129. assert(Promotable->isPromotableIntegerType());
  4130. if (const EnumType *ET = Promotable->getAs<EnumType>())
  4131. return ET->getDecl()->getPromotionType();
  4132. if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
  4133. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  4134. // (3.9.1) can be converted to a prvalue of the first of the following
  4135. // types that can represent all the values of its underlying type:
  4136. // int, unsigned int, long int, unsigned long int, long long int, or
  4137. // unsigned long long int [...]
  4138. // FIXME: Is there some better way to compute this?
  4139. if (BT->getKind() == BuiltinType::WChar_S ||
  4140. BT->getKind() == BuiltinType::WChar_U ||
  4141. BT->getKind() == BuiltinType::Char16 ||
  4142. BT->getKind() == BuiltinType::Char32) {
  4143. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  4144. uint64_t FromSize = getTypeSize(BT);
  4145. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  4146. LongLongTy, UnsignedLongLongTy };
  4147. for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
  4148. uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
  4149. if (FromSize < ToSize ||
  4150. (FromSize == ToSize &&
  4151. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
  4152. return PromoteTypes[Idx];
  4153. }
  4154. llvm_unreachable("char type should fit into long long");
  4155. }
  4156. }
  4157. // At this point, we should have a signed or unsigned integer type.
  4158. if (Promotable->isSignedIntegerType())
  4159. return IntTy;
  4160. uint64_t PromotableSize = getIntWidth(Promotable);
  4161. uint64_t IntSize = getIntWidth(IntTy);
  4162. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  4163. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  4164. }
  4165. /// \brief Recurses in pointer/array types until it finds an objc retainable
  4166. /// type and returns its ownership.
  4167. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  4168. while (!T.isNull()) {
  4169. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  4170. return T.getObjCLifetime();
  4171. if (T->isArrayType())
  4172. T = getBaseElementType(T);
  4173. else if (const PointerType *PT = T->getAs<PointerType>())
  4174. T = PT->getPointeeType();
  4175. else if (const ReferenceType *RT = T->getAs<ReferenceType>())
  4176. T = RT->getPointeeType();
  4177. else
  4178. break;
  4179. }
  4180. return Qualifiers::OCL_None;
  4181. }
  4182. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  4183. // Incomplete enum types are not treated as integer types.
  4184. // FIXME: In C++, enum types are never integer types.
  4185. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  4186. return ET->getDecl()->getIntegerType().getTypePtr();
  4187. return nullptr;
  4188. }
  4189. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  4190. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4191. /// LHS < RHS, return -1.
  4192. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  4193. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  4194. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  4195. // Unwrap enums to their underlying type.
  4196. if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
  4197. LHSC = getIntegerTypeForEnum(ET);
  4198. if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
  4199. RHSC = getIntegerTypeForEnum(ET);
  4200. if (LHSC == RHSC) return 0;
  4201. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  4202. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  4203. unsigned LHSRank = getIntegerRank(LHSC);
  4204. unsigned RHSRank = getIntegerRank(RHSC);
  4205. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  4206. if (LHSRank == RHSRank) return 0;
  4207. return LHSRank > RHSRank ? 1 : -1;
  4208. }
  4209. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  4210. if (LHSUnsigned) {
  4211. // If the unsigned [LHS] type is larger, return it.
  4212. if (LHSRank >= RHSRank)
  4213. return 1;
  4214. // If the signed type can represent all values of the unsigned type, it
  4215. // wins. Because we are dealing with 2's complement and types that are
  4216. // powers of two larger than each other, this is always safe.
  4217. return -1;
  4218. }
  4219. // If the unsigned [RHS] type is larger, return it.
  4220. if (RHSRank >= LHSRank)
  4221. return -1;
  4222. // If the signed type can represent all values of the unsigned type, it
  4223. // wins. Because we are dealing with 2's complement and types that are
  4224. // powers of two larger than each other, this is always safe.
  4225. return 1;
  4226. }
  4227. // getCFConstantStringType - Return the type used for constant CFStrings.
  4228. QualType ASTContext::getCFConstantStringType() const {
  4229. if (!CFConstantStringTypeDecl) {
  4230. CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
  4231. CFConstantStringTypeDecl->startDefinition();
  4232. QualType FieldTypes[4];
  4233. // const int *isa;
  4234. FieldTypes[0] = getPointerType(IntTy.withConst());
  4235. // int flags;
  4236. FieldTypes[1] = IntTy;
  4237. // const char *str;
  4238. FieldTypes[2] = getPointerType(CharTy.withConst());
  4239. // long length;
  4240. FieldTypes[3] = LongTy;
  4241. // Create fields
  4242. for (unsigned i = 0; i < 4; ++i) {
  4243. FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
  4244. SourceLocation(),
  4245. SourceLocation(), nullptr,
  4246. FieldTypes[i], /*TInfo=*/nullptr,
  4247. /*BitWidth=*/nullptr,
  4248. /*Mutable=*/false,
  4249. ICIS_NoInit);
  4250. Field->setAccess(AS_public);
  4251. CFConstantStringTypeDecl->addDecl(Field);
  4252. }
  4253. CFConstantStringTypeDecl->completeDefinition();
  4254. }
  4255. return getTagDeclType(CFConstantStringTypeDecl);
  4256. }
  4257. QualType ASTContext::getObjCSuperType() const {
  4258. if (ObjCSuperType.isNull()) {
  4259. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  4260. TUDecl->addDecl(ObjCSuperTypeDecl);
  4261. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  4262. }
  4263. return ObjCSuperType;
  4264. }
  4265. void ASTContext::setCFConstantStringType(QualType T) {
  4266. const RecordType *Rec = T->getAs<RecordType>();
  4267. assert(Rec && "Invalid CFConstantStringType");
  4268. CFConstantStringTypeDecl = Rec->getDecl();
  4269. }
  4270. QualType ASTContext::getBlockDescriptorType() const {
  4271. if (BlockDescriptorType)
  4272. return getTagDeclType(BlockDescriptorType);
  4273. RecordDecl *RD;
  4274. // FIXME: Needs the FlagAppleBlock bit.
  4275. RD = buildImplicitRecord("__block_descriptor");
  4276. RD->startDefinition();
  4277. QualType FieldTypes[] = {
  4278. UnsignedLongTy,
  4279. UnsignedLongTy,
  4280. };
  4281. static const char *const FieldNames[] = {
  4282. "reserved",
  4283. "Size"
  4284. };
  4285. for (size_t i = 0; i < 2; ++i) {
  4286. FieldDecl *Field = FieldDecl::Create(
  4287. *this, RD, SourceLocation(), SourceLocation(),
  4288. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  4289. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  4290. Field->setAccess(AS_public);
  4291. RD->addDecl(Field);
  4292. }
  4293. RD->completeDefinition();
  4294. BlockDescriptorType = RD;
  4295. return getTagDeclType(BlockDescriptorType);
  4296. }
  4297. QualType ASTContext::getBlockDescriptorExtendedType() const {
  4298. if (BlockDescriptorExtendedType)
  4299. return getTagDeclType(BlockDescriptorExtendedType);
  4300. RecordDecl *RD;
  4301. // FIXME: Needs the FlagAppleBlock bit.
  4302. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  4303. RD->startDefinition();
  4304. QualType FieldTypes[] = {
  4305. UnsignedLongTy,
  4306. UnsignedLongTy,
  4307. getPointerType(VoidPtrTy),
  4308. getPointerType(VoidPtrTy)
  4309. };
  4310. static const char *const FieldNames[] = {
  4311. "reserved",
  4312. "Size",
  4313. "CopyFuncPtr",
  4314. "DestroyFuncPtr"
  4315. };
  4316. for (size_t i = 0; i < 4; ++i) {
  4317. FieldDecl *Field = FieldDecl::Create(
  4318. *this, RD, SourceLocation(), SourceLocation(),
  4319. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  4320. /*BitWidth=*/nullptr,
  4321. /*Mutable=*/false, ICIS_NoInit);
  4322. Field->setAccess(AS_public);
  4323. RD->addDecl(Field);
  4324. }
  4325. RD->completeDefinition();
  4326. BlockDescriptorExtendedType = RD;
  4327. return getTagDeclType(BlockDescriptorExtendedType);
  4328. }
  4329. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  4330. /// requires copy/dispose. Note that this must match the logic
  4331. /// in buildByrefHelpers.
  4332. bool ASTContext::BlockRequiresCopying(QualType Ty,
  4333. const VarDecl *D) {
  4334. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  4335. const Expr *copyExpr = getBlockVarCopyInits(D);
  4336. if (!copyExpr && record->hasTrivialDestructor()) return false;
  4337. return true;
  4338. }
  4339. if (!Ty->isObjCRetainableType()) return false;
  4340. Qualifiers qs = Ty.getQualifiers();
  4341. // If we have lifetime, that dominates.
  4342. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  4343. assert(getLangOpts().ObjCAutoRefCount);
  4344. switch (lifetime) {
  4345. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  4346. // These are just bits as far as the runtime is concerned.
  4347. case Qualifiers::OCL_ExplicitNone:
  4348. case Qualifiers::OCL_Autoreleasing:
  4349. return false;
  4350. // Tell the runtime that this is ARC __weak, called by the
  4351. // byref routines.
  4352. case Qualifiers::OCL_Weak:
  4353. // ARC __strong __block variables need to be retained.
  4354. case Qualifiers::OCL_Strong:
  4355. return true;
  4356. }
  4357. llvm_unreachable("fell out of lifetime switch!");
  4358. }
  4359. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  4360. Ty->isObjCObjectPointerType());
  4361. }
  4362. bool ASTContext::getByrefLifetime(QualType Ty,
  4363. Qualifiers::ObjCLifetime &LifeTime,
  4364. bool &HasByrefExtendedLayout) const {
  4365. if (!getLangOpts().ObjC1 ||
  4366. getLangOpts().getGC() != LangOptions::NonGC)
  4367. return false;
  4368. HasByrefExtendedLayout = false;
  4369. if (Ty->isRecordType()) {
  4370. HasByrefExtendedLayout = true;
  4371. LifeTime = Qualifiers::OCL_None;
  4372. }
  4373. else if (getLangOpts().ObjCAutoRefCount)
  4374. LifeTime = Ty.getObjCLifetime();
  4375. // MRR.
  4376. else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  4377. LifeTime = Qualifiers::OCL_ExplicitNone;
  4378. else
  4379. LifeTime = Qualifiers::OCL_None;
  4380. return true;
  4381. }
  4382. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  4383. if (!ObjCInstanceTypeDecl)
  4384. ObjCInstanceTypeDecl =
  4385. buildImplicitTypedef(getObjCIdType(), "instancetype");
  4386. return ObjCInstanceTypeDecl;
  4387. }
  4388. // This returns true if a type has been typedefed to BOOL:
  4389. // typedef <type> BOOL;
  4390. static bool isTypeTypedefedAsBOOL(QualType T) {
  4391. if (const TypedefType *TT = dyn_cast<TypedefType>(T))
  4392. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  4393. return II->isStr("BOOL");
  4394. return false;
  4395. }
  4396. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  4397. /// purpose.
  4398. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  4399. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  4400. return CharUnits::Zero();
  4401. CharUnits sz = getTypeSizeInChars(type);
  4402. // Make all integer and enum types at least as large as an int
  4403. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  4404. sz = std::max(sz, getTypeSizeInChars(IntTy));
  4405. // Treat arrays as pointers, since that's how they're passed in.
  4406. else if (type->isArrayType())
  4407. sz = getTypeSizeInChars(VoidPtrTy);
  4408. return sz;
  4409. }
  4410. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  4411. return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
  4412. VD->getType()->isIntegralOrEnumerationType() &&
  4413. VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
  4414. }
  4415. static inline
  4416. std::string charUnitsToString(const CharUnits &CU) {
  4417. return llvm::itostr(CU.getQuantity());
  4418. }
  4419. /// getObjCEncodingForBlock - Return the encoded type for this block
  4420. /// declaration.
  4421. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  4422. std::string S;
  4423. const BlockDecl *Decl = Expr->getBlockDecl();
  4424. QualType BlockTy =
  4425. Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
  4426. // Encode result type.
  4427. if (getLangOpts().EncodeExtendedBlockSig)
  4428. getObjCEncodingForMethodParameter(
  4429. Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
  4430. true /*Extended*/);
  4431. else
  4432. getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
  4433. // Compute size of all parameters.
  4434. // Start with computing size of a pointer in number of bytes.
  4435. // FIXME: There might(should) be a better way of doing this computation!
  4436. SourceLocation Loc;
  4437. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  4438. CharUnits ParmOffset = PtrSize;
  4439. for (auto PI : Decl->params()) {
  4440. QualType PType = PI->getType();
  4441. CharUnits sz = getObjCEncodingTypeSize(PType);
  4442. if (sz.isZero())
  4443. continue;
  4444. assert (sz.isPositive() && "BlockExpr - Incomplete param type");
  4445. ParmOffset += sz;
  4446. }
  4447. // Size of the argument frame
  4448. S += charUnitsToString(ParmOffset);
  4449. // Block pointer and offset.
  4450. S += "@?0";
  4451. // Argument types.
  4452. ParmOffset = PtrSize;
  4453. for (auto PVDecl : Decl->params()) {
  4454. QualType PType = PVDecl->getOriginalType();
  4455. if (const ArrayType *AT =
  4456. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4457. // Use array's original type only if it has known number of
  4458. // elements.
  4459. if (!isa<ConstantArrayType>(AT))
  4460. PType = PVDecl->getType();
  4461. } else if (PType->isFunctionType())
  4462. PType = PVDecl->getType();
  4463. if (getLangOpts().EncodeExtendedBlockSig)
  4464. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  4465. S, true /*Extended*/);
  4466. else
  4467. getObjCEncodingForType(PType, S);
  4468. S += charUnitsToString(ParmOffset);
  4469. ParmOffset += getObjCEncodingTypeSize(PType);
  4470. }
  4471. return S;
  4472. }
  4473. bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
  4474. std::string& S) {
  4475. // Encode result type.
  4476. getObjCEncodingForType(Decl->getReturnType(), S);
  4477. CharUnits ParmOffset;
  4478. // Compute size of all parameters.
  4479. for (auto PI : Decl->params()) {
  4480. QualType PType = PI->getType();
  4481. CharUnits sz = getObjCEncodingTypeSize(PType);
  4482. if (sz.isZero())
  4483. continue;
  4484. assert (sz.isPositive() &&
  4485. "getObjCEncodingForFunctionDecl - Incomplete param type");
  4486. ParmOffset += sz;
  4487. }
  4488. S += charUnitsToString(ParmOffset);
  4489. ParmOffset = CharUnits::Zero();
  4490. // Argument types.
  4491. for (auto PVDecl : Decl->params()) {
  4492. QualType PType = PVDecl->getOriginalType();
  4493. if (const ArrayType *AT =
  4494. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4495. // Use array's original type only if it has known number of
  4496. // elements.
  4497. if (!isa<ConstantArrayType>(AT))
  4498. PType = PVDecl->getType();
  4499. } else if (PType->isFunctionType())
  4500. PType = PVDecl->getType();
  4501. getObjCEncodingForType(PType, S);
  4502. S += charUnitsToString(ParmOffset);
  4503. ParmOffset += getObjCEncodingTypeSize(PType);
  4504. }
  4505. return false;
  4506. }
  4507. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  4508. /// method parameter or return type. If Extended, include class names and
  4509. /// block object types.
  4510. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  4511. QualType T, std::string& S,
  4512. bool Extended) const {
  4513. // Encode type qualifer, 'in', 'inout', etc. for the parameter.
  4514. getObjCEncodingForTypeQualifier(QT, S);
  4515. // Encode parameter type.
  4516. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  4517. true /*OutermostType*/,
  4518. false /*EncodingProperty*/,
  4519. false /*StructField*/,
  4520. Extended /*EncodeBlockParameters*/,
  4521. Extended /*EncodeClassNames*/);
  4522. }
  4523. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  4524. /// declaration.
  4525. bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  4526. std::string& S,
  4527. bool Extended) const {
  4528. // FIXME: This is not very efficient.
  4529. // Encode return type.
  4530. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  4531. Decl->getReturnType(), S, Extended);
  4532. // Compute size of all parameters.
  4533. // Start with computing size of a pointer in number of bytes.
  4534. // FIXME: There might(should) be a better way of doing this computation!
  4535. SourceLocation Loc;
  4536. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  4537. // The first two arguments (self and _cmd) are pointers; account for
  4538. // their size.
  4539. CharUnits ParmOffset = 2 * PtrSize;
  4540. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  4541. E = Decl->sel_param_end(); PI != E; ++PI) {
  4542. QualType PType = (*PI)->getType();
  4543. CharUnits sz = getObjCEncodingTypeSize(PType);
  4544. if (sz.isZero())
  4545. continue;
  4546. assert (sz.isPositive() &&
  4547. "getObjCEncodingForMethodDecl - Incomplete param type");
  4548. ParmOffset += sz;
  4549. }
  4550. S += charUnitsToString(ParmOffset);
  4551. S += "@0:";
  4552. S += charUnitsToString(PtrSize);
  4553. // Argument types.
  4554. ParmOffset = 2 * PtrSize;
  4555. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  4556. E = Decl->sel_param_end(); PI != E; ++PI) {
  4557. const ParmVarDecl *PVDecl = *PI;
  4558. QualType PType = PVDecl->getOriginalType();
  4559. if (const ArrayType *AT =
  4560. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  4561. // Use array's original type only if it has known number of
  4562. // elements.
  4563. if (!isa<ConstantArrayType>(AT))
  4564. PType = PVDecl->getType();
  4565. } else if (PType->isFunctionType())
  4566. PType = PVDecl->getType();
  4567. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  4568. PType, S, Extended);
  4569. S += charUnitsToString(ParmOffset);
  4570. ParmOffset += getObjCEncodingTypeSize(PType);
  4571. }
  4572. return false;
  4573. }
  4574. ObjCPropertyImplDecl *
  4575. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  4576. const ObjCPropertyDecl *PD,
  4577. const Decl *Container) const {
  4578. if (!Container)
  4579. return nullptr;
  4580. if (const ObjCCategoryImplDecl *CID =
  4581. dyn_cast<ObjCCategoryImplDecl>(Container)) {
  4582. for (auto *PID : CID->property_impls())
  4583. if (PID->getPropertyDecl() == PD)
  4584. return PID;
  4585. } else {
  4586. const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
  4587. for (auto *PID : OID->property_impls())
  4588. if (PID->getPropertyDecl() == PD)
  4589. return PID;
  4590. }
  4591. return nullptr;
  4592. }
  4593. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  4594. /// property declaration. If non-NULL, Container must be either an
  4595. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  4596. /// NULL when getting encodings for protocol properties.
  4597. /// Property attributes are stored as a comma-delimited C string. The simple
  4598. /// attributes readonly and bycopy are encoded as single characters. The
  4599. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  4600. /// encoded as single characters, followed by an identifier. Property types
  4601. /// are also encoded as a parametrized attribute. The characters used to encode
  4602. /// these attributes are defined by the following enumeration:
  4603. /// @code
  4604. /// enum PropertyAttributes {
  4605. /// kPropertyReadOnly = 'R', // property is read-only.
  4606. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  4607. /// kPropertyByref = '&', // property is a reference to the value last assigned
  4608. /// kPropertyDynamic = 'D', // property is dynamic
  4609. /// kPropertyGetter = 'G', // followed by getter selector name
  4610. /// kPropertySetter = 'S', // followed by setter selector name
  4611. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  4612. /// kPropertyType = 'T' // followed by old-style type encoding.
  4613. /// kPropertyWeak = 'W' // 'weak' property
  4614. /// kPropertyStrong = 'P' // property GC'able
  4615. /// kPropertyNonAtomic = 'N' // property non-atomic
  4616. /// };
  4617. /// @endcode
  4618. void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  4619. const Decl *Container,
  4620. std::string& S) const {
  4621. // Collect information from the property implementation decl(s).
  4622. bool Dynamic = false;
  4623. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  4624. if (ObjCPropertyImplDecl *PropertyImpDecl =
  4625. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  4626. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  4627. Dynamic = true;
  4628. else
  4629. SynthesizePID = PropertyImpDecl;
  4630. }
  4631. // FIXME: This is not very efficient.
  4632. S = "T";
  4633. // Encode result type.
  4634. // GCC has some special rules regarding encoding of properties which
  4635. // closely resembles encoding of ivars.
  4636. getObjCEncodingForPropertyType(PD->getType(), S);
  4637. if (PD->isReadOnly()) {
  4638. S += ",R";
  4639. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
  4640. S += ",C";
  4641. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
  4642. S += ",&";
  4643. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
  4644. S += ",W";
  4645. } else {
  4646. switch (PD->getSetterKind()) {
  4647. case ObjCPropertyDecl::Assign: break;
  4648. case ObjCPropertyDecl::Copy: S += ",C"; break;
  4649. case ObjCPropertyDecl::Retain: S += ",&"; break;
  4650. case ObjCPropertyDecl::Weak: S += ",W"; break;
  4651. }
  4652. }
  4653. // It really isn't clear at all what this means, since properties
  4654. // are "dynamic by default".
  4655. if (Dynamic)
  4656. S += ",D";
  4657. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
  4658. S += ",N";
  4659. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
  4660. S += ",G";
  4661. S += PD->getGetterName().getAsString();
  4662. }
  4663. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
  4664. S += ",S";
  4665. S += PD->getSetterName().getAsString();
  4666. }
  4667. if (SynthesizePID) {
  4668. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  4669. S += ",V";
  4670. S += OID->getNameAsString();
  4671. }
  4672. // FIXME: OBJCGC: weak & strong
  4673. }
  4674. /// getLegacyIntegralTypeEncoding -
  4675. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  4676. /// 'l' or 'L' , but not always. For typedefs, we need to use
  4677. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  4678. ///
  4679. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  4680. if (isa<TypedefType>(PointeeTy.getTypePtr())) {
  4681. if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
  4682. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  4683. PointeeTy = UnsignedIntTy;
  4684. else
  4685. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  4686. PointeeTy = IntTy;
  4687. }
  4688. }
  4689. }
  4690. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  4691. const FieldDecl *Field,
  4692. QualType *NotEncodedT) const {
  4693. // We follow the behavior of gcc, expanding structures which are
  4694. // directly pointed to, and expanding embedded structures. Note that
  4695. // these rules are sufficient to prevent recursive encoding of the
  4696. // same type.
  4697. getObjCEncodingForTypeImpl(T, S, true, true, Field,
  4698. true /* outermost type */, false, false,
  4699. false, false, false, NotEncodedT);
  4700. }
  4701. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  4702. std::string& S) const {
  4703. // Encode result type.
  4704. // GCC has some special rules regarding encoding of properties which
  4705. // closely resembles encoding of ivars.
  4706. getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
  4707. true /* outermost type */,
  4708. true /* encoding property */);
  4709. }
  4710. static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
  4711. BuiltinType::Kind kind) {
  4712. switch (kind) {
  4713. case BuiltinType::Void: return 'v';
  4714. case BuiltinType::Bool: return 'B';
  4715. case BuiltinType::Char_U:
  4716. case BuiltinType::UChar: return 'C';
  4717. case BuiltinType::Char16:
  4718. case BuiltinType::UShort: return 'S';
  4719. case BuiltinType::Char32:
  4720. case BuiltinType::UInt: return 'I';
  4721. case BuiltinType::ULong:
  4722. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  4723. case BuiltinType::UInt128: return 'T';
  4724. case BuiltinType::ULongLong: return 'Q';
  4725. case BuiltinType::Char_S:
  4726. case BuiltinType::SChar: return 'c';
  4727. case BuiltinType::Short: return 's';
  4728. case BuiltinType::WChar_S:
  4729. case BuiltinType::WChar_U:
  4730. case BuiltinType::Int: return 'i';
  4731. case BuiltinType::Long:
  4732. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  4733. case BuiltinType::LongLong: return 'q';
  4734. case BuiltinType::Int128: return 't';
  4735. case BuiltinType::Float: return 'f';
  4736. case BuiltinType::Double: return 'd';
  4737. case BuiltinType::LongDouble: return 'D';
  4738. case BuiltinType::NullPtr: return '*'; // like char*
  4739. case BuiltinType::Half:
  4740. // FIXME: potentially need @encodes for these!
  4741. return ' ';
  4742. case BuiltinType::ObjCId:
  4743. case BuiltinType::ObjCClass:
  4744. case BuiltinType::ObjCSel:
  4745. llvm_unreachable("@encoding ObjC primitive type");
  4746. // OpenCL and placeholder types don't need @encodings.
  4747. case BuiltinType::OCLImage1d:
  4748. case BuiltinType::OCLImage1dArray:
  4749. case BuiltinType::OCLImage1dBuffer:
  4750. case BuiltinType::OCLImage2d:
  4751. case BuiltinType::OCLImage2dArray:
  4752. case BuiltinType::OCLImage3d:
  4753. case BuiltinType::OCLEvent:
  4754. case BuiltinType::OCLSampler:
  4755. case BuiltinType::Dependent:
  4756. #define BUILTIN_TYPE(KIND, ID)
  4757. #define PLACEHOLDER_TYPE(KIND, ID) \
  4758. case BuiltinType::KIND:
  4759. #include "clang/AST/BuiltinTypes.def"
  4760. llvm_unreachable("invalid builtin type for @encode");
  4761. // HLSL Change Start
  4762. case BuiltinType::Min12Int:
  4763. case BuiltinType::Min10Float:
  4764. case BuiltinType::Min16Float:
  4765. case BuiltinType::Min16Int:
  4766. case BuiltinType::Min16UInt:
  4767. case BuiltinType::HalfFloat:
  4768. case BuiltinType::LitInt:
  4769. case BuiltinType::LitFloat:
  4770. llvm_unreachable("@encoding HLSL primitive type");
  4771. // HLSL Change Ends
  4772. }
  4773. llvm_unreachable("invalid BuiltinType::Kind value");
  4774. }
  4775. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  4776. EnumDecl *Enum = ET->getDecl();
  4777. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  4778. if (!Enum->isFixed())
  4779. return 'i';
  4780. // The encoding of a fixed enum type matches its fixed underlying type.
  4781. const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  4782. return getObjCEncodingForPrimitiveKind(C, BT->getKind());
  4783. }
  4784. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  4785. QualType T, const FieldDecl *FD) {
  4786. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  4787. S += 'b';
  4788. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  4789. // The GNU runtime requires more information; bitfields are encoded as b,
  4790. // then the offset (in bits) of the first element, then the type of the
  4791. // bitfield, then the size in bits. For example, in this structure:
  4792. //
  4793. // struct
  4794. // {
  4795. // int integer;
  4796. // int flags:2;
  4797. // };
  4798. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  4799. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  4800. // information is not especially sensible, but we're stuck with it for
  4801. // compatibility with GCC, although providing it breaks anything that
  4802. // actually uses runtime introspection and wants to work on both runtimes...
  4803. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  4804. const RecordDecl *RD = FD->getParent();
  4805. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  4806. S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
  4807. if (const EnumType *ET = T->getAs<EnumType>())
  4808. S += ObjCEncodingForEnumType(Ctx, ET);
  4809. else {
  4810. const BuiltinType *BT = T->castAs<BuiltinType>();
  4811. S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
  4812. }
  4813. }
  4814. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  4815. }
  4816. // FIXME: Use SmallString for accumulating string.
  4817. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
  4818. bool ExpandPointedToStructures,
  4819. bool ExpandStructures,
  4820. const FieldDecl *FD,
  4821. bool OutermostType,
  4822. bool EncodingProperty,
  4823. bool StructField,
  4824. bool EncodeBlockParameters,
  4825. bool EncodeClassNames,
  4826. bool EncodePointerToObjCTypedef,
  4827. QualType *NotEncodedT) const {
  4828. CanQualType CT = getCanonicalType(T);
  4829. switch (CT->getTypeClass()) {
  4830. case Type::Builtin:
  4831. case Type::Enum:
  4832. if (FD && FD->isBitField())
  4833. return EncodeBitField(this, S, T, FD);
  4834. if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
  4835. S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
  4836. else
  4837. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  4838. return;
  4839. case Type::Complex: {
  4840. const ComplexType *CT = T->castAs<ComplexType>();
  4841. S += 'j';
  4842. getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
  4843. return;
  4844. }
  4845. case Type::Atomic: {
  4846. const AtomicType *AT = T->castAs<AtomicType>();
  4847. S += 'A';
  4848. getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
  4849. return;
  4850. }
  4851. // encoding for pointer or reference types.
  4852. case Type::Pointer:
  4853. case Type::LValueReference:
  4854. case Type::RValueReference: {
  4855. QualType PointeeTy;
  4856. if (isa<PointerType>(CT)) {
  4857. const PointerType *PT = T->castAs<PointerType>();
  4858. if (PT->isObjCSelType()) {
  4859. S += ':';
  4860. return;
  4861. }
  4862. PointeeTy = PT->getPointeeType();
  4863. } else {
  4864. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  4865. }
  4866. bool isReadOnly = false;
  4867. // For historical/compatibility reasons, the read-only qualifier of the
  4868. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  4869. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  4870. // Also, do not emit the 'r' for anything but the outermost type!
  4871. if (isa<TypedefType>(T.getTypePtr())) {
  4872. if (OutermostType && T.isConstQualified()) {
  4873. isReadOnly = true;
  4874. S += 'r';
  4875. }
  4876. } else if (OutermostType) {
  4877. QualType P = PointeeTy;
  4878. while (P->getAs<PointerType>())
  4879. P = P->getAs<PointerType>()->getPointeeType();
  4880. if (P.isConstQualified()) {
  4881. isReadOnly = true;
  4882. S += 'r';
  4883. }
  4884. }
  4885. if (isReadOnly) {
  4886. // Another legacy compatibility encoding. Some ObjC qualifier and type
  4887. // combinations need to be rearranged.
  4888. // Rewrite "in const" from "nr" to "rn"
  4889. if (StringRef(S).endswith("nr"))
  4890. S.replace(S.end()-2, S.end(), "rn");
  4891. }
  4892. if (PointeeTy->isCharType()) {
  4893. // char pointer types should be encoded as '*' unless it is a
  4894. // type that has been typedef'd to 'BOOL'.
  4895. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  4896. S += '*';
  4897. return;
  4898. }
  4899. } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
  4900. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  4901. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  4902. S += '#';
  4903. return;
  4904. }
  4905. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  4906. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  4907. S += '@';
  4908. return;
  4909. }
  4910. // fall through...
  4911. }
  4912. S += '^';
  4913. getLegacyIntegralTypeEncoding(PointeeTy);
  4914. getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
  4915. nullptr, false, false, false, false, false, false,
  4916. NotEncodedT);
  4917. return;
  4918. }
  4919. case Type::ConstantArray:
  4920. case Type::IncompleteArray:
  4921. case Type::VariableArray: {
  4922. const ArrayType *AT = cast<ArrayType>(CT);
  4923. if (isa<IncompleteArrayType>(AT) && !StructField) {
  4924. // Incomplete arrays are encoded as a pointer to the array element.
  4925. S += '^';
  4926. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  4927. false, ExpandStructures, FD);
  4928. } else {
  4929. S += '[';
  4930. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
  4931. S += llvm::utostr(CAT->getSize().getZExtValue());
  4932. else {
  4933. //Variable length arrays are encoded as a regular array with 0 elements.
  4934. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  4935. "Unknown array type!");
  4936. S += '0';
  4937. }
  4938. getObjCEncodingForTypeImpl(AT->getElementType(), S,
  4939. false, ExpandStructures, FD,
  4940. false, false, false, false, false, false,
  4941. NotEncodedT);
  4942. S += ']';
  4943. }
  4944. return;
  4945. }
  4946. case Type::FunctionNoProto:
  4947. case Type::FunctionProto:
  4948. S += '?';
  4949. return;
  4950. case Type::Record: {
  4951. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  4952. S += RDecl->isUnion() ? '(' : '{';
  4953. // Anonymous structures print as '?'
  4954. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  4955. S += II->getName();
  4956. if (ClassTemplateSpecializationDecl *Spec
  4957. = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  4958. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  4959. llvm::raw_string_ostream OS(S);
  4960. TemplateSpecializationType::PrintTemplateArgumentList(OS,
  4961. TemplateArgs.data(),
  4962. TemplateArgs.size(),
  4963. (*this).getPrintingPolicy());
  4964. }
  4965. } else {
  4966. S += '?';
  4967. }
  4968. if (ExpandStructures) {
  4969. S += '=';
  4970. if (!RDecl->isUnion()) {
  4971. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  4972. } else {
  4973. for (const auto *Field : RDecl->fields()) {
  4974. if (FD) {
  4975. S += '"';
  4976. S += Field->getNameAsString();
  4977. S += '"';
  4978. }
  4979. // Special case bit-fields.
  4980. if (Field->isBitField()) {
  4981. getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
  4982. Field);
  4983. } else {
  4984. QualType qt = Field->getType();
  4985. getLegacyIntegralTypeEncoding(qt);
  4986. getObjCEncodingForTypeImpl(qt, S, false, true,
  4987. FD, /*OutermostType*/false,
  4988. /*EncodingProperty*/false,
  4989. /*StructField*/true,
  4990. false, false, false, NotEncodedT);
  4991. }
  4992. }
  4993. }
  4994. }
  4995. S += RDecl->isUnion() ? ')' : '}';
  4996. return;
  4997. }
  4998. case Type::BlockPointer: {
  4999. const BlockPointerType *BT = T->castAs<BlockPointerType>();
  5000. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  5001. if (EncodeBlockParameters) {
  5002. const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
  5003. S += '<';
  5004. // Block return type
  5005. getObjCEncodingForTypeImpl(
  5006. FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
  5007. FD, false /* OutermostType */, EncodingProperty,
  5008. false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
  5009. NotEncodedT);
  5010. // Block self
  5011. S += "@?";
  5012. // Block parameters
  5013. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
  5014. for (const auto &I : FPT->param_types())
  5015. getObjCEncodingForTypeImpl(
  5016. I, S, ExpandPointedToStructures, ExpandStructures, FD,
  5017. false /* OutermostType */, EncodingProperty,
  5018. false /* StructField */, EncodeBlockParameters, EncodeClassNames,
  5019. false, NotEncodedT);
  5020. }
  5021. S += '>';
  5022. }
  5023. return;
  5024. }
  5025. case Type::ObjCObject: {
  5026. // hack to match legacy encoding of *id and *Class
  5027. QualType Ty = getObjCObjectPointerType(CT);
  5028. if (Ty->isObjCIdType()) {
  5029. S += "{objc_object=}";
  5030. return;
  5031. }
  5032. else if (Ty->isObjCClassType()) {
  5033. S += "{objc_class=}";
  5034. return;
  5035. }
  5036. }
  5037. case Type::ObjCInterface: {
  5038. // Ignore protocol qualifiers when mangling at this level.
  5039. // @encode(class_name)
  5040. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  5041. S += '{';
  5042. S += OI->getObjCRuntimeNameAsString();
  5043. S += '=';
  5044. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  5045. DeepCollectObjCIvars(OI, true, Ivars);
  5046. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  5047. const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
  5048. if (Field->isBitField())
  5049. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
  5050. else
  5051. getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
  5052. false, false, false, false, false,
  5053. EncodePointerToObjCTypedef,
  5054. NotEncodedT);
  5055. }
  5056. S += '}';
  5057. return;
  5058. }
  5059. case Type::ObjCObjectPointer: {
  5060. const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
  5061. if (OPT->isObjCIdType()) {
  5062. S += '@';
  5063. return;
  5064. }
  5065. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  5066. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  5067. // Since this is a binary compatibility issue, need to consult with runtime
  5068. // folks. Fortunately, this is a *very* obsure construct.
  5069. S += '#';
  5070. return;
  5071. }
  5072. if (OPT->isObjCQualifiedIdType()) {
  5073. getObjCEncodingForTypeImpl(getObjCIdType(), S,
  5074. ExpandPointedToStructures,
  5075. ExpandStructures, FD);
  5076. if (FD || EncodingProperty || EncodeClassNames) {
  5077. // Note that we do extended encoding of protocol qualifer list
  5078. // Only when doing ivar or property encoding.
  5079. S += '"';
  5080. for (const auto *I : OPT->quals()) {
  5081. S += '<';
  5082. S += I->getObjCRuntimeNameAsString();
  5083. S += '>';
  5084. }
  5085. S += '"';
  5086. }
  5087. return;
  5088. }
  5089. QualType PointeeTy = OPT->getPointeeType();
  5090. if (!EncodingProperty &&
  5091. isa<TypedefType>(PointeeTy.getTypePtr()) &&
  5092. !EncodePointerToObjCTypedef) {
  5093. // Another historical/compatibility reason.
  5094. // We encode the underlying type which comes out as
  5095. // {...};
  5096. S += '^';
  5097. if (FD && OPT->getInterfaceDecl()) {
  5098. // Prevent recursive encoding of fields in some rare cases.
  5099. ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
  5100. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  5101. DeepCollectObjCIvars(OI, true, Ivars);
  5102. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  5103. if (cast<FieldDecl>(Ivars[i]) == FD) {
  5104. S += '{';
  5105. S += OI->getObjCRuntimeNameAsString();
  5106. S += '}';
  5107. return;
  5108. }
  5109. }
  5110. }
  5111. getObjCEncodingForTypeImpl(PointeeTy, S,
  5112. false, ExpandPointedToStructures,
  5113. nullptr,
  5114. false, false, false, false, false,
  5115. /*EncodePointerToObjCTypedef*/true);
  5116. return;
  5117. }
  5118. S += '@';
  5119. if (OPT->getInterfaceDecl() &&
  5120. (FD || EncodingProperty || EncodeClassNames)) {
  5121. S += '"';
  5122. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  5123. for (const auto *I : OPT->quals()) {
  5124. S += '<';
  5125. S += I->getObjCRuntimeNameAsString();
  5126. S += '>';
  5127. }
  5128. S += '"';
  5129. }
  5130. return;
  5131. }
  5132. // gcc just blithely ignores member pointers.
  5133. // FIXME: we shoul do better than that. 'M' is available.
  5134. case Type::MemberPointer:
  5135. // This matches gcc's encoding, even though technically it is insufficient.
  5136. //FIXME. We should do a better job than gcc.
  5137. case Type::Vector:
  5138. case Type::ExtVector:
  5139. // Until we have a coherent encoding of these three types, issue warning.
  5140. { if (NotEncodedT)
  5141. *NotEncodedT = T;
  5142. return;
  5143. }
  5144. // We could see an undeduced auto type here during error recovery.
  5145. // Just ignore it.
  5146. case Type::Auto:
  5147. return;
  5148. #define ABSTRACT_TYPE(KIND, BASE)
  5149. #define TYPE(KIND, BASE)
  5150. #define DEPENDENT_TYPE(KIND, BASE) \
  5151. case Type::KIND:
  5152. #define NON_CANONICAL_TYPE(KIND, BASE) \
  5153. case Type::KIND:
  5154. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  5155. case Type::KIND:
  5156. #include "clang/AST/TypeNodes.def"
  5157. llvm_unreachable("@encode for dependent type!");
  5158. }
  5159. llvm_unreachable("bad type kind!");
  5160. }
  5161. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  5162. std::string &S,
  5163. const FieldDecl *FD,
  5164. bool includeVBases,
  5165. QualType *NotEncodedT) const {
  5166. assert(RDecl && "Expected non-null RecordDecl");
  5167. assert(!RDecl->isUnion() && "Should not be called for unions");
  5168. if (!RDecl->getDefinition())
  5169. return;
  5170. CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  5171. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  5172. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  5173. if (CXXRec) {
  5174. for (const auto &BI : CXXRec->bases()) {
  5175. if (!BI.isVirtual()) {
  5176. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  5177. if (base->isEmpty())
  5178. continue;
  5179. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  5180. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5181. std::make_pair(offs, base));
  5182. }
  5183. }
  5184. }
  5185. unsigned i = 0;
  5186. for (auto *Field : RDecl->fields()) {
  5187. uint64_t offs = layout.getFieldOffset(i);
  5188. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5189. std::make_pair(offs, Field));
  5190. ++i;
  5191. }
  5192. if (CXXRec && includeVBases) {
  5193. for (const auto &BI : CXXRec->vbases()) {
  5194. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  5195. if (base->isEmpty())
  5196. continue;
  5197. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  5198. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  5199. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  5200. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  5201. std::make_pair(offs, base));
  5202. }
  5203. }
  5204. CharUnits size;
  5205. if (CXXRec) {
  5206. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  5207. } else {
  5208. size = layout.getSize();
  5209. }
  5210. #ifndef NDEBUG
  5211. uint64_t CurOffs = 0;
  5212. #endif
  5213. std::multimap<uint64_t, NamedDecl *>::iterator
  5214. CurLayObj = FieldOrBaseOffsets.begin();
  5215. if (CXXRec && CXXRec->isDynamicClass() &&
  5216. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  5217. if (FD) {
  5218. S += "\"_vptr$";
  5219. std::string recname = CXXRec->getNameAsString();
  5220. if (recname.empty()) recname = "?";
  5221. S += recname;
  5222. S += '"';
  5223. }
  5224. S += "^^?";
  5225. #ifndef NDEBUG
  5226. CurOffs += getTypeSize(VoidPtrTy);
  5227. #endif
  5228. }
  5229. if (!RDecl->hasFlexibleArrayMember()) {
  5230. // Mark the end of the structure.
  5231. uint64_t offs = toBits(size);
  5232. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  5233. std::make_pair(offs, nullptr));
  5234. }
  5235. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  5236. #ifndef NDEBUG
  5237. assert(CurOffs <= CurLayObj->first);
  5238. if (CurOffs < CurLayObj->first) {
  5239. uint64_t padding = CurLayObj->first - CurOffs;
  5240. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  5241. // packing/alignment of members is different that normal, in which case
  5242. // the encoding will be out-of-sync with the real layout.
  5243. // If the runtime switches to just consider the size of types without
  5244. // taking into account alignment, we could make padding explicit in the
  5245. // encoding (e.g. using arrays of chars). The encoding strings would be
  5246. // longer then though.
  5247. CurOffs += padding;
  5248. }
  5249. #endif
  5250. NamedDecl *dcl = CurLayObj->second;
  5251. if (!dcl)
  5252. break; // reached end of structure.
  5253. if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
  5254. // We expand the bases without their virtual bases since those are going
  5255. // in the initial structure. Note that this differs from gcc which
  5256. // expands virtual bases each time one is encountered in the hierarchy,
  5257. // making the encoding type bigger than it really is.
  5258. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  5259. NotEncodedT);
  5260. assert(!base->isEmpty());
  5261. #ifndef NDEBUG
  5262. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  5263. #endif
  5264. } else {
  5265. FieldDecl *field = cast<FieldDecl>(dcl);
  5266. if (FD) {
  5267. S += '"';
  5268. S += field->getNameAsString();
  5269. S += '"';
  5270. }
  5271. if (field->isBitField()) {
  5272. EncodeBitField(this, S, field->getType(), field);
  5273. #ifndef NDEBUG
  5274. CurOffs += field->getBitWidthValue(*this);
  5275. #endif
  5276. } else {
  5277. QualType qt = field->getType();
  5278. getLegacyIntegralTypeEncoding(qt);
  5279. getObjCEncodingForTypeImpl(qt, S, false, true, FD,
  5280. /*OutermostType*/false,
  5281. /*EncodingProperty*/false,
  5282. /*StructField*/true,
  5283. false, false, false, NotEncodedT);
  5284. #ifndef NDEBUG
  5285. CurOffs += getTypeSize(field->getType());
  5286. #endif
  5287. }
  5288. }
  5289. }
  5290. }
  5291. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  5292. std::string& S) const {
  5293. if (QT & Decl::OBJC_TQ_In)
  5294. S += 'n';
  5295. if (QT & Decl::OBJC_TQ_Inout)
  5296. S += 'N';
  5297. if (QT & Decl::OBJC_TQ_Out)
  5298. S += 'o';
  5299. if (QT & Decl::OBJC_TQ_Bycopy)
  5300. S += 'O';
  5301. if (QT & Decl::OBJC_TQ_Byref)
  5302. S += 'R';
  5303. if (QT & Decl::OBJC_TQ_Oneway)
  5304. S += 'V';
  5305. }
  5306. TypedefDecl *ASTContext::getObjCIdDecl() const {
  5307. if (!ObjCIdDecl) {
  5308. QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
  5309. T = getObjCObjectPointerType(T);
  5310. ObjCIdDecl = buildImplicitTypedef(T, "id");
  5311. }
  5312. return ObjCIdDecl;
  5313. }
  5314. TypedefDecl *ASTContext::getObjCSelDecl() const {
  5315. if (!ObjCSelDecl) {
  5316. QualType T = getPointerType(ObjCBuiltinSelTy);
  5317. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  5318. }
  5319. return ObjCSelDecl;
  5320. }
  5321. TypedefDecl *ASTContext::getObjCClassDecl() const {
  5322. if (!ObjCClassDecl) {
  5323. QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
  5324. T = getObjCObjectPointerType(T);
  5325. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  5326. }
  5327. return ObjCClassDecl;
  5328. }
  5329. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  5330. if (!ObjCProtocolClassDecl) {
  5331. ObjCProtocolClassDecl
  5332. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  5333. SourceLocation(),
  5334. &Idents.get("Protocol"),
  5335. /*typeParamList=*/nullptr,
  5336. /*PrevDecl=*/nullptr,
  5337. SourceLocation(), true);
  5338. }
  5339. return ObjCProtocolClassDecl;
  5340. }
  5341. //===----------------------------------------------------------------------===//
  5342. // __builtin_va_list Construction Functions
  5343. //===----------------------------------------------------------------------===//
  5344. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  5345. // typedef char* __builtin_va_list;
  5346. QualType T = Context->getPointerType(Context->CharTy);
  5347. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5348. }
  5349. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  5350. // typedef void* __builtin_va_list;
  5351. QualType T = Context->getPointerType(Context->VoidTy);
  5352. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5353. }
  5354. static TypedefDecl *
  5355. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  5356. // struct __va_list
  5357. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  5358. if (Context->getLangOpts().CPlusPlus) {
  5359. // namespace std { struct __va_list {
  5360. NamespaceDecl *NS;
  5361. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  5362. Context->getTranslationUnitDecl(),
  5363. /*Inline*/ false, SourceLocation(),
  5364. SourceLocation(), &Context->Idents.get("std"),
  5365. /*PrevDecl*/ nullptr);
  5366. NS->setImplicit();
  5367. VaListTagDecl->setDeclContext(NS);
  5368. }
  5369. VaListTagDecl->startDefinition();
  5370. const size_t NumFields = 5;
  5371. QualType FieldTypes[NumFields];
  5372. const char *FieldNames[NumFields];
  5373. // void *__stack;
  5374. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  5375. FieldNames[0] = "__stack";
  5376. // void *__gr_top;
  5377. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  5378. FieldNames[1] = "__gr_top";
  5379. // void *__vr_top;
  5380. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5381. FieldNames[2] = "__vr_top";
  5382. // int __gr_offs;
  5383. FieldTypes[3] = Context->IntTy;
  5384. FieldNames[3] = "__gr_offs";
  5385. // int __vr_offs;
  5386. FieldTypes[4] = Context->IntTy;
  5387. FieldNames[4] = "__vr_offs";
  5388. // Create fields
  5389. for (unsigned i = 0; i < NumFields; ++i) {
  5390. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5391. VaListTagDecl,
  5392. SourceLocation(),
  5393. SourceLocation(),
  5394. &Context->Idents.get(FieldNames[i]),
  5395. FieldTypes[i], /*TInfo=*/nullptr,
  5396. /*BitWidth=*/nullptr,
  5397. /*Mutable=*/false,
  5398. ICIS_NoInit);
  5399. Field->setAccess(AS_public);
  5400. VaListTagDecl->addDecl(Field);
  5401. }
  5402. VaListTagDecl->completeDefinition();
  5403. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5404. Context->VaListTagTy = VaListTagType;
  5405. // } __builtin_va_list;
  5406. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  5407. }
  5408. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  5409. // typedef struct __va_list_tag {
  5410. RecordDecl *VaListTagDecl;
  5411. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5412. VaListTagDecl->startDefinition();
  5413. const size_t NumFields = 5;
  5414. QualType FieldTypes[NumFields];
  5415. const char *FieldNames[NumFields];
  5416. // unsigned char gpr;
  5417. FieldTypes[0] = Context->UnsignedCharTy;
  5418. FieldNames[0] = "gpr";
  5419. // unsigned char fpr;
  5420. FieldTypes[1] = Context->UnsignedCharTy;
  5421. FieldNames[1] = "fpr";
  5422. // unsigned short reserved;
  5423. FieldTypes[2] = Context->UnsignedShortTy;
  5424. FieldNames[2] = "reserved";
  5425. // void* overflow_arg_area;
  5426. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5427. FieldNames[3] = "overflow_arg_area";
  5428. // void* reg_save_area;
  5429. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  5430. FieldNames[4] = "reg_save_area";
  5431. // Create fields
  5432. for (unsigned i = 0; i < NumFields; ++i) {
  5433. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  5434. SourceLocation(),
  5435. SourceLocation(),
  5436. &Context->Idents.get(FieldNames[i]),
  5437. FieldTypes[i], /*TInfo=*/nullptr,
  5438. /*BitWidth=*/nullptr,
  5439. /*Mutable=*/false,
  5440. ICIS_NoInit);
  5441. Field->setAccess(AS_public);
  5442. VaListTagDecl->addDecl(Field);
  5443. }
  5444. VaListTagDecl->completeDefinition();
  5445. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5446. Context->VaListTagTy = VaListTagType;
  5447. // } __va_list_tag;
  5448. TypedefDecl *VaListTagTypedefDecl =
  5449. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5450. QualType VaListTagTypedefType =
  5451. Context->getTypedefType(VaListTagTypedefDecl);
  5452. // typedef __va_list_tag __builtin_va_list[1];
  5453. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5454. QualType VaListTagArrayType
  5455. = Context->getConstantArrayType(VaListTagTypedefType,
  5456. Size, ArrayType::Normal, 0);
  5457. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5458. }
  5459. static TypedefDecl *
  5460. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  5461. // typedef struct __va_list_tag {
  5462. RecordDecl *VaListTagDecl;
  5463. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5464. VaListTagDecl->startDefinition();
  5465. const size_t NumFields = 4;
  5466. QualType FieldTypes[NumFields];
  5467. const char *FieldNames[NumFields];
  5468. // unsigned gp_offset;
  5469. FieldTypes[0] = Context->UnsignedIntTy;
  5470. FieldNames[0] = "gp_offset";
  5471. // unsigned fp_offset;
  5472. FieldTypes[1] = Context->UnsignedIntTy;
  5473. FieldNames[1] = "fp_offset";
  5474. // void* overflow_arg_area;
  5475. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5476. FieldNames[2] = "overflow_arg_area";
  5477. // void* reg_save_area;
  5478. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5479. FieldNames[3] = "reg_save_area";
  5480. // Create fields
  5481. for (unsigned i = 0; i < NumFields; ++i) {
  5482. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5483. VaListTagDecl,
  5484. SourceLocation(),
  5485. SourceLocation(),
  5486. &Context->Idents.get(FieldNames[i]),
  5487. FieldTypes[i], /*TInfo=*/nullptr,
  5488. /*BitWidth=*/nullptr,
  5489. /*Mutable=*/false,
  5490. ICIS_NoInit);
  5491. Field->setAccess(AS_public);
  5492. VaListTagDecl->addDecl(Field);
  5493. }
  5494. VaListTagDecl->completeDefinition();
  5495. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5496. Context->VaListTagTy = VaListTagType;
  5497. // } __va_list_tag;
  5498. TypedefDecl *VaListTagTypedefDecl =
  5499. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5500. QualType VaListTagTypedefType =
  5501. Context->getTypedefType(VaListTagTypedefDecl);
  5502. // typedef __va_list_tag __builtin_va_list[1];
  5503. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5504. QualType VaListTagArrayType
  5505. = Context->getConstantArrayType(VaListTagTypedefType,
  5506. Size, ArrayType::Normal,0);
  5507. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5508. }
  5509. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  5510. // typedef int __builtin_va_list[4];
  5511. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  5512. QualType IntArrayType
  5513. = Context->getConstantArrayType(Context->IntTy,
  5514. Size, ArrayType::Normal, 0);
  5515. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  5516. }
  5517. static TypedefDecl *
  5518. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  5519. // struct __va_list
  5520. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  5521. if (Context->getLangOpts().CPlusPlus) {
  5522. // namespace std { struct __va_list {
  5523. NamespaceDecl *NS;
  5524. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  5525. Context->getTranslationUnitDecl(),
  5526. /*Inline*/false, SourceLocation(),
  5527. SourceLocation(), &Context->Idents.get("std"),
  5528. /*PrevDecl*/ nullptr);
  5529. NS->setImplicit();
  5530. VaListDecl->setDeclContext(NS);
  5531. }
  5532. VaListDecl->startDefinition();
  5533. // void * __ap;
  5534. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5535. VaListDecl,
  5536. SourceLocation(),
  5537. SourceLocation(),
  5538. &Context->Idents.get("__ap"),
  5539. Context->getPointerType(Context->VoidTy),
  5540. /*TInfo=*/nullptr,
  5541. /*BitWidth=*/nullptr,
  5542. /*Mutable=*/false,
  5543. ICIS_NoInit);
  5544. Field->setAccess(AS_public);
  5545. VaListDecl->addDecl(Field);
  5546. // };
  5547. VaListDecl->completeDefinition();
  5548. // typedef struct __va_list __builtin_va_list;
  5549. QualType T = Context->getRecordType(VaListDecl);
  5550. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  5551. }
  5552. static TypedefDecl *
  5553. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  5554. // typedef struct __va_list_tag {
  5555. RecordDecl *VaListTagDecl;
  5556. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  5557. VaListTagDecl->startDefinition();
  5558. const size_t NumFields = 4;
  5559. QualType FieldTypes[NumFields];
  5560. const char *FieldNames[NumFields];
  5561. // long __gpr;
  5562. FieldTypes[0] = Context->LongTy;
  5563. FieldNames[0] = "__gpr";
  5564. // long __fpr;
  5565. FieldTypes[1] = Context->LongTy;
  5566. FieldNames[1] = "__fpr";
  5567. // void *__overflow_arg_area;
  5568. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  5569. FieldNames[2] = "__overflow_arg_area";
  5570. // void *__reg_save_area;
  5571. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  5572. FieldNames[3] = "__reg_save_area";
  5573. // Create fields
  5574. for (unsigned i = 0; i < NumFields; ++i) {
  5575. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  5576. VaListTagDecl,
  5577. SourceLocation(),
  5578. SourceLocation(),
  5579. &Context->Idents.get(FieldNames[i]),
  5580. FieldTypes[i], /*TInfo=*/nullptr,
  5581. /*BitWidth=*/nullptr,
  5582. /*Mutable=*/false,
  5583. ICIS_NoInit);
  5584. Field->setAccess(AS_public);
  5585. VaListTagDecl->addDecl(Field);
  5586. }
  5587. VaListTagDecl->completeDefinition();
  5588. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  5589. Context->VaListTagTy = VaListTagType;
  5590. // } __va_list_tag;
  5591. TypedefDecl *VaListTagTypedefDecl =
  5592. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  5593. QualType VaListTagTypedefType =
  5594. Context->getTypedefType(VaListTagTypedefDecl);
  5595. // typedef __va_list_tag __builtin_va_list[1];
  5596. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  5597. QualType VaListTagArrayType
  5598. = Context->getConstantArrayType(VaListTagTypedefType,
  5599. Size, ArrayType::Normal,0);
  5600. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  5601. }
  5602. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  5603. TargetInfo::BuiltinVaListKind Kind) {
  5604. switch (Kind) {
  5605. case TargetInfo::CharPtrBuiltinVaList:
  5606. return CreateCharPtrBuiltinVaListDecl(Context);
  5607. case TargetInfo::VoidPtrBuiltinVaList:
  5608. return CreateVoidPtrBuiltinVaListDecl(Context);
  5609. case TargetInfo::AArch64ABIBuiltinVaList:
  5610. return CreateAArch64ABIBuiltinVaListDecl(Context);
  5611. case TargetInfo::PowerABIBuiltinVaList:
  5612. return CreatePowerABIBuiltinVaListDecl(Context);
  5613. case TargetInfo::X86_64ABIBuiltinVaList:
  5614. return CreateX86_64ABIBuiltinVaListDecl(Context);
  5615. case TargetInfo::PNaClABIBuiltinVaList:
  5616. return CreatePNaClABIBuiltinVaListDecl(Context);
  5617. case TargetInfo::AAPCSABIBuiltinVaList:
  5618. return CreateAAPCSABIBuiltinVaListDecl(Context);
  5619. case TargetInfo::SystemZBuiltinVaList:
  5620. return CreateSystemZBuiltinVaListDecl(Context);
  5621. }
  5622. llvm_unreachable("Unhandled __builtin_va_list type kind");
  5623. }
  5624. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  5625. if (!BuiltinVaListDecl) {
  5626. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  5627. assert(BuiltinVaListDecl->isImplicit());
  5628. }
  5629. return BuiltinVaListDecl;
  5630. }
  5631. QualType ASTContext::getVaListTagType() const {
  5632. // Force the creation of VaListTagTy by building the __builtin_va_list
  5633. // declaration.
  5634. if (VaListTagTy.isNull())
  5635. (void) getBuiltinVaListDecl();
  5636. return VaListTagTy;
  5637. }
  5638. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  5639. assert(ObjCConstantStringType.isNull() &&
  5640. "'NSConstantString' type already set!");
  5641. ObjCConstantStringType = getObjCInterfaceType(Decl);
  5642. }
  5643. /// \brief Retrieve the template name that corresponds to a non-empty
  5644. /// lookup.
  5645. TemplateName
  5646. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  5647. UnresolvedSetIterator End) const {
  5648. unsigned size = End - Begin;
  5649. assert(size > 1 && "set is not overloaded!");
  5650. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  5651. size * sizeof(FunctionTemplateDecl*));
  5652. OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
  5653. NamedDecl **Storage = OT->getStorage();
  5654. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  5655. NamedDecl *D = *I;
  5656. assert(isa<FunctionTemplateDecl>(D) ||
  5657. (isa<UsingShadowDecl>(D) &&
  5658. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  5659. *Storage++ = D;
  5660. }
  5661. return TemplateName(OT);
  5662. }
  5663. /// \brief Retrieve the template name that represents a qualified
  5664. /// template name such as \c std::vector.
  5665. TemplateName
  5666. ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  5667. bool TemplateKeyword,
  5668. TemplateDecl *Template) const {
  5669. assert(NNS && "Missing nested-name-specifier in qualified template name");
  5670. // FIXME: Canonicalization?
  5671. llvm::FoldingSetNodeID ID;
  5672. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  5673. void *InsertPos = nullptr;
  5674. QualifiedTemplateName *QTN =
  5675. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5676. if (!QTN) {
  5677. QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
  5678. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  5679. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  5680. }
  5681. return TemplateName(QTN);
  5682. }
  5683. /// \brief Retrieve the template name that represents a dependent
  5684. /// template name such as \c MetaFun::template apply.
  5685. TemplateName
  5686. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  5687. const IdentifierInfo *Name) const {
  5688. assert((!NNS || NNS->isDependent()) &&
  5689. "Nested name specifier must be dependent");
  5690. llvm::FoldingSetNodeID ID;
  5691. DependentTemplateName::Profile(ID, NNS, Name);
  5692. void *InsertPos = nullptr;
  5693. DependentTemplateName *QTN =
  5694. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5695. if (QTN)
  5696. return TemplateName(QTN);
  5697. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  5698. if (CanonNNS == NNS) {
  5699. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5700. DependentTemplateName(NNS, Name);
  5701. } else {
  5702. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  5703. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5704. DependentTemplateName(NNS, Name, Canon);
  5705. DependentTemplateName *CheckQTN =
  5706. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5707. assert(!CheckQTN && "Dependent type name canonicalization broken");
  5708. (void)CheckQTN;
  5709. }
  5710. DependentTemplateNames.InsertNode(QTN, InsertPos);
  5711. return TemplateName(QTN);
  5712. }
  5713. /// \brief Retrieve the template name that represents a dependent
  5714. /// template name such as \c MetaFun::template operator+.
  5715. TemplateName
  5716. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  5717. OverloadedOperatorKind Operator) const {
  5718. assert((!NNS || NNS->isDependent()) &&
  5719. "Nested name specifier must be dependent");
  5720. llvm::FoldingSetNodeID ID;
  5721. DependentTemplateName::Profile(ID, NNS, Operator);
  5722. void *InsertPos = nullptr;
  5723. DependentTemplateName *QTN
  5724. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5725. if (QTN)
  5726. return TemplateName(QTN);
  5727. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  5728. if (CanonNNS == NNS) {
  5729. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5730. DependentTemplateName(NNS, Operator);
  5731. } else {
  5732. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  5733. QTN = new (*this, llvm::alignOf<DependentTemplateName>())
  5734. DependentTemplateName(NNS, Operator, Canon);
  5735. DependentTemplateName *CheckQTN
  5736. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  5737. assert(!CheckQTN && "Dependent template name canonicalization broken");
  5738. (void)CheckQTN;
  5739. }
  5740. DependentTemplateNames.InsertNode(QTN, InsertPos);
  5741. return TemplateName(QTN);
  5742. }
  5743. TemplateName
  5744. ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
  5745. TemplateName replacement) const {
  5746. llvm::FoldingSetNodeID ID;
  5747. SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
  5748. void *insertPos = nullptr;
  5749. SubstTemplateTemplateParmStorage *subst
  5750. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  5751. if (!subst) {
  5752. subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
  5753. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  5754. }
  5755. return TemplateName(subst);
  5756. }
  5757. TemplateName
  5758. ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
  5759. const TemplateArgument &ArgPack) const {
  5760. ASTContext &Self = const_cast<ASTContext &>(*this);
  5761. llvm::FoldingSetNodeID ID;
  5762. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
  5763. void *InsertPos = nullptr;
  5764. SubstTemplateTemplateParmPackStorage *Subst
  5765. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  5766. if (!Subst) {
  5767. Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
  5768. ArgPack.pack_size(),
  5769. ArgPack.pack_begin());
  5770. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  5771. }
  5772. return TemplateName(Subst);
  5773. }
  5774. /// getFromTargetType - Given one of the integer types provided by
  5775. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  5776. /// is actually a value of type @c TargetInfo::IntType.
  5777. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  5778. switch (Type) {
  5779. case TargetInfo::NoInt: return CanQualType();
  5780. case TargetInfo::SignedChar: return SignedCharTy;
  5781. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  5782. case TargetInfo::SignedShort: return ShortTy;
  5783. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  5784. case TargetInfo::SignedInt: return IntTy;
  5785. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  5786. case TargetInfo::SignedLong: return LongTy;
  5787. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  5788. case TargetInfo::SignedLongLong: return LongLongTy;
  5789. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  5790. }
  5791. llvm_unreachable("Unhandled TargetInfo::IntType value");
  5792. }
  5793. //===----------------------------------------------------------------------===//
  5794. // Type Predicates.
  5795. //===----------------------------------------------------------------------===//
  5796. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  5797. /// garbage collection attribute.
  5798. ///
  5799. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  5800. if (getLangOpts().getGC() == LangOptions::NonGC)
  5801. return Qualifiers::GCNone;
  5802. assert(getLangOpts().ObjC1);
  5803. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  5804. // Default behaviour under objective-C's gc is for ObjC pointers
  5805. // (or pointers to them) be treated as though they were declared
  5806. // as __strong.
  5807. if (GCAttrs == Qualifiers::GCNone) {
  5808. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  5809. return Qualifiers::Strong;
  5810. else if (Ty->isPointerType())
  5811. return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
  5812. } else {
  5813. // It's not valid to set GC attributes on anything that isn't a
  5814. // pointer.
  5815. #ifndef NDEBUG
  5816. QualType CT = Ty->getCanonicalTypeInternal();
  5817. while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
  5818. CT = AT->getElementType();
  5819. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  5820. #endif
  5821. }
  5822. return GCAttrs;
  5823. }
  5824. //===----------------------------------------------------------------------===//
  5825. // Type Compatibility Testing
  5826. //===----------------------------------------------------------------------===//
  5827. /// areCompatVectorTypes - Return true if the two specified vector types are
  5828. /// compatible.
  5829. static bool areCompatVectorTypes(const VectorType *LHS,
  5830. const VectorType *RHS) {
  5831. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  5832. return LHS->getElementType() == RHS->getElementType() &&
  5833. LHS->getNumElements() == RHS->getNumElements();
  5834. }
  5835. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  5836. QualType SecondVec) {
  5837. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  5838. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  5839. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  5840. return true;
  5841. // Treat Neon vector types and most AltiVec vector types as if they are the
  5842. // equivalent GCC vector types.
  5843. const VectorType *First = FirstVec->getAs<VectorType>();
  5844. const VectorType *Second = SecondVec->getAs<VectorType>();
  5845. if (First->getNumElements() == Second->getNumElements() &&
  5846. hasSameType(First->getElementType(), Second->getElementType()) &&
  5847. First->getVectorKind() != VectorType::AltiVecPixel &&
  5848. First->getVectorKind() != VectorType::AltiVecBool &&
  5849. Second->getVectorKind() != VectorType::AltiVecPixel &&
  5850. Second->getVectorKind() != VectorType::AltiVecBool)
  5851. return true;
  5852. return false;
  5853. }
  5854. //===----------------------------------------------------------------------===//
  5855. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  5856. //===----------------------------------------------------------------------===//
  5857. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  5858. /// inheritance hierarchy of 'rProto'.
  5859. bool
  5860. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  5861. ObjCProtocolDecl *rProto) const {
  5862. if (declaresSameEntity(lProto, rProto))
  5863. return true;
  5864. for (auto *PI : rProto->protocols())
  5865. if (ProtocolCompatibleWithProtocol(lProto, PI))
  5866. return true;
  5867. return false;
  5868. }
  5869. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  5870. /// Class<pr1, ...>.
  5871. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
  5872. QualType rhs) {
  5873. const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
  5874. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  5875. assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
  5876. for (auto *lhsProto : lhsQID->quals()) {
  5877. bool match = false;
  5878. for (auto *rhsProto : rhsOPT->quals()) {
  5879. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  5880. match = true;
  5881. break;
  5882. }
  5883. }
  5884. if (!match)
  5885. return false;
  5886. }
  5887. return true;
  5888. }
  5889. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  5890. /// ObjCQualifiedIDType.
  5891. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
  5892. bool compare) {
  5893. // Allow id<P..> and an 'id' or void* type in all cases.
  5894. if (lhs->isVoidPointerType() ||
  5895. lhs->isObjCIdType() || lhs->isObjCClassType())
  5896. return true;
  5897. else if (rhs->isVoidPointerType() ||
  5898. rhs->isObjCIdType() || rhs->isObjCClassType())
  5899. return true;
  5900. if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
  5901. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  5902. if (!rhsOPT) return false;
  5903. if (rhsOPT->qual_empty()) {
  5904. // If the RHS is a unqualified interface pointer "NSString*",
  5905. // make sure we check the class hierarchy.
  5906. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  5907. for (auto *I : lhsQID->quals()) {
  5908. // when comparing an id<P> on lhs with a static type on rhs,
  5909. // see if static class implements all of id's protocols, directly or
  5910. // through its super class and categories.
  5911. if (!rhsID->ClassImplementsProtocol(I, true))
  5912. return false;
  5913. }
  5914. }
  5915. // If there are no qualifiers and no interface, we have an 'id'.
  5916. return true;
  5917. }
  5918. // Both the right and left sides have qualifiers.
  5919. for (auto *lhsProto : lhsQID->quals()) {
  5920. bool match = false;
  5921. // when comparing an id<P> on lhs with a static type on rhs,
  5922. // see if static class implements all of id's protocols, directly or
  5923. // through its super class and categories.
  5924. for (auto *rhsProto : rhsOPT->quals()) {
  5925. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5926. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5927. match = true;
  5928. break;
  5929. }
  5930. }
  5931. // If the RHS is a qualified interface pointer "NSString<P>*",
  5932. // make sure we check the class hierarchy.
  5933. if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
  5934. for (auto *I : lhsQID->quals()) {
  5935. // when comparing an id<P> on lhs with a static type on rhs,
  5936. // see if static class implements all of id's protocols, directly or
  5937. // through its super class and categories.
  5938. if (rhsID->ClassImplementsProtocol(I, true)) {
  5939. match = true;
  5940. break;
  5941. }
  5942. }
  5943. }
  5944. if (!match)
  5945. return false;
  5946. }
  5947. return true;
  5948. }
  5949. const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
  5950. assert(rhsQID && "One of the LHS/RHS should be id<x>");
  5951. if (const ObjCObjectPointerType *lhsOPT =
  5952. lhs->getAsObjCInterfacePointerType()) {
  5953. // If both the right and left sides have qualifiers.
  5954. for (auto *lhsProto : lhsOPT->quals()) {
  5955. bool match = false;
  5956. // when comparing an id<P> on rhs with a static type on lhs,
  5957. // see if static class implements all of id's protocols, directly or
  5958. // through its super class and categories.
  5959. // First, lhs protocols in the qualifier list must be found, direct
  5960. // or indirect in rhs's qualifier list or it is a mismatch.
  5961. for (auto *rhsProto : rhsQID->quals()) {
  5962. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5963. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5964. match = true;
  5965. break;
  5966. }
  5967. }
  5968. if (!match)
  5969. return false;
  5970. }
  5971. // Static class's protocols, or its super class or category protocols
  5972. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  5973. if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
  5974. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  5975. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  5976. // This is rather dubious but matches gcc's behavior. If lhs has
  5977. // no type qualifier and its class has no static protocol(s)
  5978. // assume that it is mismatch.
  5979. if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
  5980. return false;
  5981. for (auto *lhsProto : LHSInheritedProtocols) {
  5982. bool match = false;
  5983. for (auto *rhsProto : rhsQID->quals()) {
  5984. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  5985. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  5986. match = true;
  5987. break;
  5988. }
  5989. }
  5990. if (!match)
  5991. return false;
  5992. }
  5993. }
  5994. return true;
  5995. }
  5996. return false;
  5997. }
  5998. /// canAssignObjCInterfaces - Return true if the two interface types are
  5999. /// compatible for assignment from RHS to LHS. This handles validation of any
  6000. /// protocol qualifiers on the LHS or RHS.
  6001. ///
  6002. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  6003. const ObjCObjectPointerType *RHSOPT) {
  6004. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  6005. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  6006. // If either type represents the built-in 'id' or 'Class' types, return true.
  6007. if (LHS->isObjCUnqualifiedIdOrClass() ||
  6008. RHS->isObjCUnqualifiedIdOrClass())
  6009. return true;
  6010. // Function object that propagates a successful result or handles
  6011. // __kindof types.
  6012. auto finish = [&](bool succeeded) -> bool {
  6013. if (succeeded)
  6014. return true;
  6015. if (!RHS->isKindOfType())
  6016. return false;
  6017. // Strip off __kindof and protocol qualifiers, then check whether
  6018. // we can assign the other way.
  6019. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6020. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  6021. };
  6022. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  6023. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  6024. QualType(RHSOPT,0),
  6025. false));
  6026. }
  6027. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  6028. return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
  6029. QualType(RHSOPT,0)));
  6030. }
  6031. // If we have 2 user-defined types, fall into that path.
  6032. if (LHS->getInterface() && RHS->getInterface()) {
  6033. return finish(canAssignObjCInterfaces(LHS, RHS));
  6034. }
  6035. return false;
  6036. }
  6037. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  6038. /// for providing type-safety for objective-c pointers used to pass/return
  6039. /// arguments in block literals. When passed as arguments, passing 'A*' where
  6040. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  6041. /// not OK. For the return type, the opposite is not OK.
  6042. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  6043. const ObjCObjectPointerType *LHSOPT,
  6044. const ObjCObjectPointerType *RHSOPT,
  6045. bool BlockReturnType) {
  6046. // Function object that propagates a successful result or handles
  6047. // __kindof types.
  6048. auto finish = [&](bool succeeded) -> bool {
  6049. if (succeeded)
  6050. return true;
  6051. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  6052. if (!Expected->isKindOfType())
  6053. return false;
  6054. // Strip off __kindof and protocol qualifiers, then check whether
  6055. // we can assign the other way.
  6056. return canAssignObjCInterfacesInBlockPointer(
  6057. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6058. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  6059. BlockReturnType);
  6060. };
  6061. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  6062. return true;
  6063. if (LHSOPT->isObjCBuiltinType()) {
  6064. return finish(RHSOPT->isObjCBuiltinType() ||
  6065. RHSOPT->isObjCQualifiedIdType());
  6066. }
  6067. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
  6068. return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
  6069. QualType(RHSOPT,0),
  6070. false));
  6071. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  6072. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  6073. if (LHS && RHS) { // We have 2 user-defined types.
  6074. if (LHS != RHS) {
  6075. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  6076. return finish(BlockReturnType);
  6077. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  6078. return finish(!BlockReturnType);
  6079. }
  6080. else
  6081. return true;
  6082. }
  6083. return false;
  6084. }
  6085. /// Comparison routine for Objective-C protocols to be used with
  6086. /// llvm::array_pod_sort.
  6087. static int __cdecl compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs, // HLSL Change - __cdecl
  6088. ObjCProtocolDecl * const *rhs) {
  6089. return (*lhs)->getName().compare((*rhs)->getName());
  6090. }
  6091. /// getIntersectionOfProtocols - This routine finds the intersection of set
  6092. /// of protocols inherited from two distinct objective-c pointer objects with
  6093. /// the given common base.
  6094. /// It is used to build composite qualifier list of the composite type of
  6095. /// the conditional expression involving two objective-c pointer objects.
  6096. static
  6097. void getIntersectionOfProtocols(ASTContext &Context,
  6098. const ObjCInterfaceDecl *CommonBase,
  6099. const ObjCObjectPointerType *LHSOPT,
  6100. const ObjCObjectPointerType *RHSOPT,
  6101. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  6102. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  6103. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  6104. assert(LHS->getInterface() && "LHS must have an interface base");
  6105. assert(RHS->getInterface() && "RHS must have an interface base");
  6106. // Add all of the protocols for the LHS.
  6107. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  6108. // Start with the protocol qualifiers.
  6109. for (auto proto : LHS->quals()) {
  6110. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  6111. }
  6112. // Also add the protocols associated with the LHS interface.
  6113. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  6114. // Add all of the protocls for the RHS.
  6115. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  6116. // Start with the protocol qualifiers.
  6117. for (auto proto : RHS->quals()) {
  6118. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  6119. }
  6120. // Also add the protocols associated with the RHS interface.
  6121. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  6122. // Compute the intersection of the collected protocol sets.
  6123. for (auto proto : LHSProtocolSet) {
  6124. if (RHSProtocolSet.count(proto))
  6125. IntersectionSet.push_back(proto);
  6126. }
  6127. // Compute the set of protocols that is implied by either the common type or
  6128. // the protocols within the intersection.
  6129. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  6130. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  6131. // Remove any implied protocols from the list of inherited protocols.
  6132. if (!ImpliedProtocols.empty()) {
  6133. IntersectionSet.erase(
  6134. std::remove_if(IntersectionSet.begin(),
  6135. IntersectionSet.end(),
  6136. [&](ObjCProtocolDecl *proto) -> bool {
  6137. return ImpliedProtocols.count(proto) > 0;
  6138. }),
  6139. IntersectionSet.end());
  6140. }
  6141. // Sort the remaining protocols by name.
  6142. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  6143. compareObjCProtocolsByName);
  6144. }
  6145. /// Determine whether the first type is a subtype of the second.
  6146. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  6147. QualType rhs) {
  6148. // Common case: two object pointers.
  6149. const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  6150. const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  6151. if (lhsOPT && rhsOPT)
  6152. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  6153. // Two block pointers.
  6154. const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
  6155. const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
  6156. if (lhsBlock && rhsBlock)
  6157. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  6158. // If either is an unqualified 'id' and the other is a block, it's
  6159. // acceptable.
  6160. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  6161. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  6162. return true;
  6163. return false;
  6164. }
  6165. // Check that the given Objective-C type argument lists are equivalent.
  6166. static bool sameObjCTypeArgs(ASTContext &ctx,
  6167. const ObjCInterfaceDecl *iface,
  6168. ArrayRef<QualType> lhsArgs,
  6169. ArrayRef<QualType> rhsArgs,
  6170. bool stripKindOf) {
  6171. if (lhsArgs.size() != rhsArgs.size())
  6172. return false;
  6173. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  6174. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  6175. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  6176. continue;
  6177. switch (typeParams->begin()[i]->getVariance()) {
  6178. case ObjCTypeParamVariance::Invariant:
  6179. if (!stripKindOf ||
  6180. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  6181. rhsArgs[i].stripObjCKindOfType(ctx))) {
  6182. return false;
  6183. }
  6184. break;
  6185. case ObjCTypeParamVariance::Covariant:
  6186. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  6187. return false;
  6188. break;
  6189. case ObjCTypeParamVariance::Contravariant:
  6190. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  6191. return false;
  6192. break;
  6193. }
  6194. }
  6195. return true;
  6196. }
  6197. QualType ASTContext::areCommonBaseCompatible(
  6198. const ObjCObjectPointerType *Lptr,
  6199. const ObjCObjectPointerType *Rptr) {
  6200. const ObjCObjectType *LHS = Lptr->getObjectType();
  6201. const ObjCObjectType *RHS = Rptr->getObjectType();
  6202. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  6203. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  6204. if (!LDecl || !RDecl)
  6205. return QualType();
  6206. // Follow the left-hand side up the class hierarchy until we either hit a
  6207. // root or find the RHS. Record the ancestors in case we don't find it.
  6208. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  6209. LHSAncestors;
  6210. while (true) {
  6211. // Record this ancestor. We'll need this if the common type isn't in the
  6212. // path from the LHS to the root.
  6213. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  6214. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  6215. // Get the type arguments.
  6216. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  6217. bool anyChanges = false;
  6218. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  6219. // Both have type arguments, compare them.
  6220. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  6221. LHS->getTypeArgs(), RHS->getTypeArgs(),
  6222. /*stripKindOf=*/true))
  6223. return QualType();
  6224. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  6225. // If only one has type arguments, the result will not have type
  6226. // arguments.
  6227. LHSTypeArgs = { };
  6228. anyChanges = true;
  6229. }
  6230. // Compute the intersection of protocols.
  6231. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  6232. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  6233. Protocols);
  6234. if (!Protocols.empty())
  6235. anyChanges = true;
  6236. // If anything in the LHS will have changed, build a new result type.
  6237. if (anyChanges) {
  6238. QualType Result = getObjCInterfaceType(LHS->getInterface());
  6239. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  6240. LHS->isKindOfType());
  6241. return getObjCObjectPointerType(Result);
  6242. }
  6243. return getObjCObjectPointerType(QualType(LHS, 0));
  6244. }
  6245. // Find the superclass.
  6246. QualType LHSSuperType = LHS->getSuperClassType();
  6247. if (LHSSuperType.isNull())
  6248. break;
  6249. LHS = LHSSuperType->castAs<ObjCObjectType>();
  6250. }
  6251. // We didn't find anything by following the LHS to its root; now check
  6252. // the RHS against the cached set of ancestors.
  6253. while (true) {
  6254. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  6255. if (KnownLHS != LHSAncestors.end()) {
  6256. LHS = KnownLHS->second;
  6257. // Get the type arguments.
  6258. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  6259. bool anyChanges = false;
  6260. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  6261. // Both have type arguments, compare them.
  6262. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  6263. LHS->getTypeArgs(), RHS->getTypeArgs(),
  6264. /*stripKindOf=*/true))
  6265. return QualType();
  6266. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  6267. // If only one has type arguments, the result will not have type
  6268. // arguments.
  6269. RHSTypeArgs = { };
  6270. anyChanges = true;
  6271. }
  6272. // Compute the intersection of protocols.
  6273. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  6274. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  6275. Protocols);
  6276. if (!Protocols.empty())
  6277. anyChanges = true;
  6278. if (anyChanges) {
  6279. QualType Result = getObjCInterfaceType(RHS->getInterface());
  6280. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  6281. RHS->isKindOfType());
  6282. return getObjCObjectPointerType(Result);
  6283. }
  6284. return getObjCObjectPointerType(QualType(RHS, 0));
  6285. }
  6286. // Find the superclass of the RHS.
  6287. QualType RHSSuperType = RHS->getSuperClassType();
  6288. if (RHSSuperType.isNull())
  6289. break;
  6290. RHS = RHSSuperType->castAs<ObjCObjectType>();
  6291. }
  6292. return QualType();
  6293. }
  6294. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  6295. const ObjCObjectType *RHS) {
  6296. assert(LHS->getInterface() && "LHS is not an interface type");
  6297. assert(RHS->getInterface() && "RHS is not an interface type");
  6298. // Verify that the base decls are compatible: the RHS must be a subclass of
  6299. // the LHS.
  6300. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  6301. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  6302. if (!IsSuperClass)
  6303. return false;
  6304. // If the LHS has protocol qualifiers, determine whether all of them are
  6305. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  6306. // LHS).
  6307. if (LHS->getNumProtocols() > 0) {
  6308. // OK if conversion of LHS to SuperClass results in narrowing of types
  6309. // ; i.e., SuperClass may implement at least one of the protocols
  6310. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  6311. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  6312. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  6313. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  6314. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  6315. // qualifiers.
  6316. for (auto *RHSPI : RHS->quals())
  6317. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  6318. // If there is no protocols associated with RHS, it is not a match.
  6319. if (SuperClassInheritedProtocols.empty())
  6320. return false;
  6321. for (const auto *LHSProto : LHS->quals()) {
  6322. bool SuperImplementsProtocol = false;
  6323. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  6324. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  6325. SuperImplementsProtocol = true;
  6326. break;
  6327. }
  6328. if (!SuperImplementsProtocol)
  6329. return false;
  6330. }
  6331. }
  6332. // If the LHS is specialized, we may need to check type arguments.
  6333. if (LHS->isSpecialized()) {
  6334. // Follow the superclass chain until we've matched the LHS class in the
  6335. // hierarchy. This substitutes type arguments through.
  6336. const ObjCObjectType *RHSSuper = RHS;
  6337. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  6338. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  6339. // If the RHS is specializd, compare type arguments.
  6340. if (RHSSuper->isSpecialized() &&
  6341. !sameObjCTypeArgs(*this, LHS->getInterface(),
  6342. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  6343. /*stripKindOf=*/true)) {
  6344. return false;
  6345. }
  6346. }
  6347. return true;
  6348. }
  6349. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  6350. // get the "pointed to" types
  6351. const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  6352. const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  6353. if (!LHSOPT || !RHSOPT)
  6354. return false;
  6355. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  6356. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  6357. }
  6358. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  6359. return canAssignObjCInterfaces(
  6360. getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
  6361. getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
  6362. }
  6363. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  6364. /// both shall have the identically qualified version of a compatible type.
  6365. /// C99 6.2.7p1: Two types have compatible types if their types are the
  6366. /// same. See 6.7.[2,3,5] for additional rules.
  6367. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  6368. bool CompareUnqualified) {
  6369. if (getLangOpts().CPlusPlus)
  6370. return hasSameType(LHS, RHS);
  6371. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  6372. }
  6373. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  6374. return typesAreCompatible(LHS, RHS);
  6375. }
  6376. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  6377. return !mergeTypes(LHS, RHS, true).isNull();
  6378. }
  6379. /// mergeTransparentUnionType - if T is a transparent union type and a member
  6380. /// of T is compatible with SubType, return the merged type, else return
  6381. /// QualType()
  6382. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  6383. bool OfBlockPointer,
  6384. bool Unqualified) {
  6385. if (const RecordType *UT = T->getAsUnionType()) {
  6386. RecordDecl *UD = UT->getDecl();
  6387. if (UD->hasAttr<TransparentUnionAttr>()) {
  6388. for (const auto *I : UD->fields()) {
  6389. QualType ET = I->getType().getUnqualifiedType();
  6390. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  6391. if (!MT.isNull())
  6392. return MT;
  6393. }
  6394. }
  6395. }
  6396. return QualType();
  6397. }
  6398. /// mergeFunctionParameterTypes - merge two types which appear as function
  6399. /// parameter types
  6400. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  6401. bool OfBlockPointer,
  6402. bool Unqualified) {
  6403. // GNU extension: two types are compatible if they appear as a function
  6404. // argument, one of the types is a transparent union type and the other
  6405. // type is compatible with a union member
  6406. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  6407. Unqualified);
  6408. if (!lmerge.isNull())
  6409. return lmerge;
  6410. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  6411. Unqualified);
  6412. if (!rmerge.isNull())
  6413. return rmerge;
  6414. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  6415. }
  6416. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  6417. bool OfBlockPointer,
  6418. bool Unqualified) {
  6419. const FunctionType *lbase = lhs->getAs<FunctionType>();
  6420. const FunctionType *rbase = rhs->getAs<FunctionType>();
  6421. const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
  6422. const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
  6423. bool allLTypes = true;
  6424. bool allRTypes = true;
  6425. // Check return type
  6426. QualType retType;
  6427. if (OfBlockPointer) {
  6428. QualType RHS = rbase->getReturnType();
  6429. QualType LHS = lbase->getReturnType();
  6430. bool UnqualifiedResult = Unqualified;
  6431. if (!UnqualifiedResult)
  6432. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  6433. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  6434. }
  6435. else
  6436. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  6437. Unqualified);
  6438. if (retType.isNull()) return QualType();
  6439. if (Unqualified)
  6440. retType = retType.getUnqualifiedType();
  6441. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  6442. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  6443. if (Unqualified) {
  6444. LRetType = LRetType.getUnqualifiedType();
  6445. RRetType = RRetType.getUnqualifiedType();
  6446. }
  6447. if (getCanonicalType(retType) != LRetType)
  6448. allLTypes = false;
  6449. if (getCanonicalType(retType) != RRetType)
  6450. allRTypes = false;
  6451. // FIXME: double check this
  6452. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  6453. // rbase->getRegParmAttr() != 0 &&
  6454. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  6455. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  6456. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  6457. // Compatible functions must have compatible calling conventions
  6458. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  6459. return QualType();
  6460. // Regparm is part of the calling convention.
  6461. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  6462. return QualType();
  6463. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  6464. return QualType();
  6465. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  6466. return QualType();
  6467. // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
  6468. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  6469. if (lbaseInfo.getNoReturn() != NoReturn)
  6470. allLTypes = false;
  6471. if (rbaseInfo.getNoReturn() != NoReturn)
  6472. allRTypes = false;
  6473. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  6474. if (lproto && rproto) { // two C99 style function prototypes
  6475. assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
  6476. "C++ shouldn't be here");
  6477. // Compatible functions must have the same number of parameters
  6478. if (lproto->getNumParams() != rproto->getNumParams())
  6479. return QualType();
  6480. // Variadic and non-variadic functions aren't compatible
  6481. if (lproto->isVariadic() != rproto->isVariadic())
  6482. return QualType();
  6483. if (lproto->getTypeQuals() != rproto->getTypeQuals())
  6484. return QualType();
  6485. #if 0 // HLSL Change Starts - no ObjC support
  6486. if (LangOpts.ObjCAutoRefCount &&
  6487. !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
  6488. return QualType();
  6489. #endif // HLSL Change Ends - no ObjC support
  6490. // Check parameter type compatibility
  6491. SmallVector<QualType, 10> types;
  6492. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  6493. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  6494. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  6495. QualType paramType = mergeFunctionParameterTypes(
  6496. lParamType, rParamType, OfBlockPointer, Unqualified);
  6497. if (paramType.isNull())
  6498. return QualType();
  6499. if (Unqualified)
  6500. paramType = paramType.getUnqualifiedType();
  6501. types.push_back(paramType);
  6502. if (Unqualified) {
  6503. lParamType = lParamType.getUnqualifiedType();
  6504. rParamType = rParamType.getUnqualifiedType();
  6505. }
  6506. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  6507. allLTypes = false;
  6508. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  6509. allRTypes = false;
  6510. }
  6511. if (allLTypes) return lhs;
  6512. if (allRTypes) return rhs;
  6513. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  6514. EPI.ExtInfo = einfo;
  6515. return getFunctionType(retType, types, EPI, lproto->getParamMods());
  6516. }
  6517. if (lproto) allRTypes = false;
  6518. if (rproto) allLTypes = false;
  6519. const FunctionProtoType *proto = lproto ? lproto : rproto;
  6520. if (proto) {
  6521. assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
  6522. if (proto->isVariadic()) return QualType();
  6523. // Check that the types are compatible with the types that
  6524. // would result from default argument promotions (C99 6.7.5.3p15).
  6525. // The only types actually affected are promotable integer
  6526. // types and floats, which would be passed as a different
  6527. // type depending on whether the prototype is visible.
  6528. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  6529. QualType paramTy = proto->getParamType(i);
  6530. // Look at the converted type of enum types, since that is the type used
  6531. // to pass enum values.
  6532. if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
  6533. paramTy = Enum->getDecl()->getIntegerType();
  6534. if (paramTy.isNull())
  6535. return QualType();
  6536. }
  6537. if (paramTy->isPromotableIntegerType() ||
  6538. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  6539. return QualType();
  6540. }
  6541. if (allLTypes) return lhs;
  6542. if (allRTypes) return rhs;
  6543. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  6544. EPI.ExtInfo = einfo;
  6545. return getFunctionType(retType, proto->getParamTypes(), EPI, proto->getParamMods());
  6546. }
  6547. if (allLTypes) return lhs;
  6548. if (allRTypes) return rhs;
  6549. return getFunctionNoProtoType(retType, einfo);
  6550. }
  6551. /// Given that we have an enum type and a non-enum type, try to merge them.
  6552. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  6553. QualType other, bool isBlockReturnType) {
  6554. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  6555. // a signed integer type, or an unsigned integer type.
  6556. // Compatibility is based on the underlying type, not the promotion
  6557. // type.
  6558. QualType underlyingType = ET->getDecl()->getIntegerType();
  6559. if (underlyingType.isNull()) return QualType();
  6560. if (Context.hasSameType(underlyingType, other))
  6561. return other;
  6562. // In block return types, we're more permissive and accept any
  6563. // integral type of the same size.
  6564. if (isBlockReturnType && other->isIntegerType() &&
  6565. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  6566. return other;
  6567. return QualType();
  6568. }
  6569. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
  6570. bool OfBlockPointer,
  6571. bool Unqualified, bool BlockReturnType) {
  6572. // C++ [expr]: If an expression initially has the type "reference to T", the
  6573. // type is adjusted to "T" prior to any further analysis, the expression
  6574. // designates the object or function denoted by the reference, and the
  6575. // expression is an lvalue unless the reference is an rvalue reference and
  6576. // the expression is a function call (possibly inside parentheses).
  6577. assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
  6578. assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
  6579. if (Unqualified) {
  6580. LHS = LHS.getUnqualifiedType();
  6581. RHS = RHS.getUnqualifiedType();
  6582. }
  6583. QualType LHSCan = getCanonicalType(LHS),
  6584. RHSCan = getCanonicalType(RHS);
  6585. // If two types are identical, they are compatible.
  6586. if (LHSCan == RHSCan)
  6587. return LHS;
  6588. // If the qualifiers are different, the types aren't compatible... mostly.
  6589. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  6590. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  6591. if (LQuals != RQuals) {
  6592. // If any of these qualifiers are different, we have a type
  6593. // mismatch.
  6594. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  6595. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  6596. LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
  6597. return QualType();
  6598. // Exactly one GC qualifier difference is allowed: __strong is
  6599. // okay if the other type has no GC qualifier but is an Objective
  6600. // C object pointer (i.e. implicitly strong by default). We fix
  6601. // this by pretending that the unqualified type was actually
  6602. // qualified __strong.
  6603. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  6604. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  6605. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  6606. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  6607. return QualType();
  6608. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  6609. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  6610. }
  6611. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  6612. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  6613. }
  6614. return QualType();
  6615. }
  6616. // Okay, qualifiers are equal.
  6617. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  6618. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  6619. // We want to consider the two function types to be the same for these
  6620. // comparisons, just force one to the other.
  6621. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  6622. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  6623. // Same as above for arrays
  6624. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  6625. LHSClass = Type::ConstantArray;
  6626. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  6627. RHSClass = Type::ConstantArray;
  6628. // ObjCInterfaces are just specialized ObjCObjects.
  6629. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  6630. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  6631. // Canonicalize ExtVector -> Vector.
  6632. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  6633. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  6634. // If the canonical type classes don't match.
  6635. if (LHSClass != RHSClass) {
  6636. // Note that we only have special rules for turning block enum
  6637. // returns into block int returns, not vice-versa.
  6638. if (const EnumType* ETy = LHS->getAs<EnumType>()) {
  6639. return mergeEnumWithInteger(*this, ETy, RHS, false);
  6640. }
  6641. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  6642. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  6643. }
  6644. // allow block pointer type to match an 'id' type.
  6645. if (OfBlockPointer && !BlockReturnType) {
  6646. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  6647. return LHS;
  6648. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  6649. return RHS;
  6650. }
  6651. return QualType();
  6652. }
  6653. // The canonical type classes match.
  6654. switch (LHSClass) {
  6655. #define TYPE(Class, Base)
  6656. #define ABSTRACT_TYPE(Class, Base)
  6657. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  6658. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  6659. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  6660. #include "clang/AST/TypeNodes.def"
  6661. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  6662. case Type::Auto:
  6663. case Type::LValueReference:
  6664. case Type::RValueReference:
  6665. case Type::MemberPointer:
  6666. llvm_unreachable("C++ should never be in mergeTypes");
  6667. case Type::ObjCInterface:
  6668. case Type::IncompleteArray:
  6669. case Type::VariableArray:
  6670. case Type::FunctionProto:
  6671. case Type::ExtVector:
  6672. llvm_unreachable("Types are eliminated above");
  6673. case Type::Pointer:
  6674. {
  6675. // Merge two pointer types, while trying to preserve typedef info
  6676. QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
  6677. QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
  6678. if (Unqualified) {
  6679. LHSPointee = LHSPointee.getUnqualifiedType();
  6680. RHSPointee = RHSPointee.getUnqualifiedType();
  6681. }
  6682. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  6683. Unqualified);
  6684. if (ResultType.isNull()) return QualType();
  6685. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  6686. return LHS;
  6687. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  6688. return RHS;
  6689. return getPointerType(ResultType);
  6690. }
  6691. case Type::BlockPointer:
  6692. {
  6693. // Merge two block pointer types, while trying to preserve typedef info
  6694. QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
  6695. QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
  6696. if (Unqualified) {
  6697. LHSPointee = LHSPointee.getUnqualifiedType();
  6698. RHSPointee = RHSPointee.getUnqualifiedType();
  6699. }
  6700. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  6701. Unqualified);
  6702. if (ResultType.isNull()) return QualType();
  6703. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  6704. return LHS;
  6705. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  6706. return RHS;
  6707. return getBlockPointerType(ResultType);
  6708. }
  6709. case Type::Atomic:
  6710. {
  6711. // Merge two pointer types, while trying to preserve typedef info
  6712. QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
  6713. QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
  6714. if (Unqualified) {
  6715. LHSValue = LHSValue.getUnqualifiedType();
  6716. RHSValue = RHSValue.getUnqualifiedType();
  6717. }
  6718. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  6719. Unqualified);
  6720. if (ResultType.isNull()) return QualType();
  6721. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  6722. return LHS;
  6723. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  6724. return RHS;
  6725. return getAtomicType(ResultType);
  6726. }
  6727. case Type::ConstantArray:
  6728. {
  6729. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  6730. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  6731. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  6732. return QualType();
  6733. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  6734. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  6735. if (Unqualified) {
  6736. LHSElem = LHSElem.getUnqualifiedType();
  6737. RHSElem = RHSElem.getUnqualifiedType();
  6738. }
  6739. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  6740. if (ResultType.isNull()) return QualType();
  6741. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  6742. return LHS;
  6743. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  6744. return RHS;
  6745. if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
  6746. ArrayType::ArraySizeModifier(), 0);
  6747. if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
  6748. ArrayType::ArraySizeModifier(), 0);
  6749. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  6750. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  6751. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  6752. return LHS;
  6753. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  6754. return RHS;
  6755. if (LVAT) {
  6756. // FIXME: This isn't correct! But tricky to implement because
  6757. // the array's size has to be the size of LHS, but the type
  6758. // has to be different.
  6759. return LHS;
  6760. }
  6761. if (RVAT) {
  6762. // FIXME: This isn't correct! But tricky to implement because
  6763. // the array's size has to be the size of RHS, but the type
  6764. // has to be different.
  6765. return RHS;
  6766. }
  6767. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  6768. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  6769. return getIncompleteArrayType(ResultType,
  6770. ArrayType::ArraySizeModifier(), 0);
  6771. }
  6772. case Type::FunctionNoProto:
  6773. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
  6774. case Type::Record:
  6775. case Type::Enum:
  6776. return QualType();
  6777. case Type::Builtin:
  6778. // Only exactly equal builtin types are compatible, which is tested above.
  6779. return QualType();
  6780. case Type::Complex:
  6781. // Distinct complex types are incompatible.
  6782. return QualType();
  6783. case Type::Vector:
  6784. // FIXME: The merged type should be an ExtVector!
  6785. if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
  6786. RHSCan->getAs<VectorType>()))
  6787. return LHS;
  6788. return QualType();
  6789. case Type::ObjCObject: {
  6790. // Check if the types are assignment compatible.
  6791. // FIXME: This should be type compatibility, e.g. whether
  6792. // "LHS x; RHS x;" at global scope is legal.
  6793. const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
  6794. const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
  6795. if (canAssignObjCInterfaces(LHSIface, RHSIface))
  6796. return LHS;
  6797. return QualType();
  6798. }
  6799. case Type::ObjCObjectPointer: {
  6800. if (OfBlockPointer) {
  6801. if (canAssignObjCInterfacesInBlockPointer(
  6802. LHS->getAs<ObjCObjectPointerType>(),
  6803. RHS->getAs<ObjCObjectPointerType>(),
  6804. BlockReturnType))
  6805. return LHS;
  6806. return QualType();
  6807. }
  6808. if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
  6809. RHS->getAs<ObjCObjectPointerType>()))
  6810. return LHS;
  6811. return QualType();
  6812. }
  6813. }
  6814. llvm_unreachable("Invalid Type::Class!");
  6815. }
  6816. bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
  6817. const FunctionProtoType *FromFunctionType,
  6818. const FunctionProtoType *ToFunctionType) {
  6819. if (FromFunctionType->hasAnyConsumedParams() !=
  6820. ToFunctionType->hasAnyConsumedParams())
  6821. return false;
  6822. FunctionProtoType::ExtProtoInfo FromEPI =
  6823. FromFunctionType->getExtProtoInfo();
  6824. FunctionProtoType::ExtProtoInfo ToEPI =
  6825. ToFunctionType->getExtProtoInfo();
  6826. if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
  6827. for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
  6828. if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
  6829. return false;
  6830. }
  6831. return true;
  6832. }
  6833. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  6834. /// 'RHS' attributes and returns the merged version; including for function
  6835. /// return types.
  6836. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  6837. QualType LHSCan = getCanonicalType(LHS),
  6838. RHSCan = getCanonicalType(RHS);
  6839. // If two types are identical, they are compatible.
  6840. if (LHSCan == RHSCan)
  6841. return LHS;
  6842. if (RHSCan->isFunctionType()) {
  6843. if (!LHSCan->isFunctionType())
  6844. return QualType();
  6845. QualType OldReturnType =
  6846. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  6847. QualType NewReturnType =
  6848. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  6849. QualType ResReturnType =
  6850. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  6851. if (ResReturnType.isNull())
  6852. return QualType();
  6853. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  6854. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  6855. // In either case, use OldReturnType to build the new function type.
  6856. const FunctionType *F = LHS->getAs<FunctionType>();
  6857. if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
  6858. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  6859. EPI.ExtInfo = getFunctionExtInfo(LHS);
  6860. QualType ResultType =
  6861. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI, ArrayRef<hlsl::ParameterModifier>()); // HLSL Change
  6862. return ResultType;
  6863. }
  6864. }
  6865. return QualType();
  6866. }
  6867. // If the qualifiers are different, the types can still be merged.
  6868. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  6869. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  6870. if (LQuals != RQuals) {
  6871. // If any of these qualifiers are different, we have a type mismatch.
  6872. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  6873. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  6874. return QualType();
  6875. // Exactly one GC qualifier difference is allowed: __strong is
  6876. // okay if the other type has no GC qualifier but is an Objective
  6877. // C object pointer (i.e. implicitly strong by default). We fix
  6878. // this by pretending that the unqualified type was actually
  6879. // qualified __strong.
  6880. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  6881. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  6882. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  6883. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  6884. return QualType();
  6885. if (GC_L == Qualifiers::Strong)
  6886. return LHS;
  6887. if (GC_R == Qualifiers::Strong)
  6888. return RHS;
  6889. return QualType();
  6890. }
  6891. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  6892. QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  6893. QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
  6894. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  6895. if (ResQT == LHSBaseQT)
  6896. return LHS;
  6897. if (ResQT == RHSBaseQT)
  6898. return RHS;
  6899. }
  6900. return QualType();
  6901. }
  6902. //===----------------------------------------------------------------------===//
  6903. // Integer Predicates
  6904. //===----------------------------------------------------------------------===//
  6905. unsigned ASTContext::getIntWidth(QualType T) const {
  6906. if (const EnumType *ET = T->getAs<EnumType>())
  6907. T = ET->getDecl()->getIntegerType();
  6908. if (T->isBooleanType())
  6909. return 1;
  6910. // For builtin types, just use the standard type sizing method
  6911. return (unsigned)getTypeSize(T);
  6912. }
  6913. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  6914. assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
  6915. // Turn <4 x signed int> -> <4 x unsigned int>
  6916. if (const VectorType *VTy = T->getAs<VectorType>())
  6917. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  6918. VTy->getNumElements(), VTy->getVectorKind());
  6919. // For enums, we return the unsigned version of the base type.
  6920. if (const EnumType *ETy = T->getAs<EnumType>())
  6921. T = ETy->getDecl()->getIntegerType();
  6922. const BuiltinType *BTy = T->getAs<BuiltinType>();
  6923. assert(BTy && "Unexpected signed integer type");
  6924. switch (BTy->getKind()) {
  6925. case BuiltinType::Char_S:
  6926. case BuiltinType::SChar:
  6927. return UnsignedCharTy;
  6928. case BuiltinType::Short:
  6929. return UnsignedShortTy;
  6930. case BuiltinType::Int:
  6931. return UnsignedIntTy;
  6932. case BuiltinType::Long:
  6933. return UnsignedLongTy;
  6934. case BuiltinType::LongLong:
  6935. return UnsignedLongLongTy;
  6936. case BuiltinType::Int128:
  6937. return UnsignedInt128Ty;
  6938. case BuiltinType::LitInt: // HLSL Change
  6939. return UnsignedIntTy;
  6940. default:
  6941. llvm_unreachable("Unexpected signed integer type");
  6942. }
  6943. }
  6944. ASTMutationListener::~ASTMutationListener() { }
  6945. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  6946. QualType ReturnType) {}
  6947. //===----------------------------------------------------------------------===//
  6948. // Builtin Type Computation
  6949. //===----------------------------------------------------------------------===//
  6950. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  6951. /// pointer over the consumed characters. This returns the resultant type. If
  6952. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  6953. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  6954. /// a vector of "i*".
  6955. ///
  6956. /// RequiresICE is filled in on return to indicate whether the value is required
  6957. /// to be an Integer Constant Expression.
  6958. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  6959. ASTContext::GetBuiltinTypeError &Error,
  6960. bool &RequiresICE,
  6961. bool AllowTypeModifiers) {
  6962. // Modifiers.
  6963. int HowLong = 0;
  6964. bool Signed = false, Unsigned = false;
  6965. RequiresICE = false;
  6966. // Read the prefixed modifiers first.
  6967. bool Done = false;
  6968. while (!Done) {
  6969. switch (*Str++) {
  6970. default: Done = true; --Str; break;
  6971. case 'I':
  6972. RequiresICE = true;
  6973. break;
  6974. case 'S':
  6975. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  6976. assert(!Signed && "Can't use 'S' modifier multiple times!");
  6977. Signed = true;
  6978. break;
  6979. case 'U':
  6980. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  6981. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  6982. Unsigned = true;
  6983. break;
  6984. case 'L':
  6985. assert(HowLong <= 2 && "Can't have LLLL modifier");
  6986. ++HowLong;
  6987. break;
  6988. case 'W':
  6989. // This modifier represents int64 type.
  6990. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  6991. switch (Context.getTargetInfo().getInt64Type()) {
  6992. default:
  6993. llvm_unreachable("Unexpected integer type");
  6994. case TargetInfo::SignedLong:
  6995. HowLong = 1;
  6996. break;
  6997. case TargetInfo::SignedLongLong:
  6998. HowLong = 2;
  6999. break;
  7000. }
  7001. }
  7002. }
  7003. QualType Type;
  7004. // Read the base type.
  7005. switch (*Str++) {
  7006. default: llvm_unreachable("Unknown builtin type letter!");
  7007. case 'v':
  7008. assert(HowLong == 0 && !Signed && !Unsigned &&
  7009. "Bad modifiers used with 'v'!");
  7010. Type = Context.VoidTy;
  7011. break;
  7012. case 'h':
  7013. assert(HowLong == 0 && !Signed && !Unsigned &&
  7014. "Bad modifiers used with 'h'!");
  7015. Type = Context.HalfTy;
  7016. break;
  7017. case 'f':
  7018. assert(HowLong == 0 && !Signed && !Unsigned &&
  7019. "Bad modifiers used with 'f'!");
  7020. Type = Context.FloatTy;
  7021. break;
  7022. case 'd':
  7023. assert(HowLong < 2 && !Signed && !Unsigned &&
  7024. "Bad modifiers used with 'd'!");
  7025. if (HowLong)
  7026. Type = Context.LongDoubleTy;
  7027. else
  7028. Type = Context.DoubleTy;
  7029. break;
  7030. case 's':
  7031. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  7032. if (Unsigned)
  7033. Type = Context.UnsignedShortTy;
  7034. else
  7035. Type = Context.ShortTy;
  7036. break;
  7037. case 'i':
  7038. if (HowLong == 3)
  7039. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  7040. else if (HowLong == 2)
  7041. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  7042. else if (HowLong == 1)
  7043. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  7044. else
  7045. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  7046. break;
  7047. case 'c':
  7048. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  7049. if (Signed)
  7050. Type = Context.SignedCharTy;
  7051. else if (Unsigned)
  7052. Type = Context.UnsignedCharTy;
  7053. else
  7054. Type = Context.CharTy;
  7055. break;
  7056. case 'b': // boolean
  7057. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  7058. Type = Context.BoolTy;
  7059. break;
  7060. case 'z': // size_t.
  7061. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  7062. Type = Context.getSizeType();
  7063. break;
  7064. case 'F':
  7065. Type = Context.getCFConstantStringType();
  7066. break;
  7067. case 'G':
  7068. Type = Context.getObjCIdType();
  7069. break;
  7070. case 'H':
  7071. Type = Context.getObjCSelType();
  7072. break;
  7073. case 'M':
  7074. Type = Context.getObjCSuperType();
  7075. break;
  7076. case 'a':
  7077. Type = Context.getBuiltinVaListType();
  7078. assert(!Type.isNull() && "builtin va list type not initialized!");
  7079. break;
  7080. case 'A':
  7081. // This is a "reference" to a va_list; however, what exactly
  7082. // this means depends on how va_list is defined. There are two
  7083. // different kinds of va_list: ones passed by value, and ones
  7084. // passed by reference. An example of a by-value va_list is
  7085. // x86, where va_list is a char*. An example of by-ref va_list
  7086. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  7087. // we want this argument to be a char*&; for x86-64, we want
  7088. // it to be a __va_list_tag*.
  7089. Type = Context.getBuiltinVaListType();
  7090. assert(!Type.isNull() && "builtin va list type not initialized!");
  7091. if (Type->isArrayType())
  7092. Type = Context.getArrayDecayedType(Type);
  7093. else
  7094. Type = Context.getLValueReferenceType(Type);
  7095. break;
  7096. case 'V': {
  7097. char *End;
  7098. unsigned NumElements = strtoul(Str, &End, 10);
  7099. assert(End != Str && "Missing vector size");
  7100. Str = End;
  7101. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  7102. RequiresICE, false);
  7103. assert(!RequiresICE && "Can't require vector ICE");
  7104. // TODO: No way to make AltiVec vectors in builtins yet.
  7105. Type = Context.getVectorType(ElementType, NumElements,
  7106. VectorType::GenericVector);
  7107. break;
  7108. }
  7109. case 'E': {
  7110. char *End;
  7111. unsigned NumElements = strtoul(Str, &End, 10);
  7112. assert(End != Str && "Missing vector size");
  7113. Str = End;
  7114. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  7115. false);
  7116. Type = Context.getExtVectorType(ElementType, NumElements);
  7117. break;
  7118. }
  7119. case 'X': {
  7120. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  7121. false);
  7122. assert(!RequiresICE && "Can't require complex ICE");
  7123. Type = Context.getComplexType(ElementType);
  7124. break;
  7125. }
  7126. case 'Y' : {
  7127. Type = Context.getPointerDiffType();
  7128. break;
  7129. }
  7130. case 'P':
  7131. Type = Context.getFILEType();
  7132. if (Type.isNull()) {
  7133. Error = ASTContext::GE_Missing_stdio;
  7134. return QualType();
  7135. }
  7136. break;
  7137. case 'J':
  7138. if (Signed)
  7139. Type = Context.getsigjmp_bufType();
  7140. else
  7141. Type = Context.getjmp_bufType();
  7142. if (Type.isNull()) {
  7143. Error = ASTContext::GE_Missing_setjmp;
  7144. return QualType();
  7145. }
  7146. break;
  7147. case 'K':
  7148. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  7149. Type = Context.getucontext_tType();
  7150. if (Type.isNull()) {
  7151. Error = ASTContext::GE_Missing_ucontext;
  7152. return QualType();
  7153. }
  7154. break;
  7155. case 'p':
  7156. Type = Context.getProcessIDType();
  7157. break;
  7158. }
  7159. // If there are modifiers and if we're allowed to parse them, go for it.
  7160. Done = !AllowTypeModifiers;
  7161. while (!Done) {
  7162. switch (char c = *Str++) {
  7163. default: Done = true; --Str; break;
  7164. case '*':
  7165. case '&': {
  7166. // Both pointers and references can have their pointee types
  7167. // qualified with an address space.
  7168. char *End;
  7169. unsigned AddrSpace = strtoul(Str, &End, 10);
  7170. if (End != Str && AddrSpace != 0) {
  7171. Type = Context.getAddrSpaceQualType(Type, AddrSpace);
  7172. Str = End;
  7173. }
  7174. if (c == '*')
  7175. Type = Context.getPointerType(Type);
  7176. else
  7177. Type = Context.getLValueReferenceType(Type);
  7178. break;
  7179. }
  7180. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  7181. case 'C':
  7182. Type = Type.withConst();
  7183. break;
  7184. case 'D':
  7185. Type = Context.getVolatileType(Type);
  7186. break;
  7187. case 'R':
  7188. Type = Type.withRestrict();
  7189. break;
  7190. }
  7191. }
  7192. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  7193. "Integer constant 'I' type must be an integer");
  7194. return Type;
  7195. }
  7196. /// GetBuiltinType - Return the type for the specified builtin.
  7197. QualType ASTContext::GetBuiltinType(unsigned Id,
  7198. GetBuiltinTypeError &Error,
  7199. unsigned *IntegerConstantArgs) const {
  7200. const char *TypeStr = BuiltinInfo.GetTypeString(Id);
  7201. SmallVector<QualType, 8> ArgTypes;
  7202. bool RequiresICE = false;
  7203. Error = GE_None;
  7204. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  7205. RequiresICE, true);
  7206. if (Error != GE_None)
  7207. return QualType();
  7208. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  7209. while (TypeStr[0] && TypeStr[0] != '.') {
  7210. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  7211. if (Error != GE_None)
  7212. return QualType();
  7213. // If this argument is required to be an IntegerConstantExpression and the
  7214. // caller cares, fill in the bitmask we return.
  7215. if (RequiresICE && IntegerConstantArgs)
  7216. *IntegerConstantArgs |= 1 << ArgTypes.size();
  7217. // Do array -> pointer decay. The builtin should use the decayed type.
  7218. if (Ty->isArrayType())
  7219. Ty = getArrayDecayedType(Ty);
  7220. ArgTypes.push_back(Ty);
  7221. }
  7222. if (Id == Builtin::BI__GetExceptionInfo)
  7223. return QualType();
  7224. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  7225. "'.' should only occur at end of builtin type list!");
  7226. FunctionType::ExtInfo EI(CC_C);
  7227. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  7228. bool Variadic = (TypeStr[0] == '.');
  7229. // We really shouldn't be making a no-proto type here, especially in C++.
  7230. if (ArgTypes.empty() && Variadic)
  7231. return getFunctionNoProtoType(ResType, EI);
  7232. FunctionProtoType::ExtProtoInfo EPI;
  7233. EPI.ExtInfo = EI;
  7234. EPI.Variadic = Variadic;
  7235. // HLSL Change: add empty parameter modifier; but this should probably be removed altogether
  7236. return getFunctionType(ResType, ArgTypes, EPI, ArrayRef<hlsl::ParameterModifier>());
  7237. }
  7238. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  7239. const FunctionDecl *FD) {
  7240. if (!FD->isExternallyVisible())
  7241. return GVA_Internal;
  7242. GVALinkage External = GVA_StrongExternal;
  7243. switch (FD->getTemplateSpecializationKind()) {
  7244. case TSK_Undeclared:
  7245. case TSK_ExplicitSpecialization:
  7246. External = GVA_StrongExternal;
  7247. break;
  7248. case TSK_ExplicitInstantiationDefinition:
  7249. return GVA_StrongODR;
  7250. // C++11 [temp.explicit]p10:
  7251. // [ Note: The intent is that an inline function that is the subject of
  7252. // an explicit instantiation declaration will still be implicitly
  7253. // instantiated when used so that the body can be considered for
  7254. // inlining, but that no out-of-line copy of the inline function would be
  7255. // generated in the translation unit. -- end note ]
  7256. case TSK_ExplicitInstantiationDeclaration:
  7257. return GVA_AvailableExternally;
  7258. case TSK_ImplicitInstantiation:
  7259. External = GVA_DiscardableODR;
  7260. break;
  7261. }
  7262. if (!FD->isInlined())
  7263. return External;
  7264. if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
  7265. !FD->hasAttr<DLLExportAttr>()) ||
  7266. FD->hasAttr<GNUInlineAttr>()) {
  7267. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  7268. // GNU or C99 inline semantics. Determine whether this symbol should be
  7269. // externally visible.
  7270. if (FD->isInlineDefinitionExternallyVisible())
  7271. return External;
  7272. // C99 inline semantics, where the symbol is not externally visible.
  7273. return GVA_AvailableExternally;
  7274. }
  7275. // Functions specified with extern and inline in -fms-compatibility mode
  7276. // forcibly get emitted. While the body of the function cannot be later
  7277. // replaced, the function definition cannot be discarded.
  7278. if (FD->isMSExternInline())
  7279. return GVA_StrongODR;
  7280. return GVA_DiscardableODR;
  7281. }
  7282. static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
  7283. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  7284. // dllexport/dllimport on inline functions.
  7285. if (D->hasAttr<DLLImportAttr>()) {
  7286. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  7287. return GVA_AvailableExternally;
  7288. } else if (D->hasAttr<DLLExportAttr>()) {
  7289. if (L == GVA_DiscardableODR)
  7290. return GVA_StrongODR;
  7291. }
  7292. return L;
  7293. }
  7294. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  7295. return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
  7296. FD);
  7297. }
  7298. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  7299. const VarDecl *VD) {
  7300. if (!VD->isExternallyVisible())
  7301. return GVA_Internal;
  7302. // HLSL Change Starts - samplers, textures and UAVs should be removed if
  7303. // unused, and fit an 'available externally' model.
  7304. if (hlsl::DXIL::ResourceClass::Invalid !=
  7305. hlsl::GetResourceClassForType(Context, VD->getType())) {
  7306. return GVA_AvailableExternally;
  7307. }
  7308. // HLSL Change Ends
  7309. if (VD->isStaticLocal()) {
  7310. GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
  7311. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  7312. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  7313. LexicalContext = LexicalContext->getLexicalParent();
  7314. // Let the static local variable inherit its linkage from the nearest
  7315. // enclosing function.
  7316. if (LexicalContext)
  7317. StaticLocalLinkage =
  7318. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  7319. // GVA_StrongODR function linkage is stronger than what we need,
  7320. // downgrade to GVA_DiscardableODR.
  7321. // This allows us to discard the variable if we never end up needing it.
  7322. return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
  7323. : StaticLocalLinkage;
  7324. }
  7325. // MSVC treats in-class initialized static data members as definitions.
  7326. // By giving them non-strong linkage, out-of-line definitions won't
  7327. // cause link errors.
  7328. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  7329. return GVA_DiscardableODR;
  7330. switch (VD->getTemplateSpecializationKind()) {
  7331. case TSK_Undeclared:
  7332. case TSK_ExplicitSpecialization:
  7333. return GVA_StrongExternal;
  7334. case TSK_ExplicitInstantiationDefinition:
  7335. return GVA_StrongODR;
  7336. case TSK_ExplicitInstantiationDeclaration:
  7337. return GVA_AvailableExternally;
  7338. case TSK_ImplicitInstantiation:
  7339. return GVA_DiscardableODR;
  7340. }
  7341. llvm_unreachable("Invalid Linkage!");
  7342. }
  7343. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  7344. return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
  7345. VD);
  7346. }
  7347. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  7348. if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
  7349. if (!VD->isFileVarDecl())
  7350. return false;
  7351. // Global named register variables (GNU extension) are never emitted.
  7352. if (VD->getStorageClass() == SC_Register)
  7353. return false;
  7354. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7355. // We never need to emit an uninstantiated function template.
  7356. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  7357. return false;
  7358. } else if (isa<OMPThreadPrivateDecl>(D))
  7359. return true;
  7360. else
  7361. return false;
  7362. // If this is a member of a class template, we do not need to emit it.
  7363. if (D->getDeclContext()->isDependentContext())
  7364. return false;
  7365. // Weak references don't produce any output by themselves.
  7366. if (D->hasAttr<WeakRefAttr>())
  7367. return false;
  7368. // Aliases and used decls are required.
  7369. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  7370. return true;
  7371. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  7372. // Forward declarations aren't required.
  7373. if (!FD->doesThisDeclarationHaveABody())
  7374. return FD->doesDeclarationForceExternallyVisibleDefinition();
  7375. // Constructors and destructors are required.
  7376. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  7377. return true;
  7378. // The key function for a class is required. This rule only comes
  7379. // into play when inline functions can be key functions, though.
  7380. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  7381. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  7382. const CXXRecordDecl *RD = MD->getParent();
  7383. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  7384. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  7385. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  7386. return true;
  7387. }
  7388. }
  7389. }
  7390. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  7391. // static, static inline, always_inline, and extern inline functions can
  7392. // always be deferred. Normal inline functions can be deferred in C99/C++.
  7393. // Implicit template instantiations can also be deferred in C++.
  7394. if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
  7395. Linkage == GVA_DiscardableODR)
  7396. return false;
  7397. // HLSL Change Starts
  7398. // Don't just return true because of visibility, unless building a library
  7399. return FD->getName() == getLangOpts().HLSLEntryFunction ||
  7400. IsPatchConstantFunctionDecl(FD) || getLangOpts().IsHLSLLibrary;
  7401. // HLSL Change Ends
  7402. }
  7403. const VarDecl *VD = cast<VarDecl>(D);
  7404. assert(VD->isFileVarDecl() && "Expected file scoped var");
  7405. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  7406. !isMSStaticDataMemberInlineDefinition(VD))
  7407. return false;
  7408. // Variables that can be needed in other TUs are required.
  7409. GVALinkage L = GetGVALinkageForVariable(VD);
  7410. if (L != GVA_Internal && L != GVA_AvailableExternally &&
  7411. L != GVA_DiscardableODR)
  7412. return true;
  7413. // Variables that have destruction with side-effects are required.
  7414. if (VD->getType().isDestructedType())
  7415. return true;
  7416. // Variables that have initialization with side-effects are required.
  7417. if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
  7418. return true;
  7419. return false;
  7420. }
  7421. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  7422. bool IsCXXMethod) const {
  7423. // Pass through to the C++ ABI object
  7424. if (IsCXXMethod)
  7425. return ABI->getDefaultMethodCallConv(IsVariadic);
  7426. if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
  7427. return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
  7428. }
  7429. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  7430. // Pass through to the C++ ABI object
  7431. return ABI->isNearlyEmpty(RD);
  7432. }
  7433. VTableContextBase *ASTContext::getVTableContext() {
  7434. if (!VTContext.get()) {
  7435. if (Target->getCXXABI().isMicrosoft())
  7436. VTContext.reset(new MicrosoftVTableContext(*this));
  7437. else
  7438. VTContext.reset(new ItaniumVTableContext(*this));
  7439. }
  7440. return VTContext.get();
  7441. }
  7442. MangleContext *ASTContext::createMangleContext() {
  7443. switch (Target->getCXXABI().getKind()) {
  7444. case TargetCXXABI::GenericAArch64:
  7445. case TargetCXXABI::GenericItanium:
  7446. case TargetCXXABI::GenericARM:
  7447. case TargetCXXABI::GenericMIPS:
  7448. case TargetCXXABI::iOS:
  7449. case TargetCXXABI::iOS64:
  7450. return ItaniumMangleContext::create(*this, getDiagnostics());
  7451. case TargetCXXABI::Microsoft:
  7452. return MicrosoftMangleContext::create(*this, getDiagnostics());
  7453. }
  7454. llvm_unreachable("Unsupported ABI");
  7455. }
  7456. CXXABI::~CXXABI() {}
  7457. size_t ASTContext::getSideTableAllocatedMemory() const {
  7458. return ASTRecordLayouts.getMemorySize() +
  7459. llvm::capacity_in_bytes(ObjCLayouts) +
  7460. llvm::capacity_in_bytes(KeyFunctions) +
  7461. llvm::capacity_in_bytes(ObjCImpls) +
  7462. llvm::capacity_in_bytes(BlockVarCopyInits) +
  7463. llvm::capacity_in_bytes(DeclAttrs) +
  7464. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  7465. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  7466. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  7467. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  7468. llvm::capacity_in_bytes(OverriddenMethods) +
  7469. llvm::capacity_in_bytes(Types) +
  7470. llvm::capacity_in_bytes(VariableArrayTypes) +
  7471. llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
  7472. }
  7473. /// getIntTypeForBitwidth -
  7474. /// sets integer QualTy according to specified details:
  7475. /// bitwidth, signed/unsigned.
  7476. /// Returns empty type if there is no appropriate target types.
  7477. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  7478. unsigned Signed) const {
  7479. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  7480. CanQualType QualTy = getFromTargetType(Ty);
  7481. if (!QualTy && DestWidth == 128)
  7482. return Signed ? Int128Ty : UnsignedInt128Ty;
  7483. return QualTy;
  7484. }
  7485. /// getRealTypeForBitwidth -
  7486. /// sets floating point QualTy according to specified bitwidth.
  7487. /// Returns empty type if there is no appropriate target types.
  7488. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
  7489. TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
  7490. switch (Ty) {
  7491. case TargetInfo::Float:
  7492. return FloatTy;
  7493. case TargetInfo::Double:
  7494. return DoubleTy;
  7495. case TargetInfo::LongDouble:
  7496. return LongDoubleTy;
  7497. case TargetInfo::NoFloat:
  7498. return QualType();
  7499. }
  7500. llvm_unreachable("Unhandled TargetInfo::RealType value");
  7501. }
  7502. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  7503. if (Number > 1)
  7504. MangleNumbers[ND] = Number;
  7505. }
  7506. unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
  7507. llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
  7508. MangleNumbers.find(ND);
  7509. return I != MangleNumbers.end() ? I->second : 1;
  7510. }
  7511. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  7512. if (Number > 1)
  7513. StaticLocalNumbers[VD] = Number;
  7514. }
  7515. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  7516. llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
  7517. StaticLocalNumbers.find(VD);
  7518. return I != StaticLocalNumbers.end() ? I->second : 1;
  7519. }
  7520. MangleNumberingContext &
  7521. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  7522. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  7523. MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
  7524. if (!MCtx)
  7525. MCtx = createMangleNumberingContext();
  7526. return *MCtx;
  7527. }
  7528. MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
  7529. return ABI->createMangleNumberingContext();
  7530. }
  7531. const CXXConstructorDecl *
  7532. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  7533. return ABI->getCopyConstructorForExceptionObject(
  7534. cast<CXXRecordDecl>(RD->getFirstDecl()));
  7535. }
  7536. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  7537. CXXConstructorDecl *CD) {
  7538. return ABI->addCopyConstructorForExceptionObject(
  7539. cast<CXXRecordDecl>(RD->getFirstDecl()),
  7540. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  7541. }
  7542. void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
  7543. unsigned ParmIdx, Expr *DAE) {
  7544. ABI->addDefaultArgExprForConstructor(
  7545. cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
  7546. }
  7547. Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
  7548. unsigned ParmIdx) {
  7549. return ABI->getDefaultArgExprForConstructor(
  7550. cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
  7551. }
  7552. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  7553. ParamIndices[D] = index;
  7554. }
  7555. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  7556. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  7557. assert(I != ParamIndices.end() &&
  7558. "ParmIndices lacks entry set by ParmVarDecl");
  7559. return I->second;
  7560. }
  7561. APValue *
  7562. ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
  7563. bool MayCreate) {
  7564. assert(E && E->getStorageDuration() == SD_Static &&
  7565. "don't need to cache the computed value for this temporary");
  7566. if (MayCreate)
  7567. return &MaterializedTemporaryValues[E];
  7568. llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
  7569. MaterializedTemporaryValues.find(E);
  7570. return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
  7571. }
  7572. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  7573. const llvm::Triple &T = getTargetInfo().getTriple();
  7574. if (!T.isOSDarwin())
  7575. return false;
  7576. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  7577. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  7578. return false;
  7579. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  7580. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  7581. uint64_t Size = sizeChars.getQuantity();
  7582. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  7583. unsigned Align = alignChars.getQuantity();
  7584. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  7585. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  7586. }
  7587. namespace {
  7588. /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
  7589. /// parents as defined by the \c RecursiveASTVisitor.
  7590. ///
  7591. /// Note that the relationship described here is purely in terms of AST
  7592. /// traversal - there are other relationships (for example declaration context)
  7593. /// in the AST that are better modeled by special matchers.
  7594. ///
  7595. /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
  7596. class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
  7597. public:
  7598. /// \brief Builds and returns the translation unit's parent map.
  7599. ///
  7600. /// The caller takes ownership of the returned \c ParentMap.
  7601. static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
  7602. ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
  7603. Visitor.TraverseDecl(&TU);
  7604. return Visitor.Parents;
  7605. }
  7606. private:
  7607. typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
  7608. ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
  7609. }
  7610. bool shouldVisitTemplateInstantiations() const {
  7611. return true;
  7612. }
  7613. bool shouldVisitImplicitCode() const {
  7614. return true;
  7615. }
  7616. // Disables data recursion. We intercept Traverse* methods in the RAV, which
  7617. // are not triggered during data recursion.
  7618. bool shouldUseDataRecursionFor(clang::Stmt *S) const {
  7619. return false;
  7620. }
  7621. template <typename T>
  7622. bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
  7623. if (!Node)
  7624. return true;
  7625. if (ParentStack.size() > 0) {
  7626. // FIXME: Currently we add the same parent multiple times, but only
  7627. // when no memoization data is available for the type.
  7628. // For example when we visit all subexpressions of template
  7629. // instantiations; this is suboptimal, but benign: the only way to
  7630. // visit those is with hasAncestor / hasParent, and those do not create
  7631. // new matches.
  7632. // The plan is to enable DynTypedNode to be storable in a map or hash
  7633. // map. The main problem there is to implement hash functions /
  7634. // comparison operators for all types that DynTypedNode supports that
  7635. // do not have pointer identity.
  7636. auto &NodeOrVector = (*Parents)[Node];
  7637. if (NodeOrVector.isNull()) {
  7638. NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
  7639. } else {
  7640. if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
  7641. auto *Node =
  7642. NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
  7643. auto *Vector = new ASTContext::ParentVector(1, *Node);
  7644. NodeOrVector = Vector;
  7645. delete Node;
  7646. }
  7647. assert(NodeOrVector.template is<ASTContext::ParentVector *>());
  7648. auto *Vector =
  7649. NodeOrVector.template get<ASTContext::ParentVector *>();
  7650. // Skip duplicates for types that have memoization data.
  7651. // We must check that the type has memoization data before calling
  7652. // std::find() because DynTypedNode::operator== can't compare all
  7653. // types.
  7654. bool Found = ParentStack.back().getMemoizationData() &&
  7655. std::find(Vector->begin(), Vector->end(),
  7656. ParentStack.back()) != Vector->end();
  7657. if (!Found)
  7658. Vector->push_back(ParentStack.back());
  7659. }
  7660. }
  7661. ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
  7662. bool Result = (this ->* traverse) (Node);
  7663. ParentStack.pop_back();
  7664. return Result;
  7665. }
  7666. bool TraverseDecl(Decl *DeclNode) {
  7667. return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
  7668. }
  7669. bool TraverseStmt(Stmt *StmtNode) {
  7670. return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
  7671. }
  7672. ASTContext::ParentMap *Parents;
  7673. llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
  7674. friend class RecursiveASTVisitor<ParentMapASTVisitor>;
  7675. };
  7676. } // end namespace
  7677. ArrayRef<ast_type_traits::DynTypedNode>
  7678. ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
  7679. assert(Node.getMemoizationData() &&
  7680. "Invariant broken: only nodes that support memoization may be "
  7681. "used in the parent map.");
  7682. if (!AllParents) {
  7683. // We always need to run over the whole translation unit, as
  7684. // hasAncestor can escape any subtree.
  7685. AllParents.reset(
  7686. ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
  7687. }
  7688. ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
  7689. if (I == AllParents->end()) {
  7690. return None;
  7691. }
  7692. if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
  7693. return llvm::makeArrayRef(N, 1);
  7694. }
  7695. return *I->second.get<ParentVector *>();
  7696. }
  7697. bool
  7698. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  7699. const ObjCMethodDecl *MethodImpl) {
  7700. // No point trying to match an unavailable/deprecated mothod.
  7701. if (MethodDecl->hasAttr<UnavailableAttr>()
  7702. || MethodDecl->hasAttr<DeprecatedAttr>())
  7703. return false;
  7704. if (MethodDecl->getObjCDeclQualifier() !=
  7705. MethodImpl->getObjCDeclQualifier())
  7706. return false;
  7707. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  7708. return false;
  7709. if (MethodDecl->param_size() != MethodImpl->param_size())
  7710. return false;
  7711. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  7712. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  7713. EF = MethodDecl->param_end();
  7714. IM != EM && IF != EF; ++IM, ++IF) {
  7715. const ParmVarDecl *DeclVar = (*IF);
  7716. const ParmVarDecl *ImplVar = (*IM);
  7717. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  7718. return false;
  7719. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  7720. return false;
  7721. }
  7722. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  7723. }
  7724. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  7725. // doesn't include ASTContext.h
  7726. template
  7727. clang::LazyGenerationalUpdatePtr<
  7728. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  7729. clang::LazyGenerationalUpdatePtr<
  7730. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  7731. const clang::ASTContext &Ctx, Decl *Value);