ASTContext.cpp 379 KB

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