ASTContext.cpp 494 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455
  1. //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the ASTContext interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "CXXABI.h"
  14. #include "Interp/Context.h"
  15. #include "clang/AST/APValue.h"
  16. #include "clang/AST/ASTConcept.h"
  17. #include "clang/AST/ASTMutationListener.h"
  18. #include "clang/AST/ASTTypeTraits.h"
  19. #include "clang/AST/Attr.h"
  20. #include "clang/AST/AttrIterator.h"
  21. #include "clang/AST/CharUnits.h"
  22. #include "clang/AST/Comment.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclBase.h"
  25. #include "clang/AST/DeclCXX.h"
  26. #include "clang/AST/DeclContextInternals.h"
  27. #include "clang/AST/DeclObjC.h"
  28. #include "clang/AST/DeclOpenMP.h"
  29. #include "clang/AST/DeclTemplate.h"
  30. #include "clang/AST/DeclarationName.h"
  31. #include "clang/AST/DependenceFlags.h"
  32. #include "clang/AST/Expr.h"
  33. #include "clang/AST/ExprCXX.h"
  34. #include "clang/AST/ExprConcepts.h"
  35. #include "clang/AST/ExternalASTSource.h"
  36. #include "clang/AST/Mangle.h"
  37. #include "clang/AST/MangleNumberingContext.h"
  38. #include "clang/AST/NestedNameSpecifier.h"
  39. #include "clang/AST/ParentMapContext.h"
  40. #include "clang/AST/RawCommentList.h"
  41. #include "clang/AST/RecordLayout.h"
  42. #include "clang/AST/Stmt.h"
  43. #include "clang/AST/TemplateBase.h"
  44. #include "clang/AST/TemplateName.h"
  45. #include "clang/AST/Type.h"
  46. #include "clang/AST/TypeLoc.h"
  47. #include "clang/AST/UnresolvedSet.h"
  48. #include "clang/AST/VTableBuilder.h"
  49. #include "clang/Basic/AddressSpaces.h"
  50. #include "clang/Basic/Builtins.h"
  51. #include "clang/Basic/CommentOptions.h"
  52. #include "clang/Basic/ExceptionSpecificationType.h"
  53. #include "clang/Basic/IdentifierTable.h"
  54. #include "clang/Basic/LLVM.h"
  55. #include "clang/Basic/LangOptions.h"
  56. #include "clang/Basic/Linkage.h"
  57. #include "clang/Basic/Module.h"
  58. #include "clang/Basic/NoSanitizeList.h"
  59. #include "clang/Basic/ObjCRuntime.h"
  60. #include "clang/Basic/SourceLocation.h"
  61. #include "clang/Basic/SourceManager.h"
  62. #include "clang/Basic/Specifiers.h"
  63. #include "clang/Basic/TargetCXXABI.h"
  64. #include "clang/Basic/TargetInfo.h"
  65. #include "clang/Basic/XRayLists.h"
  66. #include "llvm/ADT/APFixedPoint.h"
  67. #include "llvm/ADT/APInt.h"
  68. #include "llvm/ADT/APSInt.h"
  69. #include "llvm/ADT/ArrayRef.h"
  70. #include "llvm/ADT/DenseMap.h"
  71. #include "llvm/ADT/DenseSet.h"
  72. #include "llvm/ADT/FoldingSet.h"
  73. #include "llvm/ADT/PointerUnion.h"
  74. #include "llvm/ADT/STLExtras.h"
  75. #include "llvm/ADT/SmallPtrSet.h"
  76. #include "llvm/ADT/SmallVector.h"
  77. #include "llvm/ADT/StringExtras.h"
  78. #include "llvm/ADT/StringRef.h"
  79. #include "llvm/ADT/Triple.h"
  80. #include "llvm/Support/Capacity.h"
  81. #include "llvm/Support/Casting.h"
  82. #include "llvm/Support/Compiler.h"
  83. #include "llvm/Support/ErrorHandling.h"
  84. #include "llvm/Support/MD5.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/raw_ostream.h"
  87. #include <algorithm>
  88. #include <cassert>
  89. #include <cstddef>
  90. #include <cstdint>
  91. #include <cstdlib>
  92. #include <map>
  93. #include <memory>
  94. #include <optional>
  95. #include <string>
  96. #include <tuple>
  97. #include <utility>
  98. using namespace clang;
  99. enum FloatingRank {
  100. BFloat16Rank,
  101. Float16Rank,
  102. HalfRank,
  103. FloatRank,
  104. DoubleRank,
  105. LongDoubleRank,
  106. Float128Rank,
  107. Ibm128Rank
  108. };
  109. /// \returns location that is relevant when searching for Doc comments related
  110. /// to \p D.
  111. static SourceLocation getDeclLocForCommentSearch(const Decl *D,
  112. SourceManager &SourceMgr) {
  113. assert(D);
  114. // User can not attach documentation to implicit declarations.
  115. if (D->isImplicit())
  116. return {};
  117. // User can not attach documentation to implicit instantiations.
  118. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  119. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  120. return {};
  121. }
  122. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  123. if (VD->isStaticDataMember() &&
  124. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  125. return {};
  126. }
  127. if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
  128. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  129. return {};
  130. }
  131. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  132. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  133. if (TSK == TSK_ImplicitInstantiation ||
  134. TSK == TSK_Undeclared)
  135. return {};
  136. }
  137. if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  138. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  139. return {};
  140. }
  141. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  142. // When tag declaration (but not definition!) is part of the
  143. // decl-specifier-seq of some other declaration, it doesn't get comment
  144. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  145. return {};
  146. }
  147. // TODO: handle comments for function parameters properly.
  148. if (isa<ParmVarDecl>(D))
  149. return {};
  150. // TODO: we could look up template parameter documentation in the template
  151. // documentation.
  152. if (isa<TemplateTypeParmDecl>(D) ||
  153. isa<NonTypeTemplateParmDecl>(D) ||
  154. isa<TemplateTemplateParmDecl>(D))
  155. return {};
  156. // Find declaration location.
  157. // For Objective-C declarations we generally don't expect to have multiple
  158. // declarators, thus use declaration starting location as the "declaration
  159. // location".
  160. // For all other declarations multiple declarators are used quite frequently,
  161. // so we use the location of the identifier as the "declaration location".
  162. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  163. isa<ObjCPropertyDecl>(D) ||
  164. isa<RedeclarableTemplateDecl>(D) ||
  165. isa<ClassTemplateSpecializationDecl>(D) ||
  166. // Allow association with Y across {} in `typedef struct X {} Y`.
  167. isa<TypedefDecl>(D))
  168. return D->getBeginLoc();
  169. const SourceLocation DeclLoc = D->getLocation();
  170. if (DeclLoc.isMacroID()) {
  171. if (isa<TypedefDecl>(D)) {
  172. // If location of the typedef name is in a macro, it is because being
  173. // declared via a macro. Try using declaration's starting location as
  174. // the "declaration location".
  175. return D->getBeginLoc();
  176. }
  177. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  178. // If location of the tag decl is inside a macro, but the spelling of
  179. // the tag name comes from a macro argument, it looks like a special
  180. // macro like NS_ENUM is being used to define the tag decl. In that
  181. // case, adjust the source location to the expansion loc so that we can
  182. // attach the comment to the tag decl.
  183. if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
  184. return SourceMgr.getExpansionLoc(DeclLoc);
  185. }
  186. }
  187. return DeclLoc;
  188. }
  189. RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
  190. const Decl *D, const SourceLocation RepresentativeLocForDecl,
  191. const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
  192. // If the declaration doesn't map directly to a location in a file, we
  193. // can't find the comment.
  194. if (RepresentativeLocForDecl.isInvalid() ||
  195. !RepresentativeLocForDecl.isFileID())
  196. return nullptr;
  197. // If there are no comments anywhere, we won't find anything.
  198. if (CommentsInTheFile.empty())
  199. return nullptr;
  200. // Decompose the location for the declaration and find the beginning of the
  201. // file buffer.
  202. const std::pair<FileID, unsigned> DeclLocDecomp =
  203. SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
  204. // Slow path.
  205. auto OffsetCommentBehindDecl =
  206. CommentsInTheFile.lower_bound(DeclLocDecomp.second);
  207. // First check whether we have a trailing comment.
  208. if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
  209. RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
  210. if ((CommentBehindDecl->isDocumentation() ||
  211. LangOpts.CommentOpts.ParseAllComments) &&
  212. CommentBehindDecl->isTrailingComment() &&
  213. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  214. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  215. // Check that Doxygen trailing comment comes after the declaration, starts
  216. // on the same line and in the same file as the declaration.
  217. if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
  218. Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
  219. OffsetCommentBehindDecl->first)) {
  220. return CommentBehindDecl;
  221. }
  222. }
  223. }
  224. // The comment just after the declaration was not a trailing comment.
  225. // Let's look at the previous comment.
  226. if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
  227. return nullptr;
  228. auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
  229. RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
  230. // Check that we actually have a non-member Doxygen comment.
  231. if (!(CommentBeforeDecl->isDocumentation() ||
  232. LangOpts.CommentOpts.ParseAllComments) ||
  233. CommentBeforeDecl->isTrailingComment())
  234. return nullptr;
  235. // Decompose the end of the comment.
  236. const unsigned CommentEndOffset =
  237. Comments.getCommentEndOffset(CommentBeforeDecl);
  238. // Get the corresponding buffer.
  239. bool Invalid = false;
  240. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  241. &Invalid).data();
  242. if (Invalid)
  243. return nullptr;
  244. // Extract text between the comment and declaration.
  245. StringRef Text(Buffer + CommentEndOffset,
  246. DeclLocDecomp.second - CommentEndOffset);
  247. // There should be no other declarations or preprocessor directives between
  248. // comment and declaration.
  249. if (Text.find_first_of(";{}#@") != StringRef::npos)
  250. return nullptr;
  251. return CommentBeforeDecl;
  252. }
  253. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  254. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  255. // If the declaration doesn't map directly to a location in a file, we
  256. // can't find the comment.
  257. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  258. return nullptr;
  259. if (ExternalSource && !CommentsLoaded) {
  260. ExternalSource->ReadComments();
  261. CommentsLoaded = true;
  262. }
  263. if (Comments.empty())
  264. return nullptr;
  265. const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
  266. if (!File.isValid()) {
  267. return nullptr;
  268. }
  269. const auto CommentsInThisFile = Comments.getCommentsInFile(File);
  270. if (!CommentsInThisFile || CommentsInThisFile->empty())
  271. return nullptr;
  272. return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
  273. }
  274. void ASTContext::addComment(const RawComment &RC) {
  275. assert(LangOpts.RetainCommentsFromSystemHeaders ||
  276. !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
  277. Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
  278. }
  279. /// If we have a 'templated' declaration for a template, adjust 'D' to
  280. /// refer to the actual template.
  281. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  282. static const Decl &adjustDeclToTemplate(const Decl &D) {
  283. if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
  284. // Is this function declaration part of a function template?
  285. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  286. return *FTD;
  287. // Nothing to do if function is not an implicit instantiation.
  288. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  289. return D;
  290. // Function is an implicit instantiation of a function template?
  291. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  292. return *FTD;
  293. // Function is instantiated from a member definition of a class template?
  294. if (const FunctionDecl *MemberDecl =
  295. FD->getInstantiatedFromMemberFunction())
  296. return *MemberDecl;
  297. return D;
  298. }
  299. if (const auto *VD = dyn_cast<VarDecl>(&D)) {
  300. // Static data member is instantiated from a member definition of a class
  301. // template?
  302. if (VD->isStaticDataMember())
  303. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  304. return *MemberDecl;
  305. return D;
  306. }
  307. if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
  308. // Is this class declaration part of a class template?
  309. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  310. return *CTD;
  311. // Class is an implicit instantiation of a class template or partial
  312. // specialization?
  313. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  314. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  315. return D;
  316. llvm::PointerUnion<ClassTemplateDecl *,
  317. ClassTemplatePartialSpecializationDecl *>
  318. PU = CTSD->getSpecializedTemplateOrPartial();
  319. return PU.is<ClassTemplateDecl *>()
  320. ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
  321. : *static_cast<const Decl *>(
  322. PU.get<ClassTemplatePartialSpecializationDecl *>());
  323. }
  324. // Class is instantiated from a member definition of a class template?
  325. if (const MemberSpecializationInfo *Info =
  326. CRD->getMemberSpecializationInfo())
  327. return *Info->getInstantiatedFrom();
  328. return D;
  329. }
  330. if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
  331. // Enum is instantiated from a member definition of a class template?
  332. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  333. return *MemberDecl;
  334. return D;
  335. }
  336. // FIXME: Adjust alias templates?
  337. return D;
  338. }
  339. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  340. const Decl *D,
  341. const Decl **OriginalDecl) const {
  342. if (!D) {
  343. if (OriginalDecl)
  344. OriginalDecl = nullptr;
  345. return nullptr;
  346. }
  347. D = &adjustDeclToTemplate(*D);
  348. // Any comment directly attached to D?
  349. {
  350. auto DeclComment = DeclRawComments.find(D);
  351. if (DeclComment != DeclRawComments.end()) {
  352. if (OriginalDecl)
  353. *OriginalDecl = D;
  354. return DeclComment->second;
  355. }
  356. }
  357. // Any comment attached to any redeclaration of D?
  358. const Decl *CanonicalD = D->getCanonicalDecl();
  359. if (!CanonicalD)
  360. return nullptr;
  361. {
  362. auto RedeclComment = RedeclChainComments.find(CanonicalD);
  363. if (RedeclComment != RedeclChainComments.end()) {
  364. if (OriginalDecl)
  365. *OriginalDecl = RedeclComment->second;
  366. auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
  367. assert(CommentAtRedecl != DeclRawComments.end() &&
  368. "This decl is supposed to have comment attached.");
  369. return CommentAtRedecl->second;
  370. }
  371. }
  372. // Any redeclarations of D that we haven't checked for comments yet?
  373. // We can't use DenseMap::iterator directly since it'd get invalid.
  374. auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
  375. auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
  376. if (LookupRes != CommentlessRedeclChains.end())
  377. return LookupRes->second;
  378. return nullptr;
  379. }();
  380. for (const auto Redecl : D->redecls()) {
  381. assert(Redecl);
  382. // Skip all redeclarations that have been checked previously.
  383. if (LastCheckedRedecl) {
  384. if (LastCheckedRedecl == Redecl) {
  385. LastCheckedRedecl = nullptr;
  386. }
  387. continue;
  388. }
  389. const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
  390. if (RedeclComment) {
  391. cacheRawCommentForDecl(*Redecl, *RedeclComment);
  392. if (OriginalDecl)
  393. *OriginalDecl = Redecl;
  394. return RedeclComment;
  395. }
  396. CommentlessRedeclChains[CanonicalD] = Redecl;
  397. }
  398. if (OriginalDecl)
  399. *OriginalDecl = nullptr;
  400. return nullptr;
  401. }
  402. void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
  403. const RawComment &Comment) const {
  404. assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
  405. DeclRawComments.try_emplace(&OriginalD, &Comment);
  406. const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
  407. RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
  408. CommentlessRedeclChains.erase(CanonicalDecl);
  409. }
  410. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  411. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  412. const DeclContext *DC = ObjCMethod->getDeclContext();
  413. if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  414. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  415. if (!ID)
  416. return;
  417. // Add redeclared method here.
  418. for (const auto *Ext : ID->known_extensions()) {
  419. if (ObjCMethodDecl *RedeclaredMethod =
  420. Ext->getMethod(ObjCMethod->getSelector(),
  421. ObjCMethod->isInstanceMethod()))
  422. Redeclared.push_back(RedeclaredMethod);
  423. }
  424. }
  425. }
  426. void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
  427. const Preprocessor *PP) {
  428. if (Comments.empty() || Decls.empty())
  429. return;
  430. FileID File;
  431. for (Decl *D : Decls) {
  432. SourceLocation Loc = D->getLocation();
  433. if (Loc.isValid()) {
  434. // See if there are any new comments that are not attached to a decl.
  435. // The location doesn't have to be precise - we care only about the file.
  436. File = SourceMgr.getDecomposedLoc(Loc).first;
  437. break;
  438. }
  439. }
  440. if (File.isInvalid())
  441. return;
  442. auto CommentsInThisFile = Comments.getCommentsInFile(File);
  443. if (!CommentsInThisFile || CommentsInThisFile->empty() ||
  444. CommentsInThisFile->rbegin()->second->isAttached())
  445. return;
  446. // There is at least one comment not attached to a decl.
  447. // Maybe it should be attached to one of Decls?
  448. //
  449. // Note that this way we pick up not only comments that precede the
  450. // declaration, but also comments that *follow* the declaration -- thanks to
  451. // the lookahead in the lexer: we've consumed the semicolon and looked
  452. // ahead through comments.
  453. for (const Decl *D : Decls) {
  454. assert(D);
  455. if (D->isInvalidDecl())
  456. continue;
  457. D = &adjustDeclToTemplate(*D);
  458. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  459. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  460. continue;
  461. if (DeclRawComments.count(D) > 0)
  462. continue;
  463. if (RawComment *const DocComment =
  464. getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
  465. cacheRawCommentForDecl(*D, *DocComment);
  466. comments::FullComment *FC = DocComment->parse(*this, PP, D);
  467. ParsedComments[D->getCanonicalDecl()] = FC;
  468. }
  469. }
  470. }
  471. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  472. const Decl *D) const {
  473. auto *ThisDeclInfo = new (*this) comments::DeclInfo;
  474. ThisDeclInfo->CommentDecl = D;
  475. ThisDeclInfo->IsFilled = false;
  476. ThisDeclInfo->fill();
  477. ThisDeclInfo->CommentDecl = FC->getDecl();
  478. if (!ThisDeclInfo->TemplateParameters)
  479. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  480. comments::FullComment *CFC =
  481. new (*this) comments::FullComment(FC->getBlocks(),
  482. ThisDeclInfo);
  483. return CFC;
  484. }
  485. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  486. const RawComment *RC = getRawCommentForDeclNoCache(D);
  487. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  488. }
  489. comments::FullComment *ASTContext::getCommentForDecl(
  490. const Decl *D,
  491. const Preprocessor *PP) const {
  492. if (!D || D->isInvalidDecl())
  493. return nullptr;
  494. D = &adjustDeclToTemplate(*D);
  495. const Decl *Canonical = D->getCanonicalDecl();
  496. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  497. ParsedComments.find(Canonical);
  498. if (Pos != ParsedComments.end()) {
  499. if (Canonical != D) {
  500. comments::FullComment *FC = Pos->second;
  501. comments::FullComment *CFC = cloneFullComment(FC, D);
  502. return CFC;
  503. }
  504. return Pos->second;
  505. }
  506. const Decl *OriginalDecl = nullptr;
  507. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  508. if (!RC) {
  509. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  510. SmallVector<const NamedDecl*, 8> Overridden;
  511. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  512. if (OMD && OMD->isPropertyAccessor())
  513. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  514. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  515. return cloneFullComment(FC, D);
  516. if (OMD)
  517. addRedeclaredMethods(OMD, Overridden);
  518. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  519. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  520. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  521. return cloneFullComment(FC, D);
  522. }
  523. else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  524. // Attach any tag type's documentation to its typedef if latter
  525. // does not have one of its own.
  526. QualType QT = TD->getUnderlyingType();
  527. if (const auto *TT = QT->getAs<TagType>())
  528. if (const Decl *TD = TT->getDecl())
  529. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  530. return cloneFullComment(FC, D);
  531. }
  532. else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  533. while (IC->getSuperClass()) {
  534. IC = IC->getSuperClass();
  535. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  536. return cloneFullComment(FC, D);
  537. }
  538. }
  539. else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  540. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  541. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  542. return cloneFullComment(FC, D);
  543. }
  544. else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  545. if (!(RD = RD->getDefinition()))
  546. return nullptr;
  547. // Check non-virtual bases.
  548. for (const auto &I : RD->bases()) {
  549. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  550. continue;
  551. QualType Ty = I.getType();
  552. if (Ty.isNull())
  553. continue;
  554. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  555. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  556. continue;
  557. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  558. return cloneFullComment(FC, D);
  559. }
  560. }
  561. // Check virtual bases.
  562. for (const auto &I : RD->vbases()) {
  563. if (I.getAccessSpecifier() != AS_public)
  564. continue;
  565. QualType Ty = I.getType();
  566. if (Ty.isNull())
  567. continue;
  568. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  569. if (!(VirtualBase= VirtualBase->getDefinition()))
  570. continue;
  571. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  572. return cloneFullComment(FC, D);
  573. }
  574. }
  575. }
  576. return nullptr;
  577. }
  578. // If the RawComment was attached to other redeclaration of this Decl, we
  579. // should parse the comment in context of that other Decl. This is important
  580. // because comments can contain references to parameter names which can be
  581. // different across redeclarations.
  582. if (D != OriginalDecl && OriginalDecl)
  583. return getCommentForDecl(OriginalDecl, PP);
  584. comments::FullComment *FC = RC->parse(*this, PP, D);
  585. ParsedComments[Canonical] = FC;
  586. return FC;
  587. }
  588. void
  589. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  590. const ASTContext &C,
  591. TemplateTemplateParmDecl *Parm) {
  592. ID.AddInteger(Parm->getDepth());
  593. ID.AddInteger(Parm->getPosition());
  594. ID.AddBoolean(Parm->isParameterPack());
  595. TemplateParameterList *Params = Parm->getTemplateParameters();
  596. ID.AddInteger(Params->size());
  597. for (TemplateParameterList::const_iterator P = Params->begin(),
  598. PEnd = Params->end();
  599. P != PEnd; ++P) {
  600. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  601. ID.AddInteger(0);
  602. ID.AddBoolean(TTP->isParameterPack());
  603. const TypeConstraint *TC = TTP->getTypeConstraint();
  604. ID.AddBoolean(TC != nullptr);
  605. if (TC)
  606. TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
  607. /*Canonical=*/true);
  608. if (TTP->isExpandedParameterPack()) {
  609. ID.AddBoolean(true);
  610. ID.AddInteger(TTP->getNumExpansionParameters());
  611. } else
  612. ID.AddBoolean(false);
  613. continue;
  614. }
  615. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  616. ID.AddInteger(1);
  617. ID.AddBoolean(NTTP->isParameterPack());
  618. const Expr *TC = NTTP->getPlaceholderTypeConstraint();
  619. ID.AddBoolean(TC != nullptr);
  620. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  621. if (TC)
  622. TC->Profile(ID, C, /*Canonical=*/true);
  623. if (NTTP->isExpandedParameterPack()) {
  624. ID.AddBoolean(true);
  625. ID.AddInteger(NTTP->getNumExpansionTypes());
  626. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  627. QualType T = NTTP->getExpansionType(I);
  628. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  629. }
  630. } else
  631. ID.AddBoolean(false);
  632. continue;
  633. }
  634. auto *TTP = cast<TemplateTemplateParmDecl>(*P);
  635. ID.AddInteger(2);
  636. Profile(ID, C, TTP);
  637. }
  638. Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
  639. ID.AddBoolean(RequiresClause != nullptr);
  640. if (RequiresClause)
  641. RequiresClause->Profile(ID, C, /*Canonical=*/true);
  642. }
  643. static Expr *
  644. canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
  645. QualType ConstrainedType) {
  646. // This is a bit ugly - we need to form a new immediately-declared
  647. // constraint that references the new parameter; this would ideally
  648. // require semantic analysis (e.g. template<C T> struct S {}; - the
  649. // converted arguments of C<T> could be an argument pack if C is
  650. // declared as template<typename... T> concept C = ...).
  651. // We don't have semantic analysis here so we dig deep into the
  652. // ready-made constraint expr and change the thing manually.
  653. ConceptSpecializationExpr *CSE;
  654. if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
  655. CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
  656. else
  657. CSE = cast<ConceptSpecializationExpr>(IDC);
  658. ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
  659. SmallVector<TemplateArgument, 3> NewConverted;
  660. NewConverted.reserve(OldConverted.size());
  661. if (OldConverted.front().getKind() == TemplateArgument::Pack) {
  662. // The case:
  663. // template<typename... T> concept C = true;
  664. // template<C<int> T> struct S; -> constraint is C<{T, int}>
  665. NewConverted.push_back(ConstrainedType);
  666. llvm::append_range(NewConverted,
  667. OldConverted.front().pack_elements().drop_front(1));
  668. TemplateArgument NewPack(NewConverted);
  669. NewConverted.clear();
  670. NewConverted.push_back(NewPack);
  671. assert(OldConverted.size() == 1 &&
  672. "Template parameter pack should be the last parameter");
  673. } else {
  674. assert(OldConverted.front().getKind() == TemplateArgument::Type &&
  675. "Unexpected first argument kind for immediately-declared "
  676. "constraint");
  677. NewConverted.push_back(ConstrainedType);
  678. llvm::append_range(NewConverted, OldConverted.drop_front(1));
  679. }
  680. auto *CSD = ImplicitConceptSpecializationDecl::Create(
  681. C, CSE->getNamedConcept()->getDeclContext(),
  682. CSE->getNamedConcept()->getLocation(), NewConverted);
  683. Expr *NewIDC = ConceptSpecializationExpr::Create(
  684. C, CSE->getNamedConcept(), CSD, nullptr, CSE->isInstantiationDependent(),
  685. CSE->containsUnexpandedParameterPack());
  686. if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
  687. NewIDC = new (C) CXXFoldExpr(
  688. OrigFold->getType(), /*Callee*/ nullptr, SourceLocation(), NewIDC,
  689. BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
  690. SourceLocation(), /*NumExpansions=*/std::nullopt);
  691. return NewIDC;
  692. }
  693. TemplateTemplateParmDecl *
  694. ASTContext::getCanonicalTemplateTemplateParmDecl(
  695. TemplateTemplateParmDecl *TTP) const {
  696. // Check if we already have a canonical template template parameter.
  697. llvm::FoldingSetNodeID ID;
  698. CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
  699. void *InsertPos = nullptr;
  700. CanonicalTemplateTemplateParm *Canonical
  701. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  702. if (Canonical)
  703. return Canonical->getParam();
  704. // Build a canonical template parameter list.
  705. TemplateParameterList *Params = TTP->getTemplateParameters();
  706. SmallVector<NamedDecl *, 4> CanonParams;
  707. CanonParams.reserve(Params->size());
  708. for (TemplateParameterList::const_iterator P = Params->begin(),
  709. PEnd = Params->end();
  710. P != PEnd; ++P) {
  711. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  712. TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(
  713. *this, getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
  714. TTP->getDepth(), TTP->getIndex(), nullptr, false,
  715. TTP->isParameterPack(), TTP->hasTypeConstraint(),
  716. TTP->isExpandedParameterPack()
  717. ? std::optional<unsigned>(TTP->getNumExpansionParameters())
  718. : std::nullopt);
  719. if (const auto *TC = TTP->getTypeConstraint()) {
  720. QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
  721. Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
  722. *this, TC->getImmediatelyDeclaredConstraint(),
  723. ParamAsArgument);
  724. NewTTP->setTypeConstraint(
  725. NestedNameSpecifierLoc(),
  726. DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
  727. SourceLocation()), /*FoundDecl=*/nullptr,
  728. // Actually canonicalizing a TemplateArgumentLoc is difficult so we
  729. // simply omit the ArgsAsWritten
  730. TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
  731. }
  732. CanonParams.push_back(NewTTP);
  733. } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  734. QualType T = getCanonicalType(NTTP->getType());
  735. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  736. NonTypeTemplateParmDecl *Param;
  737. if (NTTP->isExpandedParameterPack()) {
  738. SmallVector<QualType, 2> ExpandedTypes;
  739. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  740. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  741. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  742. ExpandedTInfos.push_back(
  743. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  744. }
  745. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  746. SourceLocation(),
  747. SourceLocation(),
  748. NTTP->getDepth(),
  749. NTTP->getPosition(), nullptr,
  750. T,
  751. TInfo,
  752. ExpandedTypes,
  753. ExpandedTInfos);
  754. } else {
  755. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  756. SourceLocation(),
  757. SourceLocation(),
  758. NTTP->getDepth(),
  759. NTTP->getPosition(), nullptr,
  760. T,
  761. NTTP->isParameterPack(),
  762. TInfo);
  763. }
  764. if (AutoType *AT = T->getContainedAutoType()) {
  765. if (AT->isConstrained()) {
  766. Param->setPlaceholderTypeConstraint(
  767. canonicalizeImmediatelyDeclaredConstraint(
  768. *this, NTTP->getPlaceholderTypeConstraint(), T));
  769. }
  770. }
  771. CanonParams.push_back(Param);
  772. } else
  773. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  774. cast<TemplateTemplateParmDecl>(*P)));
  775. }
  776. Expr *CanonRequiresClause = nullptr;
  777. if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
  778. CanonRequiresClause = RequiresClause;
  779. TemplateTemplateParmDecl *CanonTTP
  780. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  781. SourceLocation(), TTP->getDepth(),
  782. TTP->getPosition(),
  783. TTP->isParameterPack(),
  784. nullptr,
  785. TemplateParameterList::Create(*this, SourceLocation(),
  786. SourceLocation(),
  787. CanonParams,
  788. SourceLocation(),
  789. CanonRequiresClause));
  790. // Get the new insert position for the node we care about.
  791. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  792. assert(!Canonical && "Shouldn't be in the map!");
  793. (void)Canonical;
  794. // Create the canonical template template parameter entry.
  795. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  796. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  797. return CanonTTP;
  798. }
  799. TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
  800. auto Kind = getTargetInfo().getCXXABI().getKind();
  801. return getLangOpts().CXXABI.value_or(Kind);
  802. }
  803. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  804. if (!LangOpts.CPlusPlus) return nullptr;
  805. switch (getCXXABIKind()) {
  806. case TargetCXXABI::AppleARM64:
  807. case TargetCXXABI::Fuchsia:
  808. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  809. case TargetCXXABI::iOS:
  810. case TargetCXXABI::WatchOS:
  811. case TargetCXXABI::GenericAArch64:
  812. case TargetCXXABI::GenericMIPS:
  813. case TargetCXXABI::GenericItanium:
  814. case TargetCXXABI::WebAssembly:
  815. case TargetCXXABI::XL:
  816. return CreateItaniumCXXABI(*this);
  817. case TargetCXXABI::Microsoft:
  818. return CreateMicrosoftCXXABI(*this);
  819. }
  820. llvm_unreachable("Invalid CXXABI type!");
  821. }
  822. interp::Context &ASTContext::getInterpContext() {
  823. if (!InterpContext) {
  824. InterpContext.reset(new interp::Context(*this));
  825. }
  826. return *InterpContext.get();
  827. }
  828. ParentMapContext &ASTContext::getParentMapContext() {
  829. if (!ParentMapCtx)
  830. ParentMapCtx.reset(new ParentMapContext(*this));
  831. return *ParentMapCtx.get();
  832. }
  833. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  834. const LangOptions &LangOpts) {
  835. switch (LangOpts.getAddressSpaceMapMangling()) {
  836. case LangOptions::ASMM_Target:
  837. return TI.useAddressSpaceMapMangling();
  838. case LangOptions::ASMM_On:
  839. return true;
  840. case LangOptions::ASMM_Off:
  841. return false;
  842. }
  843. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  844. }
  845. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  846. IdentifierTable &idents, SelectorTable &sels,
  847. Builtin::Context &builtins, TranslationUnitKind TUKind)
  848. : ConstantArrayTypes(this_(), ConstantArrayTypesLog2InitSize),
  849. FunctionProtoTypes(this_(), FunctionProtoTypesLog2InitSize),
  850. TemplateSpecializationTypes(this_()),
  851. DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
  852. SubstTemplateTemplateParmPacks(this_()),
  853. CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
  854. NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
  855. XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
  856. LangOpts.XRayNeverInstrumentFiles,
  857. LangOpts.XRayAttrListFiles, SM)),
  858. ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
  859. PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
  860. BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
  861. Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
  862. CompCategories(this_()), LastSDM(nullptr, 0) {
  863. addTranslationUnitDecl();
  864. }
  865. void ASTContext::cleanup() {
  866. // Release the DenseMaps associated with DeclContext objects.
  867. // FIXME: Is this the ideal solution?
  868. ReleaseDeclContextMaps();
  869. // Call all of the deallocation functions on all of their targets.
  870. for (auto &Pair : Deallocations)
  871. (Pair.first)(Pair.second);
  872. Deallocations.clear();
  873. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  874. // because they can contain DenseMaps.
  875. for (llvm::DenseMap<const ObjCContainerDecl*,
  876. const ASTRecordLayout*>::iterator
  877. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  878. // Increment in loop to prevent using deallocated memory.
  879. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  880. R->Destroy(*this);
  881. ObjCLayouts.clear();
  882. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  883. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  884. // Increment in loop to prevent using deallocated memory.
  885. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  886. R->Destroy(*this);
  887. }
  888. ASTRecordLayouts.clear();
  889. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  890. AEnd = DeclAttrs.end();
  891. A != AEnd; ++A)
  892. A->second->~AttrVec();
  893. DeclAttrs.clear();
  894. for (const auto &Value : ModuleInitializers)
  895. Value.second->~PerModuleInitializers();
  896. ModuleInitializers.clear();
  897. }
  898. ASTContext::~ASTContext() { cleanup(); }
  899. void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
  900. TraversalScope = TopLevelDecls;
  901. getParentMapContext().clear();
  902. }
  903. void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
  904. Deallocations.push_back({Callback, Data});
  905. }
  906. void
  907. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  908. ExternalSource = std::move(Source);
  909. }
  910. void ASTContext::PrintStats() const {
  911. llvm::errs() << "\n*** AST Context Stats:\n";
  912. llvm::errs() << " " << Types.size() << " types total.\n";
  913. unsigned counts[] = {
  914. #define TYPE(Name, Parent) 0,
  915. #define ABSTRACT_TYPE(Name, Parent)
  916. #include "clang/AST/TypeNodes.inc"
  917. 0 // Extra
  918. };
  919. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  920. Type *T = Types[i];
  921. counts[(unsigned)T->getTypeClass()]++;
  922. }
  923. unsigned Idx = 0;
  924. unsigned TotalBytes = 0;
  925. #define TYPE(Name, Parent) \
  926. if (counts[Idx]) \
  927. llvm::errs() << " " << counts[Idx] << " " << #Name \
  928. << " types, " << sizeof(Name##Type) << " each " \
  929. << "(" << counts[Idx] * sizeof(Name##Type) \
  930. << " bytes)\n"; \
  931. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  932. ++Idx;
  933. #define ABSTRACT_TYPE(Name, Parent)
  934. #include "clang/AST/TypeNodes.inc"
  935. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  936. // Implicit special member functions.
  937. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  938. << NumImplicitDefaultConstructors
  939. << " implicit default constructors created\n";
  940. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  941. << NumImplicitCopyConstructors
  942. << " implicit copy constructors created\n";
  943. if (getLangOpts().CPlusPlus)
  944. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  945. << NumImplicitMoveConstructors
  946. << " implicit move constructors created\n";
  947. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  948. << NumImplicitCopyAssignmentOperators
  949. << " implicit copy assignment operators created\n";
  950. if (getLangOpts().CPlusPlus)
  951. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  952. << NumImplicitMoveAssignmentOperators
  953. << " implicit move assignment operators created\n";
  954. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  955. << NumImplicitDestructors
  956. << " implicit destructors created\n";
  957. if (ExternalSource) {
  958. llvm::errs() << "\n";
  959. ExternalSource->PrintStats();
  960. }
  961. BumpAlloc.PrintStats();
  962. }
  963. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  964. bool NotifyListeners) {
  965. if (NotifyListeners)
  966. if (auto *Listener = getASTMutationListener())
  967. Listener->RedefinedHiddenDefinition(ND, M);
  968. MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
  969. }
  970. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  971. auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
  972. if (It == MergedDefModules.end())
  973. return;
  974. auto &Merged = It->second;
  975. llvm::DenseSet<Module*> Found;
  976. for (Module *&M : Merged)
  977. if (!Found.insert(M).second)
  978. M = nullptr;
  979. llvm::erase_value(Merged, nullptr);
  980. }
  981. ArrayRef<Module *>
  982. ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
  983. auto MergedIt =
  984. MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
  985. if (MergedIt == MergedDefModules.end())
  986. return std::nullopt;
  987. return MergedIt->second;
  988. }
  989. void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
  990. if (LazyInitializers.empty())
  991. return;
  992. auto *Source = Ctx.getExternalSource();
  993. assert(Source && "lazy initializers but no external source");
  994. auto LazyInits = std::move(LazyInitializers);
  995. LazyInitializers.clear();
  996. for (auto ID : LazyInits)
  997. Initializers.push_back(Source->GetExternalDecl(ID));
  998. assert(LazyInitializers.empty() &&
  999. "GetExternalDecl for lazy module initializer added more inits");
  1000. }
  1001. void ASTContext::addModuleInitializer(Module *M, Decl *D) {
  1002. // One special case: if we add a module initializer that imports another
  1003. // module, and that module's only initializer is an ImportDecl, simplify.
  1004. if (const auto *ID = dyn_cast<ImportDecl>(D)) {
  1005. auto It = ModuleInitializers.find(ID->getImportedModule());
  1006. // Maybe the ImportDecl does nothing at all. (Common case.)
  1007. if (It == ModuleInitializers.end())
  1008. return;
  1009. // Maybe the ImportDecl only imports another ImportDecl.
  1010. auto &Imported = *It->second;
  1011. if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
  1012. Imported.resolve(*this);
  1013. auto *OnlyDecl = Imported.Initializers.front();
  1014. if (isa<ImportDecl>(OnlyDecl))
  1015. D = OnlyDecl;
  1016. }
  1017. }
  1018. auto *&Inits = ModuleInitializers[M];
  1019. if (!Inits)
  1020. Inits = new (*this) PerModuleInitializers;
  1021. Inits->Initializers.push_back(D);
  1022. }
  1023. void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
  1024. auto *&Inits = ModuleInitializers[M];
  1025. if (!Inits)
  1026. Inits = new (*this) PerModuleInitializers;
  1027. Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
  1028. IDs.begin(), IDs.end());
  1029. }
  1030. ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
  1031. auto It = ModuleInitializers.find(M);
  1032. if (It == ModuleInitializers.end())
  1033. return std::nullopt;
  1034. auto *Inits = It->second;
  1035. Inits->resolve(*this);
  1036. return Inits->Initializers;
  1037. }
  1038. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  1039. if (!ExternCContext)
  1040. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  1041. return ExternCContext;
  1042. }
  1043. BuiltinTemplateDecl *
  1044. ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
  1045. const IdentifierInfo *II) const {
  1046. auto *BuiltinTemplate =
  1047. BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
  1048. BuiltinTemplate->setImplicit();
  1049. getTranslationUnitDecl()->addDecl(BuiltinTemplate);
  1050. return BuiltinTemplate;
  1051. }
  1052. BuiltinTemplateDecl *
  1053. ASTContext::getMakeIntegerSeqDecl() const {
  1054. if (!MakeIntegerSeqDecl)
  1055. MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
  1056. getMakeIntegerSeqName());
  1057. return MakeIntegerSeqDecl;
  1058. }
  1059. BuiltinTemplateDecl *
  1060. ASTContext::getTypePackElementDecl() const {
  1061. if (!TypePackElementDecl)
  1062. TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
  1063. getTypePackElementName());
  1064. return TypePackElementDecl;
  1065. }
  1066. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  1067. RecordDecl::TagKind TK) const {
  1068. SourceLocation Loc;
  1069. RecordDecl *NewDecl;
  1070. if (getLangOpts().CPlusPlus)
  1071. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  1072. Loc, &Idents.get(Name));
  1073. else
  1074. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  1075. &Idents.get(Name));
  1076. NewDecl->setImplicit();
  1077. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  1078. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  1079. return NewDecl;
  1080. }
  1081. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  1082. StringRef Name) const {
  1083. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  1084. TypedefDecl *NewDecl = TypedefDecl::Create(
  1085. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  1086. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  1087. NewDecl->setImplicit();
  1088. return NewDecl;
  1089. }
  1090. TypedefDecl *ASTContext::getInt128Decl() const {
  1091. if (!Int128Decl)
  1092. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  1093. return Int128Decl;
  1094. }
  1095. TypedefDecl *ASTContext::getUInt128Decl() const {
  1096. if (!UInt128Decl)
  1097. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  1098. return UInt128Decl;
  1099. }
  1100. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  1101. auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
  1102. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  1103. Types.push_back(Ty);
  1104. }
  1105. void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
  1106. const TargetInfo *AuxTarget) {
  1107. assert((!this->Target || this->Target == &Target) &&
  1108. "Incorrect target reinitialization");
  1109. assert(VoidTy.isNull() && "Context reinitialized?");
  1110. this->Target = &Target;
  1111. this->AuxTarget = AuxTarget;
  1112. ABI.reset(createCXXABI(Target));
  1113. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  1114. // C99 6.2.5p19.
  1115. InitBuiltinType(VoidTy, BuiltinType::Void);
  1116. // C99 6.2.5p2.
  1117. InitBuiltinType(BoolTy, BuiltinType::Bool);
  1118. // C99 6.2.5p3.
  1119. if (LangOpts.CharIsSigned)
  1120. InitBuiltinType(CharTy, BuiltinType::Char_S);
  1121. else
  1122. InitBuiltinType(CharTy, BuiltinType::Char_U);
  1123. // C99 6.2.5p4.
  1124. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  1125. InitBuiltinType(ShortTy, BuiltinType::Short);
  1126. InitBuiltinType(IntTy, BuiltinType::Int);
  1127. InitBuiltinType(LongTy, BuiltinType::Long);
  1128. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  1129. // C99 6.2.5p6.
  1130. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  1131. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  1132. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  1133. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  1134. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  1135. // C99 6.2.5p10.
  1136. InitBuiltinType(FloatTy, BuiltinType::Float);
  1137. InitBuiltinType(DoubleTy, BuiltinType::Double);
  1138. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  1139. // GNU extension, __float128 for IEEE quadruple precision
  1140. InitBuiltinType(Float128Ty, BuiltinType::Float128);
  1141. // __ibm128 for IBM extended precision
  1142. InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
  1143. // C11 extension ISO/IEC TS 18661-3
  1144. InitBuiltinType(Float16Ty, BuiltinType::Float16);
  1145. // ISO/IEC JTC1 SC22 WG14 N1169 Extension
  1146. InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
  1147. InitBuiltinType(AccumTy, BuiltinType::Accum);
  1148. InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
  1149. InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
  1150. InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
  1151. InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
  1152. InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
  1153. InitBuiltinType(FractTy, BuiltinType::Fract);
  1154. InitBuiltinType(LongFractTy, BuiltinType::LongFract);
  1155. InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
  1156. InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
  1157. InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
  1158. InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
  1159. InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
  1160. InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
  1161. InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
  1162. InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
  1163. InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
  1164. InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
  1165. InitBuiltinType(SatFractTy, BuiltinType::SatFract);
  1166. InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
  1167. InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
  1168. InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
  1169. InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
  1170. // GNU extension, 128-bit integers.
  1171. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  1172. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  1173. // C++ 3.9.1p5
  1174. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  1175. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  1176. else // -fshort-wchar makes wchar_t be unsigned.
  1177. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  1178. if (LangOpts.CPlusPlus && LangOpts.WChar)
  1179. WideCharTy = WCharTy;
  1180. else {
  1181. // C99 (or C++ using -fno-wchar).
  1182. WideCharTy = getFromTargetType(Target.getWCharType());
  1183. }
  1184. WIntTy = getFromTargetType(Target.getWIntType());
  1185. // C++20 (proposed)
  1186. InitBuiltinType(Char8Ty, BuiltinType::Char8);
  1187. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1188. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  1189. else // C99
  1190. Char16Ty = getFromTargetType(Target.getChar16Type());
  1191. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1192. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  1193. else // C99
  1194. Char32Ty = getFromTargetType(Target.getChar32Type());
  1195. // Placeholder type for type-dependent expressions whose type is
  1196. // completely unknown. No code should ever check a type against
  1197. // DependentTy and users should never see it; however, it is here to
  1198. // help diagnose failures to properly check for type-dependent
  1199. // expressions.
  1200. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  1201. // Placeholder type for functions.
  1202. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  1203. // Placeholder type for bound members.
  1204. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  1205. // Placeholder type for pseudo-objects.
  1206. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  1207. // "any" type; useful for debugger-like clients.
  1208. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  1209. // Placeholder type for unbridged ARC casts.
  1210. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  1211. // Placeholder type for builtin functions.
  1212. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  1213. // Placeholder type for OMP array sections.
  1214. if (LangOpts.OpenMP) {
  1215. InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
  1216. InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
  1217. InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
  1218. }
  1219. if (LangOpts.MatrixTypes)
  1220. InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
  1221. // Builtin types for 'id', 'Class', and 'SEL'.
  1222. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  1223. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  1224. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  1225. if (LangOpts.OpenCL) {
  1226. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1227. InitBuiltinType(SingletonId, BuiltinType::Id);
  1228. #include "clang/Basic/OpenCLImageTypes.def"
  1229. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  1230. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  1231. InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
  1232. InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
  1233. InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
  1234. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1235. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1236. #include "clang/Basic/OpenCLExtensionTypes.def"
  1237. }
  1238. if (Target.hasAArch64SVETypes()) {
  1239. #define SVE_TYPE(Name, Id, SingletonId) \
  1240. InitBuiltinType(SingletonId, BuiltinType::Id);
  1241. #include "clang/Basic/AArch64SVEACLETypes.def"
  1242. }
  1243. if (Target.getTriple().isPPC64()) {
  1244. #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
  1245. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1246. #include "clang/Basic/PPCTypes.def"
  1247. #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
  1248. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1249. #include "clang/Basic/PPCTypes.def"
  1250. }
  1251. if (Target.hasRISCVVTypes()) {
  1252. #define RVV_TYPE(Name, Id, SingletonId) \
  1253. InitBuiltinType(SingletonId, BuiltinType::Id);
  1254. #include "clang/Basic/RISCVVTypes.def"
  1255. }
  1256. // Builtin type for __objc_yes and __objc_no
  1257. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  1258. SignedCharTy : BoolTy);
  1259. ObjCConstantStringType = QualType();
  1260. ObjCSuperType = QualType();
  1261. // void * type
  1262. if (LangOpts.OpenCLGenericAddressSpace) {
  1263. auto Q = VoidTy.getQualifiers();
  1264. Q.setAddressSpace(LangAS::opencl_generic);
  1265. VoidPtrTy = getPointerType(getCanonicalType(
  1266. getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
  1267. } else {
  1268. VoidPtrTy = getPointerType(VoidTy);
  1269. }
  1270. // nullptr type (C++0x 2.14.7)
  1271. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  1272. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  1273. InitBuiltinType(HalfTy, BuiltinType::Half);
  1274. InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
  1275. // Builtin type used to help define __builtin_va_list.
  1276. VaListTagDecl = nullptr;
  1277. // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
  1278. if (LangOpts.MicrosoftExt || LangOpts.Borland) {
  1279. MSGuidTagDecl = buildImplicitRecord("_GUID");
  1280. getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
  1281. }
  1282. }
  1283. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  1284. return SourceMgr.getDiagnostics();
  1285. }
  1286. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  1287. AttrVec *&Result = DeclAttrs[D];
  1288. if (!Result) {
  1289. void *Mem = Allocate(sizeof(AttrVec));
  1290. Result = new (Mem) AttrVec;
  1291. }
  1292. return *Result;
  1293. }
  1294. /// Erase the attributes corresponding to the given declaration.
  1295. void ASTContext::eraseDeclAttrs(const Decl *D) {
  1296. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  1297. if (Pos != DeclAttrs.end()) {
  1298. Pos->second->~AttrVec();
  1299. DeclAttrs.erase(Pos);
  1300. }
  1301. }
  1302. // FIXME: Remove ?
  1303. MemberSpecializationInfo *
  1304. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  1305. assert(Var->isStaticDataMember() && "Not a static data member");
  1306. return getTemplateOrSpecializationInfo(Var)
  1307. .dyn_cast<MemberSpecializationInfo *>();
  1308. }
  1309. ASTContext::TemplateOrSpecializationInfo
  1310. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  1311. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  1312. TemplateOrInstantiation.find(Var);
  1313. if (Pos == TemplateOrInstantiation.end())
  1314. return {};
  1315. return Pos->second;
  1316. }
  1317. void
  1318. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1319. TemplateSpecializationKind TSK,
  1320. SourceLocation PointOfInstantiation) {
  1321. assert(Inst->isStaticDataMember() && "Not a static data member");
  1322. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1323. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1324. Tmpl, TSK, PointOfInstantiation));
  1325. }
  1326. void
  1327. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1328. TemplateOrSpecializationInfo TSI) {
  1329. assert(!TemplateOrInstantiation[Inst] &&
  1330. "Already noted what the variable was instantiated from");
  1331. TemplateOrInstantiation[Inst] = TSI;
  1332. }
  1333. NamedDecl *
  1334. ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
  1335. auto Pos = InstantiatedFromUsingDecl.find(UUD);
  1336. if (Pos == InstantiatedFromUsingDecl.end())
  1337. return nullptr;
  1338. return Pos->second;
  1339. }
  1340. void
  1341. ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
  1342. assert((isa<UsingDecl>(Pattern) ||
  1343. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1344. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1345. "pattern decl is not a using decl");
  1346. assert((isa<UsingDecl>(Inst) ||
  1347. isa<UnresolvedUsingValueDecl>(Inst) ||
  1348. isa<UnresolvedUsingTypenameDecl>(Inst)) &&
  1349. "instantiation did not produce a using decl");
  1350. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1351. InstantiatedFromUsingDecl[Inst] = Pattern;
  1352. }
  1353. UsingEnumDecl *
  1354. ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
  1355. auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
  1356. if (Pos == InstantiatedFromUsingEnumDecl.end())
  1357. return nullptr;
  1358. return Pos->second;
  1359. }
  1360. void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
  1361. UsingEnumDecl *Pattern) {
  1362. assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
  1363. InstantiatedFromUsingEnumDecl[Inst] = Pattern;
  1364. }
  1365. UsingShadowDecl *
  1366. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1367. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1368. = InstantiatedFromUsingShadowDecl.find(Inst);
  1369. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1370. return nullptr;
  1371. return Pos->second;
  1372. }
  1373. void
  1374. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1375. UsingShadowDecl *Pattern) {
  1376. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1377. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1378. }
  1379. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1380. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1381. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1382. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1383. return nullptr;
  1384. return Pos->second;
  1385. }
  1386. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1387. FieldDecl *Tmpl) {
  1388. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1389. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1390. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1391. "Already noted what unnamed field was instantiated from");
  1392. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1393. }
  1394. ASTContext::overridden_cxx_method_iterator
  1395. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1396. return overridden_methods(Method).begin();
  1397. }
  1398. ASTContext::overridden_cxx_method_iterator
  1399. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1400. return overridden_methods(Method).end();
  1401. }
  1402. unsigned
  1403. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1404. auto Range = overridden_methods(Method);
  1405. return Range.end() - Range.begin();
  1406. }
  1407. ASTContext::overridden_method_range
  1408. ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
  1409. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
  1410. OverriddenMethods.find(Method->getCanonicalDecl());
  1411. if (Pos == OverriddenMethods.end())
  1412. return overridden_method_range(nullptr, nullptr);
  1413. return overridden_method_range(Pos->second.begin(), Pos->second.end());
  1414. }
  1415. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1416. const CXXMethodDecl *Overridden) {
  1417. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1418. OverriddenMethods[Method].push_back(Overridden);
  1419. }
  1420. void ASTContext::getOverriddenMethods(
  1421. const NamedDecl *D,
  1422. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1423. assert(D);
  1424. if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1425. Overridden.append(overridden_methods_begin(CXXMethod),
  1426. overridden_methods_end(CXXMethod));
  1427. return;
  1428. }
  1429. const auto *Method = dyn_cast<ObjCMethodDecl>(D);
  1430. if (!Method)
  1431. return;
  1432. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1433. Method->getOverriddenMethods(OverDecls);
  1434. Overridden.append(OverDecls.begin(), OverDecls.end());
  1435. }
  1436. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1437. assert(!Import->getNextLocalImport() &&
  1438. "Import declaration already in the chain");
  1439. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1440. if (!FirstLocalImport) {
  1441. FirstLocalImport = Import;
  1442. LastLocalImport = Import;
  1443. return;
  1444. }
  1445. LastLocalImport->setNextLocalImport(Import);
  1446. LastLocalImport = Import;
  1447. }
  1448. //===----------------------------------------------------------------------===//
  1449. // Type Sizing and Analysis
  1450. //===----------------------------------------------------------------------===//
  1451. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1452. /// scalar floating point type.
  1453. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1454. switch (T->castAs<BuiltinType>()->getKind()) {
  1455. default:
  1456. llvm_unreachable("Not a floating point type!");
  1457. case BuiltinType::BFloat16:
  1458. return Target->getBFloat16Format();
  1459. case BuiltinType::Float16:
  1460. return Target->getHalfFormat();
  1461. case BuiltinType::Half:
  1462. // For HLSL, when the native half type is disabled, half will be treat as
  1463. // float.
  1464. if (getLangOpts().HLSL)
  1465. if (getLangOpts().NativeHalfType)
  1466. return Target->getHalfFormat();
  1467. else
  1468. return Target->getFloatFormat();
  1469. else
  1470. return Target->getHalfFormat();
  1471. case BuiltinType::Float: return Target->getFloatFormat();
  1472. case BuiltinType::Double: return Target->getDoubleFormat();
  1473. case BuiltinType::Ibm128:
  1474. return Target->getIbm128Format();
  1475. case BuiltinType::LongDouble:
  1476. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1477. return AuxTarget->getLongDoubleFormat();
  1478. return Target->getLongDoubleFormat();
  1479. case BuiltinType::Float128:
  1480. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1481. return AuxTarget->getFloat128Format();
  1482. return Target->getFloat128Format();
  1483. }
  1484. }
  1485. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1486. unsigned Align = Target->getCharWidth();
  1487. bool UseAlignAttrOnly = false;
  1488. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1489. Align = AlignFromAttr;
  1490. // __attribute__((aligned)) can increase or decrease alignment
  1491. // *except* on a struct or struct member, where it only increases
  1492. // alignment unless 'packed' is also specified.
  1493. //
  1494. // It is an error for alignas to decrease alignment, so we can
  1495. // ignore that possibility; Sema should diagnose it.
  1496. if (isa<FieldDecl>(D)) {
  1497. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1498. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1499. } else {
  1500. UseAlignAttrOnly = true;
  1501. }
  1502. }
  1503. else if (isa<FieldDecl>(D))
  1504. UseAlignAttrOnly =
  1505. D->hasAttr<PackedAttr>() ||
  1506. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1507. // If we're using the align attribute only, just ignore everything
  1508. // else about the declaration and its type.
  1509. if (UseAlignAttrOnly) {
  1510. // do nothing
  1511. } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  1512. QualType T = VD->getType();
  1513. if (const auto *RT = T->getAs<ReferenceType>()) {
  1514. if (ForAlignof)
  1515. T = RT->getPointeeType();
  1516. else
  1517. T = getPointerType(RT->getPointeeType());
  1518. }
  1519. QualType BaseT = getBaseElementType(T);
  1520. if (T->isFunctionType())
  1521. Align = getTypeInfoImpl(T.getTypePtr()).Align;
  1522. else if (!BaseT->isIncompleteType()) {
  1523. // Adjust alignments of declarations with array type by the
  1524. // large-array alignment on the target.
  1525. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1526. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1527. if (!ForAlignof && MinWidth) {
  1528. if (isa<VariableArrayType>(arrayType))
  1529. Align = std::max(Align, Target->getLargeArrayAlign());
  1530. else if (isa<ConstantArrayType>(arrayType) &&
  1531. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1532. Align = std::max(Align, Target->getLargeArrayAlign());
  1533. }
  1534. }
  1535. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1536. if (BaseT.getQualifiers().hasUnaligned())
  1537. Align = Target->getCharWidth();
  1538. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1539. if (VD->hasGlobalStorage() && !ForAlignof) {
  1540. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  1541. Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
  1542. }
  1543. }
  1544. }
  1545. // Fields can be subject to extra alignment constraints, like if
  1546. // the field is packed, the struct is packed, or the struct has a
  1547. // a max-field-alignment constraint (#pragma pack). So calculate
  1548. // the actual alignment of the field within the struct, and then
  1549. // (as we're expected to) constrain that by the alignment of the type.
  1550. if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
  1551. const RecordDecl *Parent = Field->getParent();
  1552. // We can only produce a sensible answer if the record is valid.
  1553. if (!Parent->isInvalidDecl()) {
  1554. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1555. // Start with the record's overall alignment.
  1556. unsigned FieldAlign = toBits(Layout.getAlignment());
  1557. // Use the GCD of that and the offset within the record.
  1558. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1559. if (Offset > 0) {
  1560. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1561. // which means we get to do this crazy thing instead of Euclid's.
  1562. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1563. if (LowBitOfOffset < FieldAlign)
  1564. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1565. }
  1566. Align = std::min(Align, FieldAlign);
  1567. }
  1568. }
  1569. }
  1570. // Some targets have hard limitation on the maximum requestable alignment in
  1571. // aligned attribute for static variables.
  1572. const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
  1573. const auto *VD = dyn_cast<VarDecl>(D);
  1574. if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
  1575. Align = std::min(Align, MaxAlignedAttr);
  1576. return toCharUnitsFromBits(Align);
  1577. }
  1578. CharUnits ASTContext::getExnObjectAlignment() const {
  1579. return toCharUnitsFromBits(Target->getExnObjectAlignment());
  1580. }
  1581. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1582. // chars. If the type is a record, its data size is returned. This is
  1583. // the size of the memcpy that's performed when assigning this type
  1584. // using a trivial copy/move assignment operator.
  1585. TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1586. TypeInfoChars Info = getTypeInfoInChars(T);
  1587. // In C++, objects can sometimes be allocated into the tail padding
  1588. // of a base-class subobject. We decide whether that's possible
  1589. // during class layout, so here we can just trust the layout results.
  1590. if (getLangOpts().CPlusPlus) {
  1591. if (const auto *RT = T->getAs<RecordType>()) {
  1592. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1593. Info.Width = layout.getDataSize();
  1594. }
  1595. }
  1596. return Info;
  1597. }
  1598. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1599. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1600. TypeInfoChars
  1601. static getConstantArrayInfoInChars(const ASTContext &Context,
  1602. const ConstantArrayType *CAT) {
  1603. TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
  1604. uint64_t Size = CAT->getSize().getZExtValue();
  1605. assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
  1606. (uint64_t)(-1)/Size) &&
  1607. "Overflow in array type char size evaluation");
  1608. uint64_t Width = EltInfo.Width.getQuantity() * Size;
  1609. unsigned Align = EltInfo.Align.getQuantity();
  1610. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1611. Context.getTargetInfo().getPointerWidth(LangAS::Default) == 64)
  1612. Width = llvm::alignTo(Width, Align);
  1613. return TypeInfoChars(CharUnits::fromQuantity(Width),
  1614. CharUnits::fromQuantity(Align),
  1615. EltInfo.AlignRequirement);
  1616. }
  1617. TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
  1618. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1619. return getConstantArrayInfoInChars(*this, CAT);
  1620. TypeInfo Info = getTypeInfo(T);
  1621. return TypeInfoChars(toCharUnitsFromBits(Info.Width),
  1622. toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
  1623. }
  1624. TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
  1625. return getTypeInfoInChars(T.getTypePtr());
  1626. }
  1627. bool ASTContext::isPromotableIntegerType(QualType T) const {
  1628. // HLSL doesn't promote all small integer types to int, it
  1629. // just uses the rank-based promotion rules for all types.
  1630. if (getLangOpts().HLSL)
  1631. return false;
  1632. if (const auto *BT = T->getAs<BuiltinType>())
  1633. switch (BT->getKind()) {
  1634. case BuiltinType::Bool:
  1635. case BuiltinType::Char_S:
  1636. case BuiltinType::Char_U:
  1637. case BuiltinType::SChar:
  1638. case BuiltinType::UChar:
  1639. case BuiltinType::Short:
  1640. case BuiltinType::UShort:
  1641. case BuiltinType::WChar_S:
  1642. case BuiltinType::WChar_U:
  1643. case BuiltinType::Char8:
  1644. case BuiltinType::Char16:
  1645. case BuiltinType::Char32:
  1646. return true;
  1647. default:
  1648. return false;
  1649. }
  1650. // Enumerated types are promotable to their compatible integer types
  1651. // (C99 6.3.1.1) a.k.a. its underlying type (C++ [conv.prom]p2).
  1652. if (const auto *ET = T->getAs<EnumType>()) {
  1653. if (T->isDependentType() || ET->getDecl()->getPromotionType().isNull() ||
  1654. ET->getDecl()->isScoped())
  1655. return false;
  1656. return true;
  1657. }
  1658. return false;
  1659. }
  1660. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1661. return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
  1662. }
  1663. bool ASTContext::isAlignmentRequired(QualType T) const {
  1664. return isAlignmentRequired(T.getTypePtr());
  1665. }
  1666. unsigned ASTContext::getTypeAlignIfKnown(QualType T,
  1667. bool NeedsPreferredAlignment) const {
  1668. // An alignment on a typedef overrides anything else.
  1669. if (const auto *TT = T->getAs<TypedefType>())
  1670. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1671. return Align;
  1672. // If we have an (array of) complete type, we're done.
  1673. T = getBaseElementType(T);
  1674. if (!T->isIncompleteType())
  1675. return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
  1676. // If we had an array type, its element type might be a typedef
  1677. // type with an alignment attribute.
  1678. if (const auto *TT = T->getAs<TypedefType>())
  1679. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1680. return Align;
  1681. // Otherwise, see if the declaration of the type had an attribute.
  1682. if (const auto *TT = T->getAs<TagType>())
  1683. return TT->getDecl()->getMaxAlignment();
  1684. return 0;
  1685. }
  1686. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1687. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1688. if (I != MemoizedTypeInfo.end())
  1689. return I->second;
  1690. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1691. TypeInfo TI = getTypeInfoImpl(T);
  1692. MemoizedTypeInfo[T] = TI;
  1693. return TI;
  1694. }
  1695. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1696. /// method does not work on incomplete types.
  1697. ///
  1698. /// FIXME: Pointers into different addr spaces could have different sizes and
  1699. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1700. /// should take a QualType, &c.
  1701. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1702. uint64_t Width = 0;
  1703. unsigned Align = 8;
  1704. AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
  1705. LangAS AS = LangAS::Default;
  1706. switch (T->getTypeClass()) {
  1707. #define TYPE(Class, Base)
  1708. #define ABSTRACT_TYPE(Class, Base)
  1709. #define NON_CANONICAL_TYPE(Class, Base)
  1710. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1711. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1712. case Type::Class: \
  1713. assert(!T->isDependentType() && "should not see dependent types here"); \
  1714. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1715. #include "clang/AST/TypeNodes.inc"
  1716. llvm_unreachable("Should not see dependent types");
  1717. case Type::FunctionNoProto:
  1718. case Type::FunctionProto:
  1719. // GCC extension: alignof(function) = 32 bits
  1720. Width = 0;
  1721. Align = 32;
  1722. break;
  1723. case Type::IncompleteArray:
  1724. case Type::VariableArray:
  1725. case Type::ConstantArray: {
  1726. // Model non-constant sized arrays as size zero, but track the alignment.
  1727. uint64_t Size = 0;
  1728. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1729. Size = CAT->getSize().getZExtValue();
  1730. TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
  1731. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1732. "Overflow in array type bit size evaluation");
  1733. Width = EltInfo.Width * Size;
  1734. Align = EltInfo.Align;
  1735. AlignRequirement = EltInfo.AlignRequirement;
  1736. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1737. getTargetInfo().getPointerWidth(LangAS::Default) == 64)
  1738. Width = llvm::alignTo(Width, Align);
  1739. break;
  1740. }
  1741. case Type::ExtVector:
  1742. case Type::Vector: {
  1743. const auto *VT = cast<VectorType>(T);
  1744. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1745. Width = VT->isExtVectorBoolType() ? VT->getNumElements()
  1746. : EltInfo.Width * VT->getNumElements();
  1747. // Enforce at least byte alignment.
  1748. Align = std::max<unsigned>(8, Width);
  1749. // If the alignment is not a power of 2, round up to the next power of 2.
  1750. // This happens for non-power-of-2 length vectors.
  1751. if (Align & (Align-1)) {
  1752. Align = llvm::NextPowerOf2(Align);
  1753. Width = llvm::alignTo(Width, Align);
  1754. }
  1755. // Adjust the alignment based on the target max.
  1756. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1757. if (TargetVectorAlign && TargetVectorAlign < Align)
  1758. Align = TargetVectorAlign;
  1759. if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
  1760. // Adjust the alignment for fixed-length SVE vectors. This is important
  1761. // for non-power-of-2 vector lengths.
  1762. Align = 128;
  1763. else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  1764. // Adjust the alignment for fixed-length SVE predicates.
  1765. Align = 16;
  1766. break;
  1767. }
  1768. case Type::ConstantMatrix: {
  1769. const auto *MT = cast<ConstantMatrixType>(T);
  1770. TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
  1771. // The internal layout of a matrix value is implementation defined.
  1772. // Initially be ABI compatible with arrays with respect to alignment and
  1773. // size.
  1774. Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
  1775. Align = ElementInfo.Align;
  1776. break;
  1777. }
  1778. case Type::Builtin:
  1779. switch (cast<BuiltinType>(T)->getKind()) {
  1780. default: llvm_unreachable("Unknown builtin type!");
  1781. case BuiltinType::Void:
  1782. // GCC extension: alignof(void) = 8 bits.
  1783. Width = 0;
  1784. Align = 8;
  1785. break;
  1786. case BuiltinType::Bool:
  1787. Width = Target->getBoolWidth();
  1788. Align = Target->getBoolAlign();
  1789. break;
  1790. case BuiltinType::Char_S:
  1791. case BuiltinType::Char_U:
  1792. case BuiltinType::UChar:
  1793. case BuiltinType::SChar:
  1794. case BuiltinType::Char8:
  1795. Width = Target->getCharWidth();
  1796. Align = Target->getCharAlign();
  1797. break;
  1798. case BuiltinType::WChar_S:
  1799. case BuiltinType::WChar_U:
  1800. Width = Target->getWCharWidth();
  1801. Align = Target->getWCharAlign();
  1802. break;
  1803. case BuiltinType::Char16:
  1804. Width = Target->getChar16Width();
  1805. Align = Target->getChar16Align();
  1806. break;
  1807. case BuiltinType::Char32:
  1808. Width = Target->getChar32Width();
  1809. Align = Target->getChar32Align();
  1810. break;
  1811. case BuiltinType::UShort:
  1812. case BuiltinType::Short:
  1813. Width = Target->getShortWidth();
  1814. Align = Target->getShortAlign();
  1815. break;
  1816. case BuiltinType::UInt:
  1817. case BuiltinType::Int:
  1818. Width = Target->getIntWidth();
  1819. Align = Target->getIntAlign();
  1820. break;
  1821. case BuiltinType::ULong:
  1822. case BuiltinType::Long:
  1823. Width = Target->getLongWidth();
  1824. Align = Target->getLongAlign();
  1825. break;
  1826. case BuiltinType::ULongLong:
  1827. case BuiltinType::LongLong:
  1828. Width = Target->getLongLongWidth();
  1829. Align = Target->getLongLongAlign();
  1830. break;
  1831. case BuiltinType::Int128:
  1832. case BuiltinType::UInt128:
  1833. Width = 128;
  1834. Align = Target->getInt128Align();
  1835. break;
  1836. case BuiltinType::ShortAccum:
  1837. case BuiltinType::UShortAccum:
  1838. case BuiltinType::SatShortAccum:
  1839. case BuiltinType::SatUShortAccum:
  1840. Width = Target->getShortAccumWidth();
  1841. Align = Target->getShortAccumAlign();
  1842. break;
  1843. case BuiltinType::Accum:
  1844. case BuiltinType::UAccum:
  1845. case BuiltinType::SatAccum:
  1846. case BuiltinType::SatUAccum:
  1847. Width = Target->getAccumWidth();
  1848. Align = Target->getAccumAlign();
  1849. break;
  1850. case BuiltinType::LongAccum:
  1851. case BuiltinType::ULongAccum:
  1852. case BuiltinType::SatLongAccum:
  1853. case BuiltinType::SatULongAccum:
  1854. Width = Target->getLongAccumWidth();
  1855. Align = Target->getLongAccumAlign();
  1856. break;
  1857. case BuiltinType::ShortFract:
  1858. case BuiltinType::UShortFract:
  1859. case BuiltinType::SatShortFract:
  1860. case BuiltinType::SatUShortFract:
  1861. Width = Target->getShortFractWidth();
  1862. Align = Target->getShortFractAlign();
  1863. break;
  1864. case BuiltinType::Fract:
  1865. case BuiltinType::UFract:
  1866. case BuiltinType::SatFract:
  1867. case BuiltinType::SatUFract:
  1868. Width = Target->getFractWidth();
  1869. Align = Target->getFractAlign();
  1870. break;
  1871. case BuiltinType::LongFract:
  1872. case BuiltinType::ULongFract:
  1873. case BuiltinType::SatLongFract:
  1874. case BuiltinType::SatULongFract:
  1875. Width = Target->getLongFractWidth();
  1876. Align = Target->getLongFractAlign();
  1877. break;
  1878. case BuiltinType::BFloat16:
  1879. if (Target->hasBFloat16Type()) {
  1880. Width = Target->getBFloat16Width();
  1881. Align = Target->getBFloat16Align();
  1882. }
  1883. break;
  1884. case BuiltinType::Float16:
  1885. case BuiltinType::Half:
  1886. if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
  1887. !getLangOpts().OpenMPIsDevice) {
  1888. Width = Target->getHalfWidth();
  1889. Align = Target->getHalfAlign();
  1890. } else {
  1891. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1892. "Expected OpenMP device compilation.");
  1893. Width = AuxTarget->getHalfWidth();
  1894. Align = AuxTarget->getHalfAlign();
  1895. }
  1896. break;
  1897. case BuiltinType::Float:
  1898. Width = Target->getFloatWidth();
  1899. Align = Target->getFloatAlign();
  1900. break;
  1901. case BuiltinType::Double:
  1902. Width = Target->getDoubleWidth();
  1903. Align = Target->getDoubleAlign();
  1904. break;
  1905. case BuiltinType::Ibm128:
  1906. Width = Target->getIbm128Width();
  1907. Align = Target->getIbm128Align();
  1908. break;
  1909. case BuiltinType::LongDouble:
  1910. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1911. (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
  1912. Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
  1913. Width = AuxTarget->getLongDoubleWidth();
  1914. Align = AuxTarget->getLongDoubleAlign();
  1915. } else {
  1916. Width = Target->getLongDoubleWidth();
  1917. Align = Target->getLongDoubleAlign();
  1918. }
  1919. break;
  1920. case BuiltinType::Float128:
  1921. if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
  1922. !getLangOpts().OpenMPIsDevice) {
  1923. Width = Target->getFloat128Width();
  1924. Align = Target->getFloat128Align();
  1925. } else {
  1926. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1927. "Expected OpenMP device compilation.");
  1928. Width = AuxTarget->getFloat128Width();
  1929. Align = AuxTarget->getFloat128Align();
  1930. }
  1931. break;
  1932. case BuiltinType::NullPtr:
  1933. // C++ 3.9.1p11: sizeof(nullptr_t) == sizeof(void*)
  1934. Width = Target->getPointerWidth(LangAS::Default);
  1935. Align = Target->getPointerAlign(LangAS::Default);
  1936. break;
  1937. case BuiltinType::ObjCId:
  1938. case BuiltinType::ObjCClass:
  1939. case BuiltinType::ObjCSel:
  1940. Width = Target->getPointerWidth(LangAS::Default);
  1941. Align = Target->getPointerAlign(LangAS::Default);
  1942. break;
  1943. case BuiltinType::OCLSampler:
  1944. case BuiltinType::OCLEvent:
  1945. case BuiltinType::OCLClkEvent:
  1946. case BuiltinType::OCLQueue:
  1947. case BuiltinType::OCLReserveID:
  1948. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1949. case BuiltinType::Id:
  1950. #include "clang/Basic/OpenCLImageTypes.def"
  1951. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1952. case BuiltinType::Id:
  1953. #include "clang/Basic/OpenCLExtensionTypes.def"
  1954. AS = Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
  1955. Width = Target->getPointerWidth(AS);
  1956. Align = Target->getPointerAlign(AS);
  1957. break;
  1958. // The SVE types are effectively target-specific. The length of an
  1959. // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
  1960. // of 128 bits. There is one predicate bit for each vector byte, so the
  1961. // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
  1962. //
  1963. // Because the length is only known at runtime, we use a dummy value
  1964. // of 0 for the static length. The alignment values are those defined
  1965. // by the Procedure Call Standard for the Arm Architecture.
  1966. #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
  1967. IsSigned, IsFP, IsBF) \
  1968. case BuiltinType::Id: \
  1969. Width = 0; \
  1970. Align = 128; \
  1971. break;
  1972. #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
  1973. case BuiltinType::Id: \
  1974. Width = 0; \
  1975. Align = 16; \
  1976. break;
  1977. #include "clang/Basic/AArch64SVEACLETypes.def"
  1978. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  1979. case BuiltinType::Id: \
  1980. Width = Size; \
  1981. Align = Size; \
  1982. break;
  1983. #include "clang/Basic/PPCTypes.def"
  1984. #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
  1985. IsFP) \
  1986. case BuiltinType::Id: \
  1987. Width = 0; \
  1988. Align = ElBits; \
  1989. break;
  1990. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
  1991. case BuiltinType::Id: \
  1992. Width = 0; \
  1993. Align = 8; \
  1994. break;
  1995. #include "clang/Basic/RISCVVTypes.def"
  1996. }
  1997. break;
  1998. case Type::ObjCObjectPointer:
  1999. Width = Target->getPointerWidth(LangAS::Default);
  2000. Align = Target->getPointerAlign(LangAS::Default);
  2001. break;
  2002. case Type::BlockPointer:
  2003. AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
  2004. Width = Target->getPointerWidth(AS);
  2005. Align = Target->getPointerAlign(AS);
  2006. break;
  2007. case Type::LValueReference:
  2008. case Type::RValueReference:
  2009. // alignof and sizeof should never enter this code path here, so we go
  2010. // the pointer route.
  2011. AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
  2012. Width = Target->getPointerWidth(AS);
  2013. Align = Target->getPointerAlign(AS);
  2014. break;
  2015. case Type::Pointer:
  2016. AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
  2017. Width = Target->getPointerWidth(AS);
  2018. Align = Target->getPointerAlign(AS);
  2019. break;
  2020. case Type::MemberPointer: {
  2021. const auto *MPT = cast<MemberPointerType>(T);
  2022. CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
  2023. Width = MPI.Width;
  2024. Align = MPI.Align;
  2025. break;
  2026. }
  2027. case Type::Complex: {
  2028. // Complex types have the same alignment as their elements, but twice the
  2029. // size.
  2030. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  2031. Width = EltInfo.Width * 2;
  2032. Align = EltInfo.Align;
  2033. break;
  2034. }
  2035. case Type::ObjCObject:
  2036. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  2037. case Type::Adjusted:
  2038. case Type::Decayed:
  2039. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  2040. case Type::ObjCInterface: {
  2041. const auto *ObjCI = cast<ObjCInterfaceType>(T);
  2042. if (ObjCI->getDecl()->isInvalidDecl()) {
  2043. Width = 8;
  2044. Align = 8;
  2045. break;
  2046. }
  2047. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  2048. Width = toBits(Layout.getSize());
  2049. Align = toBits(Layout.getAlignment());
  2050. break;
  2051. }
  2052. case Type::BitInt: {
  2053. const auto *EIT = cast<BitIntType>(T);
  2054. Align =
  2055. std::min(static_cast<unsigned>(std::max(
  2056. getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
  2057. Target->getLongLongAlign());
  2058. Width = llvm::alignTo(EIT->getNumBits(), Align);
  2059. break;
  2060. }
  2061. case Type::Record:
  2062. case Type::Enum: {
  2063. const auto *TT = cast<TagType>(T);
  2064. if (TT->getDecl()->isInvalidDecl()) {
  2065. Width = 8;
  2066. Align = 8;
  2067. break;
  2068. }
  2069. if (const auto *ET = dyn_cast<EnumType>(TT)) {
  2070. const EnumDecl *ED = ET->getDecl();
  2071. TypeInfo Info =
  2072. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  2073. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  2074. Info.Align = AttrAlign;
  2075. Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
  2076. }
  2077. return Info;
  2078. }
  2079. const auto *RT = cast<RecordType>(TT);
  2080. const RecordDecl *RD = RT->getDecl();
  2081. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  2082. Width = toBits(Layout.getSize());
  2083. Align = toBits(Layout.getAlignment());
  2084. AlignRequirement = RD->hasAttr<AlignedAttr>()
  2085. ? AlignRequirementKind::RequiredByRecord
  2086. : AlignRequirementKind::None;
  2087. break;
  2088. }
  2089. case Type::SubstTemplateTypeParm:
  2090. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  2091. getReplacementType().getTypePtr());
  2092. case Type::Auto:
  2093. case Type::DeducedTemplateSpecialization: {
  2094. const auto *A = cast<DeducedType>(T);
  2095. assert(!A->getDeducedType().isNull() &&
  2096. "cannot request the size of an undeduced or dependent auto type");
  2097. return getTypeInfo(A->getDeducedType().getTypePtr());
  2098. }
  2099. case Type::Paren:
  2100. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  2101. case Type::MacroQualified:
  2102. return getTypeInfo(
  2103. cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
  2104. case Type::ObjCTypeParam:
  2105. return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
  2106. case Type::Using:
  2107. return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
  2108. case Type::Typedef: {
  2109. const auto *TT = cast<TypedefType>(T);
  2110. TypeInfo Info = getTypeInfo(TT->desugar().getTypePtr());
  2111. // If the typedef has an aligned attribute on it, it overrides any computed
  2112. // alignment we have. This violates the GCC documentation (which says that
  2113. // attribute(aligned) can only round up) but matches its implementation.
  2114. if (unsigned AttrAlign = TT->getDecl()->getMaxAlignment()) {
  2115. Align = AttrAlign;
  2116. AlignRequirement = AlignRequirementKind::RequiredByTypedef;
  2117. } else {
  2118. Align = Info.Align;
  2119. AlignRequirement = Info.AlignRequirement;
  2120. }
  2121. Width = Info.Width;
  2122. break;
  2123. }
  2124. case Type::Elaborated:
  2125. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  2126. case Type::Attributed:
  2127. return getTypeInfo(
  2128. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  2129. case Type::BTFTagAttributed:
  2130. return getTypeInfo(
  2131. cast<BTFTagAttributedType>(T)->getWrappedType().getTypePtr());
  2132. case Type::Atomic: {
  2133. // Start with the base type information.
  2134. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  2135. Width = Info.Width;
  2136. Align = Info.Align;
  2137. if (!Width) {
  2138. // An otherwise zero-sized type should still generate an
  2139. // atomic operation.
  2140. Width = Target->getCharWidth();
  2141. assert(Align);
  2142. } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
  2143. // If the size of the type doesn't exceed the platform's max
  2144. // atomic promotion width, make the size and alignment more
  2145. // favorable to atomic operations:
  2146. // Round the size up to a power of 2.
  2147. if (!llvm::isPowerOf2_64(Width))
  2148. Width = llvm::NextPowerOf2(Width);
  2149. // Set the alignment equal to the size.
  2150. Align = static_cast<unsigned>(Width);
  2151. }
  2152. }
  2153. break;
  2154. case Type::Pipe:
  2155. Width = Target->getPointerWidth(LangAS::opencl_global);
  2156. Align = Target->getPointerAlign(LangAS::opencl_global);
  2157. break;
  2158. }
  2159. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  2160. return TypeInfo(Width, Align, AlignRequirement);
  2161. }
  2162. unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
  2163. UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
  2164. if (I != MemoizedUnadjustedAlign.end())
  2165. return I->second;
  2166. unsigned UnadjustedAlign;
  2167. if (const auto *RT = T->getAs<RecordType>()) {
  2168. const RecordDecl *RD = RT->getDecl();
  2169. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  2170. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  2171. } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
  2172. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  2173. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  2174. } else {
  2175. UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
  2176. }
  2177. MemoizedUnadjustedAlign[T] = UnadjustedAlign;
  2178. return UnadjustedAlign;
  2179. }
  2180. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  2181. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  2182. return SimdAlign;
  2183. }
  2184. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  2185. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  2186. return CharUnits::fromQuantity(BitSize / getCharWidth());
  2187. }
  2188. /// toBits - Convert a size in characters to a size in characters.
  2189. int64_t ASTContext::toBits(CharUnits CharSize) const {
  2190. return CharSize.getQuantity() * getCharWidth();
  2191. }
  2192. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  2193. /// This method does not work on incomplete types.
  2194. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  2195. return getTypeInfoInChars(T).Width;
  2196. }
  2197. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  2198. return getTypeInfoInChars(T).Width;
  2199. }
  2200. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  2201. /// characters. This method does not work on incomplete types.
  2202. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  2203. return toCharUnitsFromBits(getTypeAlign(T));
  2204. }
  2205. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  2206. return toCharUnitsFromBits(getTypeAlign(T));
  2207. }
  2208. /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
  2209. /// type, in characters, before alignment adjustments. This method does
  2210. /// not work on incomplete types.
  2211. CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
  2212. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2213. }
  2214. CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
  2215. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2216. }
  2217. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  2218. /// type for the current target in bits. This can be different than the ABI
  2219. /// alignment in cases where it is beneficial for performance or backwards
  2220. /// compatibility preserving to overalign a data type. (Note: despite the name,
  2221. /// the preferred alignment is ABI-impacting, and not an optimization.)
  2222. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  2223. TypeInfo TI = getTypeInfo(T);
  2224. unsigned ABIAlign = TI.Align;
  2225. T = T->getBaseElementTypeUnsafe();
  2226. // The preferred alignment of member pointers is that of a pointer.
  2227. if (T->isMemberPointerType())
  2228. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  2229. if (!Target->allowsLargerPreferedTypeAlignment())
  2230. return ABIAlign;
  2231. if (const auto *RT = T->getAs<RecordType>()) {
  2232. const RecordDecl *RD = RT->getDecl();
  2233. // When used as part of a typedef, or together with a 'packed' attribute,
  2234. // the 'aligned' attribute can be used to decrease alignment. Note that the
  2235. // 'packed' case is already taken into consideration when computing the
  2236. // alignment, we only need to handle the typedef case here.
  2237. if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
  2238. RD->isInvalidDecl())
  2239. return ABIAlign;
  2240. unsigned PreferredAlign = static_cast<unsigned>(
  2241. toBits(getASTRecordLayout(RD).PreferredAlignment));
  2242. assert(PreferredAlign >= ABIAlign &&
  2243. "PreferredAlign should be at least as large as ABIAlign.");
  2244. return PreferredAlign;
  2245. }
  2246. // Double (and, for targets supporting AIX `power` alignment, long double) and
  2247. // long long should be naturally aligned (despite requiring less alignment) if
  2248. // possible.
  2249. if (const auto *CT = T->getAs<ComplexType>())
  2250. T = CT->getElementType().getTypePtr();
  2251. if (const auto *ET = T->getAs<EnumType>())
  2252. T = ET->getDecl()->getIntegerType().getTypePtr();
  2253. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  2254. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  2255. T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  2256. (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
  2257. Target->defaultsToAIXPowerAlignment()))
  2258. // Don't increase the alignment if an alignment attribute was specified on a
  2259. // typedef declaration.
  2260. if (!TI.isAlignRequired())
  2261. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  2262. return ABIAlign;
  2263. }
  2264. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  2265. /// for __attribute__((aligned)) on this target, to be used if no alignment
  2266. /// value is specified.
  2267. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
  2268. return getTargetInfo().getDefaultAlignForAttributeAligned();
  2269. }
  2270. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  2271. /// to a global variable of the specified type.
  2272. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  2273. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  2274. return std::max(getPreferredTypeAlign(T),
  2275. getTargetInfo().getMinGlobalAlign(TypeSize));
  2276. }
  2277. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  2278. /// should be given to a global variable of the specified type.
  2279. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  2280. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  2281. }
  2282. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  2283. CharUnits Offset = CharUnits::Zero();
  2284. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  2285. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  2286. Offset += Layout->getBaseClassOffset(Base);
  2287. Layout = &getASTRecordLayout(Base);
  2288. }
  2289. return Offset;
  2290. }
  2291. CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
  2292. const ValueDecl *MPD = MP.getMemberPointerDecl();
  2293. CharUnits ThisAdjustment = CharUnits::Zero();
  2294. ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
  2295. bool DerivedMember = MP.isMemberPointerToDerivedMember();
  2296. const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
  2297. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  2298. const CXXRecordDecl *Base = RD;
  2299. const CXXRecordDecl *Derived = Path[I];
  2300. if (DerivedMember)
  2301. std::swap(Base, Derived);
  2302. ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
  2303. RD = Path[I];
  2304. }
  2305. if (DerivedMember)
  2306. ThisAdjustment = -ThisAdjustment;
  2307. return ThisAdjustment;
  2308. }
  2309. /// DeepCollectObjCIvars -
  2310. /// This routine first collects all declared, but not synthesized, ivars in
  2311. /// super class and then collects all ivars, including those synthesized for
  2312. /// current class. This routine is used for implementation of current class
  2313. /// when all ivars, declared and synthesized are known.
  2314. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  2315. bool leafClass,
  2316. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  2317. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  2318. DeepCollectObjCIvars(SuperClass, false, Ivars);
  2319. if (!leafClass) {
  2320. llvm::append_range(Ivars, OI->ivars());
  2321. } else {
  2322. auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  2323. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  2324. Iv= Iv->getNextIvar())
  2325. Ivars.push_back(Iv);
  2326. }
  2327. }
  2328. /// CollectInheritedProtocols - Collect all protocols in current class and
  2329. /// those inherited by it.
  2330. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  2331. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  2332. if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2333. // We can use protocol_iterator here instead of
  2334. // all_referenced_protocol_iterator since we are walking all categories.
  2335. for (auto *Proto : OI->all_referenced_protocols()) {
  2336. CollectInheritedProtocols(Proto, Protocols);
  2337. }
  2338. // Categories of this Interface.
  2339. for (const auto *Cat : OI->visible_categories())
  2340. CollectInheritedProtocols(Cat, Protocols);
  2341. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  2342. while (SD) {
  2343. CollectInheritedProtocols(SD, Protocols);
  2344. SD = SD->getSuperClass();
  2345. }
  2346. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2347. for (auto *Proto : OC->protocols()) {
  2348. CollectInheritedProtocols(Proto, Protocols);
  2349. }
  2350. } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  2351. // Insert the protocol.
  2352. if (!Protocols.insert(
  2353. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  2354. return;
  2355. for (auto *Proto : OP->protocols())
  2356. CollectInheritedProtocols(Proto, Protocols);
  2357. }
  2358. }
  2359. static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
  2360. const RecordDecl *RD) {
  2361. assert(RD->isUnion() && "Must be union type");
  2362. CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
  2363. for (const auto *Field : RD->fields()) {
  2364. if (!Context.hasUniqueObjectRepresentations(Field->getType()))
  2365. return false;
  2366. CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
  2367. if (FieldSize != UnionSize)
  2368. return false;
  2369. }
  2370. return !RD->field_empty();
  2371. }
  2372. static int64_t getSubobjectOffset(const FieldDecl *Field,
  2373. const ASTContext &Context,
  2374. const clang::ASTRecordLayout & /*Layout*/) {
  2375. return Context.getFieldOffset(Field);
  2376. }
  2377. static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
  2378. const ASTContext &Context,
  2379. const clang::ASTRecordLayout &Layout) {
  2380. return Context.toBits(Layout.getBaseClassOffset(RD));
  2381. }
  2382. static std::optional<int64_t>
  2383. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2384. const RecordDecl *RD);
  2385. static std::optional<int64_t>
  2386. getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
  2387. if (Field->getType()->isRecordType()) {
  2388. const RecordDecl *RD = Field->getType()->getAsRecordDecl();
  2389. if (!RD->isUnion())
  2390. return structHasUniqueObjectRepresentations(Context, RD);
  2391. }
  2392. // A _BitInt type may not be unique if it has padding bits
  2393. // but if it is a bitfield the padding bits are not used.
  2394. bool IsBitIntType = Field->getType()->isBitIntType();
  2395. if (!Field->getType()->isReferenceType() && !IsBitIntType &&
  2396. !Context.hasUniqueObjectRepresentations(Field->getType()))
  2397. return std::nullopt;
  2398. int64_t FieldSizeInBits =
  2399. Context.toBits(Context.getTypeSizeInChars(Field->getType()));
  2400. if (Field->isBitField()) {
  2401. int64_t BitfieldSize = Field->getBitWidthValue(Context);
  2402. if (IsBitIntType) {
  2403. if ((unsigned)BitfieldSize >
  2404. cast<BitIntType>(Field->getType())->getNumBits())
  2405. return std::nullopt;
  2406. } else if (BitfieldSize > FieldSizeInBits) {
  2407. return std::nullopt;
  2408. }
  2409. FieldSizeInBits = BitfieldSize;
  2410. } else if (IsBitIntType &&
  2411. !Context.hasUniqueObjectRepresentations(Field->getType())) {
  2412. return std::nullopt;
  2413. }
  2414. return FieldSizeInBits;
  2415. }
  2416. static std::optional<int64_t>
  2417. getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
  2418. return structHasUniqueObjectRepresentations(Context, RD);
  2419. }
  2420. template <typename RangeT>
  2421. static std::optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
  2422. const RangeT &Subobjects, int64_t CurOffsetInBits,
  2423. const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
  2424. for (const auto *Subobject : Subobjects) {
  2425. std::optional<int64_t> SizeInBits =
  2426. getSubobjectSizeInBits(Subobject, Context);
  2427. if (!SizeInBits)
  2428. return std::nullopt;
  2429. if (*SizeInBits != 0) {
  2430. int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
  2431. if (Offset != CurOffsetInBits)
  2432. return std::nullopt;
  2433. CurOffsetInBits += *SizeInBits;
  2434. }
  2435. }
  2436. return CurOffsetInBits;
  2437. }
  2438. static std::optional<int64_t>
  2439. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2440. const RecordDecl *RD) {
  2441. assert(!RD->isUnion() && "Must be struct/class type");
  2442. const auto &Layout = Context.getASTRecordLayout(RD);
  2443. int64_t CurOffsetInBits = 0;
  2444. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
  2445. if (ClassDecl->isDynamicClass())
  2446. return std::nullopt;
  2447. SmallVector<CXXRecordDecl *, 4> Bases;
  2448. for (const auto &Base : ClassDecl->bases()) {
  2449. // Empty types can be inherited from, and non-empty types can potentially
  2450. // have tail padding, so just make sure there isn't an error.
  2451. Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
  2452. }
  2453. llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
  2454. return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
  2455. });
  2456. std::optional<int64_t> OffsetAfterBases =
  2457. structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
  2458. Context, Layout);
  2459. if (!OffsetAfterBases)
  2460. return std::nullopt;
  2461. CurOffsetInBits = *OffsetAfterBases;
  2462. }
  2463. std::optional<int64_t> OffsetAfterFields =
  2464. structSubobjectsHaveUniqueObjectRepresentations(
  2465. RD->fields(), CurOffsetInBits, Context, Layout);
  2466. if (!OffsetAfterFields)
  2467. return std::nullopt;
  2468. CurOffsetInBits = *OffsetAfterFields;
  2469. return CurOffsetInBits;
  2470. }
  2471. bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
  2472. // C++17 [meta.unary.prop]:
  2473. // The predicate condition for a template specialization
  2474. // has_unique_object_representations<T> shall be
  2475. // satisfied if and only if:
  2476. // (9.1) - T is trivially copyable, and
  2477. // (9.2) - any two objects of type T with the same value have the same
  2478. // object representation, where two objects
  2479. // of array or non-union class type are considered to have the same value
  2480. // if their respective sequences of
  2481. // direct subobjects have the same values, and two objects of union type
  2482. // are considered to have the same
  2483. // value if they have the same active member and the corresponding members
  2484. // have the same value.
  2485. // The set of scalar types for which this condition holds is
  2486. // implementation-defined. [ Note: If a type has padding
  2487. // bits, the condition does not hold; otherwise, the condition holds true
  2488. // for unsigned integral types. -- end note ]
  2489. assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
  2490. // Arrays are unique only if their element type is unique.
  2491. if (Ty->isArrayType())
  2492. return hasUniqueObjectRepresentations(getBaseElementType(Ty));
  2493. // (9.1) - T is trivially copyable...
  2494. if (!Ty.isTriviallyCopyableType(*this))
  2495. return false;
  2496. // All integrals and enums are unique.
  2497. if (Ty->isIntegralOrEnumerationType()) {
  2498. // Except _BitInt types that have padding bits.
  2499. if (const auto *BIT = dyn_cast<BitIntType>(Ty))
  2500. return getTypeSize(BIT) == BIT->getNumBits();
  2501. return true;
  2502. }
  2503. // All other pointers are unique.
  2504. if (Ty->isPointerType())
  2505. return true;
  2506. if (Ty->isMemberPointerType()) {
  2507. const auto *MPT = Ty->getAs<MemberPointerType>();
  2508. return !ABI->getMemberPointerInfo(MPT).HasPadding;
  2509. }
  2510. if (Ty->isRecordType()) {
  2511. const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
  2512. if (Record->isInvalidDecl())
  2513. return false;
  2514. if (Record->isUnion())
  2515. return unionHasUniqueObjectRepresentations(*this, Record);
  2516. std::optional<int64_t> StructSize =
  2517. structHasUniqueObjectRepresentations(*this, Record);
  2518. return StructSize && *StructSize == static_cast<int64_t>(getTypeSize(Ty));
  2519. }
  2520. // FIXME: More cases to handle here (list by rsmith):
  2521. // vectors (careful about, eg, vector of 3 foo)
  2522. // _Complex int and friends
  2523. // _Atomic T
  2524. // Obj-C block pointers
  2525. // Obj-C object pointers
  2526. // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
  2527. // clk_event_t, queue_t, reserve_id_t)
  2528. // There're also Obj-C class types and the Obj-C selector type, but I think it
  2529. // makes sense for those to return false here.
  2530. return false;
  2531. }
  2532. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  2533. unsigned count = 0;
  2534. // Count ivars declared in class extension.
  2535. for (const auto *Ext : OI->known_extensions())
  2536. count += Ext->ivar_size();
  2537. // Count ivar defined in this class's implementation. This
  2538. // includes synthesized ivars.
  2539. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  2540. count += ImplDecl->ivar_size();
  2541. return count;
  2542. }
  2543. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  2544. if (!E)
  2545. return false;
  2546. // nullptr_t is always treated as null.
  2547. if (E->getType()->isNullPtrType()) return true;
  2548. if (E->getType()->isAnyPointerType() &&
  2549. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  2550. Expr::NPC_ValueDependentIsNull))
  2551. return true;
  2552. // Unfortunately, __null has type 'int'.
  2553. if (isa<GNUNullExpr>(E)) return true;
  2554. return false;
  2555. }
  2556. /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
  2557. /// exists.
  2558. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  2559. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2560. I = ObjCImpls.find(D);
  2561. if (I != ObjCImpls.end())
  2562. return cast<ObjCImplementationDecl>(I->second);
  2563. return nullptr;
  2564. }
  2565. /// Get the implementation of ObjCCategoryDecl, or nullptr if none
  2566. /// exists.
  2567. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  2568. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2569. I = ObjCImpls.find(D);
  2570. if (I != ObjCImpls.end())
  2571. return cast<ObjCCategoryImplDecl>(I->second);
  2572. return nullptr;
  2573. }
  2574. /// Set the implementation of ObjCInterfaceDecl.
  2575. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  2576. ObjCImplementationDecl *ImplD) {
  2577. assert(IFaceD && ImplD && "Passed null params");
  2578. ObjCImpls[IFaceD] = ImplD;
  2579. }
  2580. /// Set the implementation of ObjCCategoryDecl.
  2581. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  2582. ObjCCategoryImplDecl *ImplD) {
  2583. assert(CatD && ImplD && "Passed null params");
  2584. ObjCImpls[CatD] = ImplD;
  2585. }
  2586. const ObjCMethodDecl *
  2587. ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
  2588. return ObjCMethodRedecls.lookup(MD);
  2589. }
  2590. void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
  2591. const ObjCMethodDecl *Redecl) {
  2592. assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
  2593. ObjCMethodRedecls[MD] = Redecl;
  2594. }
  2595. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  2596. const NamedDecl *ND) const {
  2597. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  2598. return ID;
  2599. if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  2600. return CD->getClassInterface();
  2601. if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  2602. return IMD->getClassInterface();
  2603. return nullptr;
  2604. }
  2605. /// Get the copy initialization expression of VarDecl, or nullptr if
  2606. /// none exists.
  2607. BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
  2608. assert(VD && "Passed null params");
  2609. assert(VD->hasAttr<BlocksAttr>() &&
  2610. "getBlockVarCopyInits - not __block var");
  2611. auto I = BlockVarCopyInits.find(VD);
  2612. if (I != BlockVarCopyInits.end())
  2613. return I->second;
  2614. return {nullptr, false};
  2615. }
  2616. /// Set the copy initialization expression of a block var decl.
  2617. void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
  2618. bool CanThrow) {
  2619. assert(VD && CopyExpr && "Passed null params");
  2620. assert(VD->hasAttr<BlocksAttr>() &&
  2621. "setBlockVarCopyInits - not __block var");
  2622. BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
  2623. }
  2624. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  2625. unsigned DataSize) const {
  2626. if (!DataSize)
  2627. DataSize = TypeLoc::getFullDataSizeForType(T);
  2628. else
  2629. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  2630. "incorrect data size provided to CreateTypeSourceInfo!");
  2631. auto *TInfo =
  2632. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  2633. new (TInfo) TypeSourceInfo(T);
  2634. return TInfo;
  2635. }
  2636. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  2637. SourceLocation L) const {
  2638. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  2639. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  2640. return DI;
  2641. }
  2642. const ASTRecordLayout &
  2643. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  2644. return getObjCLayout(D, nullptr);
  2645. }
  2646. const ASTRecordLayout &
  2647. ASTContext::getASTObjCImplementationLayout(
  2648. const ObjCImplementationDecl *D) const {
  2649. return getObjCLayout(D->getClassInterface(), D);
  2650. }
  2651. static auto getCanonicalTemplateArguments(const ASTContext &C,
  2652. ArrayRef<TemplateArgument> Args,
  2653. bool &AnyNonCanonArgs) {
  2654. SmallVector<TemplateArgument, 16> CanonArgs(Args);
  2655. for (auto &Arg : CanonArgs) {
  2656. TemplateArgument OrigArg = Arg;
  2657. Arg = C.getCanonicalTemplateArgument(Arg);
  2658. AnyNonCanonArgs |= !Arg.structurallyEquals(OrigArg);
  2659. }
  2660. return CanonArgs;
  2661. }
  2662. //===----------------------------------------------------------------------===//
  2663. // Type creation/memoization methods
  2664. //===----------------------------------------------------------------------===//
  2665. QualType
  2666. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  2667. unsigned fastQuals = quals.getFastQualifiers();
  2668. quals.removeFastQualifiers();
  2669. // Check if we've already instantiated this type.
  2670. llvm::FoldingSetNodeID ID;
  2671. ExtQuals::Profile(ID, baseType, quals);
  2672. void *insertPos = nullptr;
  2673. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  2674. assert(eq->getQualifiers() == quals);
  2675. return QualType(eq, fastQuals);
  2676. }
  2677. // If the base type is not canonical, make the appropriate canonical type.
  2678. QualType canon;
  2679. if (!baseType->isCanonicalUnqualified()) {
  2680. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  2681. canonSplit.Quals.addConsistentQualifiers(quals);
  2682. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  2683. // Re-find the insert position.
  2684. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  2685. }
  2686. auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  2687. ExtQualNodes.InsertNode(eq, insertPos);
  2688. return QualType(eq, fastQuals);
  2689. }
  2690. QualType ASTContext::getAddrSpaceQualType(QualType T,
  2691. LangAS AddressSpace) const {
  2692. QualType CanT = getCanonicalType(T);
  2693. if (CanT.getAddressSpace() == AddressSpace)
  2694. return T;
  2695. // If we are composing extended qualifiers together, merge together
  2696. // into one ExtQuals node.
  2697. QualifierCollector Quals;
  2698. const Type *TypeNode = Quals.strip(T);
  2699. // If this type already has an address space specified, it cannot get
  2700. // another one.
  2701. assert(!Quals.hasAddressSpace() &&
  2702. "Type cannot be in multiple addr spaces!");
  2703. Quals.addAddressSpace(AddressSpace);
  2704. return getExtQualType(TypeNode, Quals);
  2705. }
  2706. QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
  2707. // If the type is not qualified with an address space, just return it
  2708. // immediately.
  2709. if (!T.hasAddressSpace())
  2710. return T;
  2711. // If we are composing extended qualifiers together, merge together
  2712. // into one ExtQuals node.
  2713. QualifierCollector Quals;
  2714. const Type *TypeNode;
  2715. while (T.hasAddressSpace()) {
  2716. TypeNode = Quals.strip(T);
  2717. // If the type no longer has an address space after stripping qualifiers,
  2718. // jump out.
  2719. if (!QualType(TypeNode, 0).hasAddressSpace())
  2720. break;
  2721. // There might be sugar in the way. Strip it and try again.
  2722. T = T.getSingleStepDesugaredType(*this);
  2723. }
  2724. Quals.removeAddressSpace();
  2725. // Removal of the address space can mean there are no longer any
  2726. // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
  2727. // or required.
  2728. if (Quals.hasNonFastQualifiers())
  2729. return getExtQualType(TypeNode, Quals);
  2730. else
  2731. return QualType(TypeNode, Quals.getFastQualifiers());
  2732. }
  2733. QualType ASTContext::getObjCGCQualType(QualType T,
  2734. Qualifiers::GC GCAttr) const {
  2735. QualType CanT = getCanonicalType(T);
  2736. if (CanT.getObjCGCAttr() == GCAttr)
  2737. return T;
  2738. if (const auto *ptr = T->getAs<PointerType>()) {
  2739. QualType Pointee = ptr->getPointeeType();
  2740. if (Pointee->isAnyPointerType()) {
  2741. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  2742. return getPointerType(ResultType);
  2743. }
  2744. }
  2745. // If we are composing extended qualifiers together, merge together
  2746. // into one ExtQuals node.
  2747. QualifierCollector Quals;
  2748. const Type *TypeNode = Quals.strip(T);
  2749. // If this type already has an ObjCGC specified, it cannot get
  2750. // another one.
  2751. assert(!Quals.hasObjCGCAttr() &&
  2752. "Type cannot have multiple ObjCGCs!");
  2753. Quals.addObjCGCAttr(GCAttr);
  2754. return getExtQualType(TypeNode, Quals);
  2755. }
  2756. QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
  2757. if (const PointerType *Ptr = T->getAs<PointerType>()) {
  2758. QualType Pointee = Ptr->getPointeeType();
  2759. if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
  2760. return getPointerType(removeAddrSpaceQualType(Pointee));
  2761. }
  2762. }
  2763. return T;
  2764. }
  2765. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  2766. FunctionType::ExtInfo Info) {
  2767. if (T->getExtInfo() == Info)
  2768. return T;
  2769. QualType Result;
  2770. if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  2771. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  2772. } else {
  2773. const auto *FPT = cast<FunctionProtoType>(T);
  2774. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2775. EPI.ExtInfo = Info;
  2776. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
  2777. }
  2778. return cast<FunctionType>(Result.getTypePtr());
  2779. }
  2780. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  2781. QualType ResultType) {
  2782. FD = FD->getMostRecentDecl();
  2783. while (true) {
  2784. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  2785. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2786. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
  2787. if (FunctionDecl *Next = FD->getPreviousDecl())
  2788. FD = Next;
  2789. else
  2790. break;
  2791. }
  2792. if (ASTMutationListener *L = getASTMutationListener())
  2793. L->DeducedReturnType(FD, ResultType);
  2794. }
  2795. /// Get a function type and produce the equivalent function type with the
  2796. /// specified exception specification. Type sugar that can be present on a
  2797. /// declaration of a function with an exception specification is permitted
  2798. /// and preserved. Other type sugar (for instance, typedefs) is not.
  2799. QualType ASTContext::getFunctionTypeWithExceptionSpec(
  2800. QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const {
  2801. // Might have some parens.
  2802. if (const auto *PT = dyn_cast<ParenType>(Orig))
  2803. return getParenType(
  2804. getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
  2805. // Might be wrapped in a macro qualified type.
  2806. if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
  2807. return getMacroQualifiedType(
  2808. getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
  2809. MQT->getMacroIdentifier());
  2810. // Might have a calling-convention attribute.
  2811. if (const auto *AT = dyn_cast<AttributedType>(Orig))
  2812. return getAttributedType(
  2813. AT->getAttrKind(),
  2814. getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
  2815. getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
  2816. // Anything else must be a function type. Rebuild it with the new exception
  2817. // specification.
  2818. const auto *Proto = Orig->castAs<FunctionProtoType>();
  2819. return getFunctionType(
  2820. Proto->getReturnType(), Proto->getParamTypes(),
  2821. Proto->getExtProtoInfo().withExceptionSpec(ESI));
  2822. }
  2823. bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
  2824. QualType U) const {
  2825. return hasSameType(T, U) ||
  2826. (getLangOpts().CPlusPlus17 &&
  2827. hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
  2828. getFunctionTypeWithExceptionSpec(U, EST_None)));
  2829. }
  2830. QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
  2831. if (const auto *Proto = T->getAs<FunctionProtoType>()) {
  2832. QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
  2833. SmallVector<QualType, 16> Args(Proto->param_types().size());
  2834. for (unsigned i = 0, n = Args.size(); i != n; ++i)
  2835. Args[i] = removePtrSizeAddrSpace(Proto->param_types()[i]);
  2836. return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
  2837. }
  2838. if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
  2839. QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
  2840. return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
  2841. }
  2842. return T;
  2843. }
  2844. bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
  2845. return hasSameType(T, U) ||
  2846. hasSameType(getFunctionTypeWithoutPtrSizes(T),
  2847. getFunctionTypeWithoutPtrSizes(U));
  2848. }
  2849. void ASTContext::adjustExceptionSpec(
  2850. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  2851. bool AsWritten) {
  2852. // Update the type.
  2853. QualType Updated =
  2854. getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
  2855. FD->setType(Updated);
  2856. if (!AsWritten)
  2857. return;
  2858. // Update the type in the type source information too.
  2859. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2860. // If the type and the type-as-written differ, we may need to update
  2861. // the type-as-written too.
  2862. if (TSInfo->getType() != FD->getType())
  2863. Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
  2864. // FIXME: When we get proper type location information for exceptions,
  2865. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2866. // up the TypeSourceInfo;
  2867. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2868. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2869. "TypeLoc size mismatch from updating exception specification");
  2870. TSInfo->overrideType(Updated);
  2871. }
  2872. }
  2873. /// getComplexType - Return the uniqued reference to the type for a complex
  2874. /// number with the specified element type.
  2875. QualType ASTContext::getComplexType(QualType T) const {
  2876. // Unique pointers, to guarantee there is only one pointer of a particular
  2877. // structure.
  2878. llvm::FoldingSetNodeID ID;
  2879. ComplexType::Profile(ID, T);
  2880. void *InsertPos = nullptr;
  2881. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2882. return QualType(CT, 0);
  2883. // If the pointee type isn't canonical, this won't be a canonical type either,
  2884. // so fill in the canonical type field.
  2885. QualType Canonical;
  2886. if (!T.isCanonical()) {
  2887. Canonical = getComplexType(getCanonicalType(T));
  2888. // Get the new insert position for the node we care about.
  2889. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2890. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2891. }
  2892. auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2893. Types.push_back(New);
  2894. ComplexTypes.InsertNode(New, InsertPos);
  2895. return QualType(New, 0);
  2896. }
  2897. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2898. /// the specified type.
  2899. QualType ASTContext::getPointerType(QualType T) const {
  2900. // Unique pointers, to guarantee there is only one pointer of a particular
  2901. // structure.
  2902. llvm::FoldingSetNodeID ID;
  2903. PointerType::Profile(ID, T);
  2904. void *InsertPos = nullptr;
  2905. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2906. return QualType(PT, 0);
  2907. // If the pointee type isn't canonical, this won't be a canonical type either,
  2908. // so fill in the canonical type field.
  2909. QualType Canonical;
  2910. if (!T.isCanonical()) {
  2911. Canonical = getPointerType(getCanonicalType(T));
  2912. // Get the new insert position for the node we care about.
  2913. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2914. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2915. }
  2916. auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2917. Types.push_back(New);
  2918. PointerTypes.InsertNode(New, InsertPos);
  2919. return QualType(New, 0);
  2920. }
  2921. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2922. llvm::FoldingSetNodeID ID;
  2923. AdjustedType::Profile(ID, Orig, New);
  2924. void *InsertPos = nullptr;
  2925. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2926. if (AT)
  2927. return QualType(AT, 0);
  2928. QualType Canonical = getCanonicalType(New);
  2929. // Get the new insert position for the node we care about.
  2930. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2931. assert(!AT && "Shouldn't be in the map!");
  2932. AT = new (*this, TypeAlignment)
  2933. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2934. Types.push_back(AT);
  2935. AdjustedTypes.InsertNode(AT, InsertPos);
  2936. return QualType(AT, 0);
  2937. }
  2938. QualType ASTContext::getDecayedType(QualType Orig, QualType Decayed) const {
  2939. llvm::FoldingSetNodeID ID;
  2940. AdjustedType::Profile(ID, Orig, Decayed);
  2941. void *InsertPos = nullptr;
  2942. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2943. if (AT)
  2944. return QualType(AT, 0);
  2945. QualType Canonical = getCanonicalType(Decayed);
  2946. // Get the new insert position for the node we care about.
  2947. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2948. assert(!AT && "Shouldn't be in the map!");
  2949. AT = new (*this, TypeAlignment) DecayedType(Orig, Decayed, Canonical);
  2950. Types.push_back(AT);
  2951. AdjustedTypes.InsertNode(AT, InsertPos);
  2952. return QualType(AT, 0);
  2953. }
  2954. QualType ASTContext::getDecayedType(QualType T) const {
  2955. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2956. QualType Decayed;
  2957. // C99 6.7.5.3p7:
  2958. // A declaration of a parameter as "array of type" shall be
  2959. // adjusted to "qualified pointer to type", where the type
  2960. // qualifiers (if any) are those specified within the [ and ] of
  2961. // the array type derivation.
  2962. if (T->isArrayType())
  2963. Decayed = getArrayDecayedType(T);
  2964. // C99 6.7.5.3p8:
  2965. // A declaration of a parameter as "function returning type"
  2966. // shall be adjusted to "pointer to function returning type", as
  2967. // in 6.3.2.1.
  2968. if (T->isFunctionType())
  2969. Decayed = getPointerType(T);
  2970. return getDecayedType(T, Decayed);
  2971. }
  2972. /// getBlockPointerType - Return the uniqued reference to the type for
  2973. /// a pointer to the specified block.
  2974. QualType ASTContext::getBlockPointerType(QualType T) const {
  2975. assert(T->isFunctionType() && "block of function types only");
  2976. // Unique pointers, to guarantee there is only one block of a particular
  2977. // structure.
  2978. llvm::FoldingSetNodeID ID;
  2979. BlockPointerType::Profile(ID, T);
  2980. void *InsertPos = nullptr;
  2981. if (BlockPointerType *PT =
  2982. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2983. return QualType(PT, 0);
  2984. // If the block pointee type isn't canonical, this won't be a canonical
  2985. // type either so fill in the canonical type field.
  2986. QualType Canonical;
  2987. if (!T.isCanonical()) {
  2988. Canonical = getBlockPointerType(getCanonicalType(T));
  2989. // Get the new insert position for the node we care about.
  2990. BlockPointerType *NewIP =
  2991. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2992. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2993. }
  2994. auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2995. Types.push_back(New);
  2996. BlockPointerTypes.InsertNode(New, InsertPos);
  2997. return QualType(New, 0);
  2998. }
  2999. /// getLValueReferenceType - Return the uniqued reference to the type for an
  3000. /// lvalue reference to the specified type.
  3001. QualType
  3002. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  3003. assert((!T->isPlaceholderType() ||
  3004. T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
  3005. "Unresolved placeholder type");
  3006. // Unique pointers, to guarantee there is only one pointer of a particular
  3007. // structure.
  3008. llvm::FoldingSetNodeID ID;
  3009. ReferenceType::Profile(ID, T, SpelledAsLValue);
  3010. void *InsertPos = nullptr;
  3011. if (LValueReferenceType *RT =
  3012. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  3013. return QualType(RT, 0);
  3014. const auto *InnerRef = T->getAs<ReferenceType>();
  3015. // If the referencee type isn't canonical, this won't be a canonical type
  3016. // either, so fill in the canonical type field.
  3017. QualType Canonical;
  3018. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  3019. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  3020. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  3021. // Get the new insert position for the node we care about.
  3022. LValueReferenceType *NewIP =
  3023. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  3024. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3025. }
  3026. auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  3027. SpelledAsLValue);
  3028. Types.push_back(New);
  3029. LValueReferenceTypes.InsertNode(New, InsertPos);
  3030. return QualType(New, 0);
  3031. }
  3032. /// getRValueReferenceType - Return the uniqued reference to the type for an
  3033. /// rvalue reference to the specified type.
  3034. QualType ASTContext::getRValueReferenceType(QualType T) const {
  3035. assert((!T->isPlaceholderType() ||
  3036. T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
  3037. "Unresolved placeholder type");
  3038. // Unique pointers, to guarantee there is only one pointer of a particular
  3039. // structure.
  3040. llvm::FoldingSetNodeID ID;
  3041. ReferenceType::Profile(ID, T, false);
  3042. void *InsertPos = nullptr;
  3043. if (RValueReferenceType *RT =
  3044. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  3045. return QualType(RT, 0);
  3046. const auto *InnerRef = T->getAs<ReferenceType>();
  3047. // If the referencee type isn't canonical, this won't be a canonical type
  3048. // either, so fill in the canonical type field.
  3049. QualType Canonical;
  3050. if (InnerRef || !T.isCanonical()) {
  3051. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  3052. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  3053. // Get the new insert position for the node we care about.
  3054. RValueReferenceType *NewIP =
  3055. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  3056. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3057. }
  3058. auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  3059. Types.push_back(New);
  3060. RValueReferenceTypes.InsertNode(New, InsertPos);
  3061. return QualType(New, 0);
  3062. }
  3063. /// getMemberPointerType - Return the uniqued reference to the type for a
  3064. /// member pointer to the specified type, in the specified class.
  3065. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  3066. // Unique pointers, to guarantee there is only one pointer of a particular
  3067. // structure.
  3068. llvm::FoldingSetNodeID ID;
  3069. MemberPointerType::Profile(ID, T, Cls);
  3070. void *InsertPos = nullptr;
  3071. if (MemberPointerType *PT =
  3072. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  3073. return QualType(PT, 0);
  3074. // If the pointee or class type isn't canonical, this won't be a canonical
  3075. // type either, so fill in the canonical type field.
  3076. QualType Canonical;
  3077. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  3078. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  3079. // Get the new insert position for the node we care about.
  3080. MemberPointerType *NewIP =
  3081. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  3082. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3083. }
  3084. auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  3085. Types.push_back(New);
  3086. MemberPointerTypes.InsertNode(New, InsertPos);
  3087. return QualType(New, 0);
  3088. }
  3089. /// getConstantArrayType - Return the unique reference to the type for an
  3090. /// array of the specified element type.
  3091. QualType ASTContext::getConstantArrayType(QualType EltTy,
  3092. const llvm::APInt &ArySizeIn,
  3093. const Expr *SizeExpr,
  3094. ArrayType::ArraySizeModifier ASM,
  3095. unsigned IndexTypeQuals) const {
  3096. assert((EltTy->isDependentType() ||
  3097. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  3098. "Constant array of VLAs is illegal!");
  3099. // We only need the size as part of the type if it's instantiation-dependent.
  3100. if (SizeExpr && !SizeExpr->isInstantiationDependent())
  3101. SizeExpr = nullptr;
  3102. // Convert the array size into a canonical width matching the pointer size for
  3103. // the target.
  3104. llvm::APInt ArySize(ArySizeIn);
  3105. ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
  3106. llvm::FoldingSetNodeID ID;
  3107. ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
  3108. IndexTypeQuals);
  3109. void *InsertPos = nullptr;
  3110. if (ConstantArrayType *ATP =
  3111. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  3112. return QualType(ATP, 0);
  3113. // If the element type isn't canonical or has qualifiers, or the array bound
  3114. // is instantiation-dependent, this won't be a canonical type either, so fill
  3115. // in the canonical type field.
  3116. QualType Canon;
  3117. // FIXME: Check below should look for qualifiers behind sugar.
  3118. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
  3119. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  3120. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
  3121. ASM, IndexTypeQuals);
  3122. Canon = getQualifiedType(Canon, canonSplit.Quals);
  3123. // Get the new insert position for the node we care about.
  3124. ConstantArrayType *NewIP =
  3125. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  3126. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3127. }
  3128. void *Mem = Allocate(
  3129. ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
  3130. TypeAlignment);
  3131. auto *New = new (Mem)
  3132. ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
  3133. ConstantArrayTypes.InsertNode(New, InsertPos);
  3134. Types.push_back(New);
  3135. return QualType(New, 0);
  3136. }
  3137. /// getVariableArrayDecayedType - Turns the given type, which may be
  3138. /// variably-modified, into the corresponding type with all the known
  3139. /// sizes replaced with [*].
  3140. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  3141. // Vastly most common case.
  3142. if (!type->isVariablyModifiedType()) return type;
  3143. QualType result;
  3144. SplitQualType split = type.getSplitDesugaredType();
  3145. const Type *ty = split.Ty;
  3146. switch (ty->getTypeClass()) {
  3147. #define TYPE(Class, Base)
  3148. #define ABSTRACT_TYPE(Class, Base)
  3149. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  3150. #include "clang/AST/TypeNodes.inc"
  3151. llvm_unreachable("didn't desugar past all non-canonical types?");
  3152. // These types should never be variably-modified.
  3153. case Type::Builtin:
  3154. case Type::Complex:
  3155. case Type::Vector:
  3156. case Type::DependentVector:
  3157. case Type::ExtVector:
  3158. case Type::DependentSizedExtVector:
  3159. case Type::ConstantMatrix:
  3160. case Type::DependentSizedMatrix:
  3161. case Type::DependentAddressSpace:
  3162. case Type::ObjCObject:
  3163. case Type::ObjCInterface:
  3164. case Type::ObjCObjectPointer:
  3165. case Type::Record:
  3166. case Type::Enum:
  3167. case Type::UnresolvedUsing:
  3168. case Type::TypeOfExpr:
  3169. case Type::TypeOf:
  3170. case Type::Decltype:
  3171. case Type::UnaryTransform:
  3172. case Type::DependentName:
  3173. case Type::InjectedClassName:
  3174. case Type::TemplateSpecialization:
  3175. case Type::DependentTemplateSpecialization:
  3176. case Type::TemplateTypeParm:
  3177. case Type::SubstTemplateTypeParmPack:
  3178. case Type::Auto:
  3179. case Type::DeducedTemplateSpecialization:
  3180. case Type::PackExpansion:
  3181. case Type::BitInt:
  3182. case Type::DependentBitInt:
  3183. llvm_unreachable("type should never be variably-modified");
  3184. // These types can be variably-modified but should never need to
  3185. // further decay.
  3186. case Type::FunctionNoProto:
  3187. case Type::FunctionProto:
  3188. case Type::BlockPointer:
  3189. case Type::MemberPointer:
  3190. case Type::Pipe:
  3191. return type;
  3192. // These types can be variably-modified. All these modifications
  3193. // preserve structure except as noted by comments.
  3194. // TODO: if we ever care about optimizing VLAs, there are no-op
  3195. // optimizations available here.
  3196. case Type::Pointer:
  3197. result = getPointerType(getVariableArrayDecayedType(
  3198. cast<PointerType>(ty)->getPointeeType()));
  3199. break;
  3200. case Type::LValueReference: {
  3201. const auto *lv = cast<LValueReferenceType>(ty);
  3202. result = getLValueReferenceType(
  3203. getVariableArrayDecayedType(lv->getPointeeType()),
  3204. lv->isSpelledAsLValue());
  3205. break;
  3206. }
  3207. case Type::RValueReference: {
  3208. const auto *lv = cast<RValueReferenceType>(ty);
  3209. result = getRValueReferenceType(
  3210. getVariableArrayDecayedType(lv->getPointeeType()));
  3211. break;
  3212. }
  3213. case Type::Atomic: {
  3214. const auto *at = cast<AtomicType>(ty);
  3215. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  3216. break;
  3217. }
  3218. case Type::ConstantArray: {
  3219. const auto *cat = cast<ConstantArrayType>(ty);
  3220. result = getConstantArrayType(
  3221. getVariableArrayDecayedType(cat->getElementType()),
  3222. cat->getSize(),
  3223. cat->getSizeExpr(),
  3224. cat->getSizeModifier(),
  3225. cat->getIndexTypeCVRQualifiers());
  3226. break;
  3227. }
  3228. case Type::DependentSizedArray: {
  3229. const auto *dat = cast<DependentSizedArrayType>(ty);
  3230. result = getDependentSizedArrayType(
  3231. getVariableArrayDecayedType(dat->getElementType()),
  3232. dat->getSizeExpr(),
  3233. dat->getSizeModifier(),
  3234. dat->getIndexTypeCVRQualifiers(),
  3235. dat->getBracketsRange());
  3236. break;
  3237. }
  3238. // Turn incomplete types into [*] types.
  3239. case Type::IncompleteArray: {
  3240. const auto *iat = cast<IncompleteArrayType>(ty);
  3241. result = getVariableArrayType(
  3242. getVariableArrayDecayedType(iat->getElementType()),
  3243. /*size*/ nullptr,
  3244. ArrayType::Normal,
  3245. iat->getIndexTypeCVRQualifiers(),
  3246. SourceRange());
  3247. break;
  3248. }
  3249. // Turn VLA types into [*] types.
  3250. case Type::VariableArray: {
  3251. const auto *vat = cast<VariableArrayType>(ty);
  3252. result = getVariableArrayType(
  3253. getVariableArrayDecayedType(vat->getElementType()),
  3254. /*size*/ nullptr,
  3255. ArrayType::Star,
  3256. vat->getIndexTypeCVRQualifiers(),
  3257. vat->getBracketsRange());
  3258. break;
  3259. }
  3260. }
  3261. // Apply the top-level qualifiers from the original.
  3262. return getQualifiedType(result, split.Quals);
  3263. }
  3264. /// getVariableArrayType - Returns a non-unique reference to the type for a
  3265. /// variable array of the specified element type.
  3266. QualType ASTContext::getVariableArrayType(QualType EltTy,
  3267. Expr *NumElts,
  3268. ArrayType::ArraySizeModifier ASM,
  3269. unsigned IndexTypeQuals,
  3270. SourceRange Brackets) const {
  3271. // Since we don't unique expressions, it isn't possible to unique VLA's
  3272. // that have an expression provided for their size.
  3273. QualType Canon;
  3274. // Be sure to pull qualifiers off the element type.
  3275. // FIXME: Check below should look for qualifiers behind sugar.
  3276. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  3277. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  3278. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  3279. IndexTypeQuals, Brackets);
  3280. Canon = getQualifiedType(Canon, canonSplit.Quals);
  3281. }
  3282. auto *New = new (*this, TypeAlignment)
  3283. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  3284. VariableArrayTypes.push_back(New);
  3285. Types.push_back(New);
  3286. return QualType(New, 0);
  3287. }
  3288. /// getDependentSizedArrayType - Returns a non-unique reference to
  3289. /// the type for a dependently-sized array of the specified element
  3290. /// type.
  3291. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  3292. Expr *numElements,
  3293. ArrayType::ArraySizeModifier ASM,
  3294. unsigned elementTypeQuals,
  3295. SourceRange brackets) const {
  3296. assert((!numElements || numElements->isTypeDependent() ||
  3297. numElements->isValueDependent()) &&
  3298. "Size must be type- or value-dependent!");
  3299. // Dependently-sized array types that do not have a specified number
  3300. // of elements will have their sizes deduced from a dependent
  3301. // initializer. We do no canonicalization here at all, which is okay
  3302. // because they can't be used in most locations.
  3303. if (!numElements) {
  3304. auto *newType
  3305. = new (*this, TypeAlignment)
  3306. DependentSizedArrayType(*this, elementType, QualType(),
  3307. numElements, ASM, elementTypeQuals,
  3308. brackets);
  3309. Types.push_back(newType);
  3310. return QualType(newType, 0);
  3311. }
  3312. // Otherwise, we actually build a new type every time, but we
  3313. // also build a canonical type.
  3314. SplitQualType canonElementType = getCanonicalType(elementType).split();
  3315. void *insertPos = nullptr;
  3316. llvm::FoldingSetNodeID ID;
  3317. DependentSizedArrayType::Profile(ID, *this,
  3318. QualType(canonElementType.Ty, 0),
  3319. ASM, elementTypeQuals, numElements);
  3320. // Look for an existing type with these properties.
  3321. DependentSizedArrayType *canonTy =
  3322. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  3323. // If we don't have one, build one.
  3324. if (!canonTy) {
  3325. canonTy = new (*this, TypeAlignment)
  3326. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  3327. QualType(), numElements, ASM, elementTypeQuals,
  3328. brackets);
  3329. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  3330. Types.push_back(canonTy);
  3331. }
  3332. // Apply qualifiers from the element type to the array.
  3333. QualType canon = getQualifiedType(QualType(canonTy,0),
  3334. canonElementType.Quals);
  3335. // If we didn't need extra canonicalization for the element type or the size
  3336. // expression, then just use that as our result.
  3337. if (QualType(canonElementType.Ty, 0) == elementType &&
  3338. canonTy->getSizeExpr() == numElements)
  3339. return canon;
  3340. // Otherwise, we need to build a type which follows the spelling
  3341. // of the element type.
  3342. auto *sugaredType
  3343. = new (*this, TypeAlignment)
  3344. DependentSizedArrayType(*this, elementType, canon, numElements,
  3345. ASM, elementTypeQuals, brackets);
  3346. Types.push_back(sugaredType);
  3347. return QualType(sugaredType, 0);
  3348. }
  3349. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  3350. ArrayType::ArraySizeModifier ASM,
  3351. unsigned elementTypeQuals) const {
  3352. llvm::FoldingSetNodeID ID;
  3353. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  3354. void *insertPos = nullptr;
  3355. if (IncompleteArrayType *iat =
  3356. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  3357. return QualType(iat, 0);
  3358. // If the element type isn't canonical, this won't be a canonical type
  3359. // either, so fill in the canonical type field. We also have to pull
  3360. // qualifiers off the element type.
  3361. QualType canon;
  3362. // FIXME: Check below should look for qualifiers behind sugar.
  3363. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  3364. SplitQualType canonSplit = getCanonicalType(elementType).split();
  3365. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  3366. ASM, elementTypeQuals);
  3367. canon = getQualifiedType(canon, canonSplit.Quals);
  3368. // Get the new insert position for the node we care about.
  3369. IncompleteArrayType *existing =
  3370. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  3371. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  3372. }
  3373. auto *newType = new (*this, TypeAlignment)
  3374. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  3375. IncompleteArrayTypes.InsertNode(newType, insertPos);
  3376. Types.push_back(newType);
  3377. return QualType(newType, 0);
  3378. }
  3379. ASTContext::BuiltinVectorTypeInfo
  3380. ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
  3381. #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
  3382. {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
  3383. NUMVECTORS};
  3384. #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
  3385. {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
  3386. switch (Ty->getKind()) {
  3387. default:
  3388. llvm_unreachable("Unsupported builtin vector type");
  3389. case BuiltinType::SveInt8:
  3390. return SVE_INT_ELTTY(8, 16, true, 1);
  3391. case BuiltinType::SveUint8:
  3392. return SVE_INT_ELTTY(8, 16, false, 1);
  3393. case BuiltinType::SveInt8x2:
  3394. return SVE_INT_ELTTY(8, 16, true, 2);
  3395. case BuiltinType::SveUint8x2:
  3396. return SVE_INT_ELTTY(8, 16, false, 2);
  3397. case BuiltinType::SveInt8x3:
  3398. return SVE_INT_ELTTY(8, 16, true, 3);
  3399. case BuiltinType::SveUint8x3:
  3400. return SVE_INT_ELTTY(8, 16, false, 3);
  3401. case BuiltinType::SveInt8x4:
  3402. return SVE_INT_ELTTY(8, 16, true, 4);
  3403. case BuiltinType::SveUint8x4:
  3404. return SVE_INT_ELTTY(8, 16, false, 4);
  3405. case BuiltinType::SveInt16:
  3406. return SVE_INT_ELTTY(16, 8, true, 1);
  3407. case BuiltinType::SveUint16:
  3408. return SVE_INT_ELTTY(16, 8, false, 1);
  3409. case BuiltinType::SveInt16x2:
  3410. return SVE_INT_ELTTY(16, 8, true, 2);
  3411. case BuiltinType::SveUint16x2:
  3412. return SVE_INT_ELTTY(16, 8, false, 2);
  3413. case BuiltinType::SveInt16x3:
  3414. return SVE_INT_ELTTY(16, 8, true, 3);
  3415. case BuiltinType::SveUint16x3:
  3416. return SVE_INT_ELTTY(16, 8, false, 3);
  3417. case BuiltinType::SveInt16x4:
  3418. return SVE_INT_ELTTY(16, 8, true, 4);
  3419. case BuiltinType::SveUint16x4:
  3420. return SVE_INT_ELTTY(16, 8, false, 4);
  3421. case BuiltinType::SveInt32:
  3422. return SVE_INT_ELTTY(32, 4, true, 1);
  3423. case BuiltinType::SveUint32:
  3424. return SVE_INT_ELTTY(32, 4, false, 1);
  3425. case BuiltinType::SveInt32x2:
  3426. return SVE_INT_ELTTY(32, 4, true, 2);
  3427. case BuiltinType::SveUint32x2:
  3428. return SVE_INT_ELTTY(32, 4, false, 2);
  3429. case BuiltinType::SveInt32x3:
  3430. return SVE_INT_ELTTY(32, 4, true, 3);
  3431. case BuiltinType::SveUint32x3:
  3432. return SVE_INT_ELTTY(32, 4, false, 3);
  3433. case BuiltinType::SveInt32x4:
  3434. return SVE_INT_ELTTY(32, 4, true, 4);
  3435. case BuiltinType::SveUint32x4:
  3436. return SVE_INT_ELTTY(32, 4, false, 4);
  3437. case BuiltinType::SveInt64:
  3438. return SVE_INT_ELTTY(64, 2, true, 1);
  3439. case BuiltinType::SveUint64:
  3440. return SVE_INT_ELTTY(64, 2, false, 1);
  3441. case BuiltinType::SveInt64x2:
  3442. return SVE_INT_ELTTY(64, 2, true, 2);
  3443. case BuiltinType::SveUint64x2:
  3444. return SVE_INT_ELTTY(64, 2, false, 2);
  3445. case BuiltinType::SveInt64x3:
  3446. return SVE_INT_ELTTY(64, 2, true, 3);
  3447. case BuiltinType::SveUint64x3:
  3448. return SVE_INT_ELTTY(64, 2, false, 3);
  3449. case BuiltinType::SveInt64x4:
  3450. return SVE_INT_ELTTY(64, 2, true, 4);
  3451. case BuiltinType::SveUint64x4:
  3452. return SVE_INT_ELTTY(64, 2, false, 4);
  3453. case BuiltinType::SveBool:
  3454. return SVE_ELTTY(BoolTy, 16, 1);
  3455. case BuiltinType::SveFloat16:
  3456. return SVE_ELTTY(HalfTy, 8, 1);
  3457. case BuiltinType::SveFloat16x2:
  3458. return SVE_ELTTY(HalfTy, 8, 2);
  3459. case BuiltinType::SveFloat16x3:
  3460. return SVE_ELTTY(HalfTy, 8, 3);
  3461. case BuiltinType::SveFloat16x4:
  3462. return SVE_ELTTY(HalfTy, 8, 4);
  3463. case BuiltinType::SveFloat32:
  3464. return SVE_ELTTY(FloatTy, 4, 1);
  3465. case BuiltinType::SveFloat32x2:
  3466. return SVE_ELTTY(FloatTy, 4, 2);
  3467. case BuiltinType::SveFloat32x3:
  3468. return SVE_ELTTY(FloatTy, 4, 3);
  3469. case BuiltinType::SveFloat32x4:
  3470. return SVE_ELTTY(FloatTy, 4, 4);
  3471. case BuiltinType::SveFloat64:
  3472. return SVE_ELTTY(DoubleTy, 2, 1);
  3473. case BuiltinType::SveFloat64x2:
  3474. return SVE_ELTTY(DoubleTy, 2, 2);
  3475. case BuiltinType::SveFloat64x3:
  3476. return SVE_ELTTY(DoubleTy, 2, 3);
  3477. case BuiltinType::SveFloat64x4:
  3478. return SVE_ELTTY(DoubleTy, 2, 4);
  3479. case BuiltinType::SveBFloat16:
  3480. return SVE_ELTTY(BFloat16Ty, 8, 1);
  3481. case BuiltinType::SveBFloat16x2:
  3482. return SVE_ELTTY(BFloat16Ty, 8, 2);
  3483. case BuiltinType::SveBFloat16x3:
  3484. return SVE_ELTTY(BFloat16Ty, 8, 3);
  3485. case BuiltinType::SveBFloat16x4:
  3486. return SVE_ELTTY(BFloat16Ty, 8, 4);
  3487. #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
  3488. IsSigned) \
  3489. case BuiltinType::Id: \
  3490. return {getIntTypeForBitwidth(ElBits, IsSigned), \
  3491. llvm::ElementCount::getScalable(NumEls), NF};
  3492. #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
  3493. case BuiltinType::Id: \
  3494. return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
  3495. llvm::ElementCount::getScalable(NumEls), NF};
  3496. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
  3497. case BuiltinType::Id: \
  3498. return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
  3499. #include "clang/Basic/RISCVVTypes.def"
  3500. }
  3501. }
  3502. /// getScalableVectorType - Return the unique reference to a scalable vector
  3503. /// type of the specified element type and size. VectorType must be a built-in
  3504. /// type.
  3505. QualType ASTContext::getScalableVectorType(QualType EltTy,
  3506. unsigned NumElts) const {
  3507. if (Target->hasAArch64SVETypes()) {
  3508. uint64_t EltTySize = getTypeSize(EltTy);
  3509. #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
  3510. IsSigned, IsFP, IsBF) \
  3511. if (!EltTy->isBooleanType() && \
  3512. ((EltTy->hasIntegerRepresentation() && \
  3513. EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
  3514. (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
  3515. IsFP && !IsBF) || \
  3516. (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
  3517. IsBF && !IsFP)) && \
  3518. EltTySize == ElBits && NumElts == NumEls) { \
  3519. return SingletonId; \
  3520. }
  3521. #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
  3522. if (EltTy->isBooleanType() && NumElts == NumEls) \
  3523. return SingletonId;
  3524. #include "clang/Basic/AArch64SVEACLETypes.def"
  3525. } else if (Target->hasRISCVVTypes()) {
  3526. uint64_t EltTySize = getTypeSize(EltTy);
  3527. #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
  3528. IsFP) \
  3529. if (!EltTy->isBooleanType() && \
  3530. ((EltTy->hasIntegerRepresentation() && \
  3531. EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
  3532. (EltTy->hasFloatingRepresentation() && IsFP)) && \
  3533. EltTySize == ElBits && NumElts == NumEls) \
  3534. return SingletonId;
  3535. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
  3536. if (EltTy->isBooleanType() && NumElts == NumEls) \
  3537. return SingletonId;
  3538. #include "clang/Basic/RISCVVTypes.def"
  3539. }
  3540. return QualType();
  3541. }
  3542. /// getVectorType - Return the unique reference to a vector type of
  3543. /// the specified element type and size. VectorType must be a built-in type.
  3544. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  3545. VectorType::VectorKind VecKind) const {
  3546. assert(vecType->isBuiltinType() ||
  3547. (vecType->isBitIntType() &&
  3548. // Only support _BitInt elements with byte-sized power of 2 NumBits.
  3549. llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) &&
  3550. vecType->getAs<BitIntType>()->getNumBits() >= 8));
  3551. // Check if we've already instantiated a vector of this type.
  3552. llvm::FoldingSetNodeID ID;
  3553. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  3554. void *InsertPos = nullptr;
  3555. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3556. return QualType(VTP, 0);
  3557. // If the element type isn't canonical, this won't be a canonical type either,
  3558. // so fill in the canonical type field.
  3559. QualType Canonical;
  3560. if (!vecType.isCanonical()) {
  3561. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  3562. // Get the new insert position for the node we care about.
  3563. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3564. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3565. }
  3566. auto *New = new (*this, TypeAlignment)
  3567. VectorType(vecType, NumElts, Canonical, VecKind);
  3568. VectorTypes.InsertNode(New, InsertPos);
  3569. Types.push_back(New);
  3570. return QualType(New, 0);
  3571. }
  3572. QualType
  3573. ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
  3574. SourceLocation AttrLoc,
  3575. VectorType::VectorKind VecKind) const {
  3576. llvm::FoldingSetNodeID ID;
  3577. DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
  3578. VecKind);
  3579. void *InsertPos = nullptr;
  3580. DependentVectorType *Canon =
  3581. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3582. DependentVectorType *New;
  3583. if (Canon) {
  3584. New = new (*this, TypeAlignment) DependentVectorType(
  3585. *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
  3586. } else {
  3587. QualType CanonVecTy = getCanonicalType(VecType);
  3588. if (CanonVecTy == VecType) {
  3589. New = new (*this, TypeAlignment) DependentVectorType(
  3590. *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
  3591. DependentVectorType *CanonCheck =
  3592. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3593. assert(!CanonCheck &&
  3594. "Dependent-sized vector_size canonical type broken");
  3595. (void)CanonCheck;
  3596. DependentVectorTypes.InsertNode(New, InsertPos);
  3597. } else {
  3598. QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
  3599. SourceLocation(), VecKind);
  3600. New = new (*this, TypeAlignment) DependentVectorType(
  3601. *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
  3602. }
  3603. }
  3604. Types.push_back(New);
  3605. return QualType(New, 0);
  3606. }
  3607. /// getExtVectorType - Return the unique reference to an extended vector type of
  3608. /// the specified element type and size. VectorType must be a built-in type.
  3609. QualType ASTContext::getExtVectorType(QualType vecType,
  3610. unsigned NumElts) const {
  3611. assert(vecType->isBuiltinType() || vecType->isDependentType() ||
  3612. (vecType->isBitIntType() &&
  3613. // Only support _BitInt elements with byte-sized power of 2 NumBits.
  3614. llvm::isPowerOf2_32(vecType->getAs<BitIntType>()->getNumBits()) &&
  3615. vecType->getAs<BitIntType>()->getNumBits() >= 8));
  3616. // Check if we've already instantiated a vector of this type.
  3617. llvm::FoldingSetNodeID ID;
  3618. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  3619. VectorType::GenericVector);
  3620. void *InsertPos = nullptr;
  3621. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3622. return QualType(VTP, 0);
  3623. // If the element type isn't canonical, this won't be a canonical type either,
  3624. // so fill in the canonical type field.
  3625. QualType Canonical;
  3626. if (!vecType.isCanonical()) {
  3627. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  3628. // Get the new insert position for the node we care about.
  3629. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3630. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3631. }
  3632. auto *New = new (*this, TypeAlignment)
  3633. ExtVectorType(vecType, NumElts, Canonical);
  3634. VectorTypes.InsertNode(New, InsertPos);
  3635. Types.push_back(New);
  3636. return QualType(New, 0);
  3637. }
  3638. QualType
  3639. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  3640. Expr *SizeExpr,
  3641. SourceLocation AttrLoc) const {
  3642. llvm::FoldingSetNodeID ID;
  3643. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  3644. SizeExpr);
  3645. void *InsertPos = nullptr;
  3646. DependentSizedExtVectorType *Canon
  3647. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3648. DependentSizedExtVectorType *New;
  3649. if (Canon) {
  3650. // We already have a canonical version of this array type; use it as
  3651. // the canonical type for a newly-built type.
  3652. New = new (*this, TypeAlignment)
  3653. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  3654. SizeExpr, AttrLoc);
  3655. } else {
  3656. QualType CanonVecTy = getCanonicalType(vecType);
  3657. if (CanonVecTy == vecType) {
  3658. New = new (*this, TypeAlignment)
  3659. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  3660. AttrLoc);
  3661. DependentSizedExtVectorType *CanonCheck
  3662. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3663. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  3664. (void)CanonCheck;
  3665. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  3666. } else {
  3667. QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  3668. SourceLocation());
  3669. New = new (*this, TypeAlignment) DependentSizedExtVectorType(
  3670. *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
  3671. }
  3672. }
  3673. Types.push_back(New);
  3674. return QualType(New, 0);
  3675. }
  3676. QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
  3677. unsigned NumColumns) const {
  3678. llvm::FoldingSetNodeID ID;
  3679. ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
  3680. Type::ConstantMatrix);
  3681. assert(MatrixType::isValidElementType(ElementTy) &&
  3682. "need a valid element type");
  3683. assert(ConstantMatrixType::isDimensionValid(NumRows) &&
  3684. ConstantMatrixType::isDimensionValid(NumColumns) &&
  3685. "need valid matrix dimensions");
  3686. void *InsertPos = nullptr;
  3687. if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
  3688. return QualType(MTP, 0);
  3689. QualType Canonical;
  3690. if (!ElementTy.isCanonical()) {
  3691. Canonical =
  3692. getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
  3693. ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3694. assert(!NewIP && "Matrix type shouldn't already exist in the map");
  3695. (void)NewIP;
  3696. }
  3697. auto *New = new (*this, TypeAlignment)
  3698. ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
  3699. MatrixTypes.InsertNode(New, InsertPos);
  3700. Types.push_back(New);
  3701. return QualType(New, 0);
  3702. }
  3703. QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
  3704. Expr *RowExpr,
  3705. Expr *ColumnExpr,
  3706. SourceLocation AttrLoc) const {
  3707. QualType CanonElementTy = getCanonicalType(ElementTy);
  3708. llvm::FoldingSetNodeID ID;
  3709. DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
  3710. ColumnExpr);
  3711. void *InsertPos = nullptr;
  3712. DependentSizedMatrixType *Canon =
  3713. DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3714. if (!Canon) {
  3715. Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
  3716. *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
  3717. #ifndef NDEBUG
  3718. DependentSizedMatrixType *CanonCheck =
  3719. DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3720. assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
  3721. #endif
  3722. DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
  3723. Types.push_back(Canon);
  3724. }
  3725. // Already have a canonical version of the matrix type
  3726. //
  3727. // If it exactly matches the requested type, use it directly.
  3728. if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
  3729. Canon->getRowExpr() == ColumnExpr)
  3730. return QualType(Canon, 0);
  3731. // Use Canon as the canonical type for newly-built type.
  3732. DependentSizedMatrixType *New = new (*this, TypeAlignment)
  3733. DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
  3734. ColumnExpr, AttrLoc);
  3735. Types.push_back(New);
  3736. return QualType(New, 0);
  3737. }
  3738. QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
  3739. Expr *AddrSpaceExpr,
  3740. SourceLocation AttrLoc) const {
  3741. assert(AddrSpaceExpr->isInstantiationDependent());
  3742. QualType canonPointeeType = getCanonicalType(PointeeType);
  3743. void *insertPos = nullptr;
  3744. llvm::FoldingSetNodeID ID;
  3745. DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
  3746. AddrSpaceExpr);
  3747. DependentAddressSpaceType *canonTy =
  3748. DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
  3749. if (!canonTy) {
  3750. canonTy = new (*this, TypeAlignment)
  3751. DependentAddressSpaceType(*this, canonPointeeType,
  3752. QualType(), AddrSpaceExpr, AttrLoc);
  3753. DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
  3754. Types.push_back(canonTy);
  3755. }
  3756. if (canonPointeeType == PointeeType &&
  3757. canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
  3758. return QualType(canonTy, 0);
  3759. auto *sugaredType
  3760. = new (*this, TypeAlignment)
  3761. DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
  3762. AddrSpaceExpr, AttrLoc);
  3763. Types.push_back(sugaredType);
  3764. return QualType(sugaredType, 0);
  3765. }
  3766. /// Determine whether \p T is canonical as the result type of a function.
  3767. static bool isCanonicalResultType(QualType T) {
  3768. return T.isCanonical() &&
  3769. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  3770. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  3771. }
  3772. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  3773. QualType
  3774. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  3775. const FunctionType::ExtInfo &Info) const {
  3776. // FIXME: This assertion cannot be enabled (yet) because the ObjC rewriter
  3777. // functionality creates a function without a prototype regardless of
  3778. // language mode (so it makes them even in C++). Once the rewriter has been
  3779. // fixed, this assertion can be enabled again.
  3780. //assert(!LangOpts.requiresStrictPrototypes() &&
  3781. // "strict prototypes are disabled");
  3782. // Unique functions, to guarantee there is only one function of a particular
  3783. // structure.
  3784. llvm::FoldingSetNodeID ID;
  3785. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  3786. void *InsertPos = nullptr;
  3787. if (FunctionNoProtoType *FT =
  3788. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3789. return QualType(FT, 0);
  3790. QualType Canonical;
  3791. if (!isCanonicalResultType(ResultTy)) {
  3792. Canonical =
  3793. getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
  3794. // Get the new insert position for the node we care about.
  3795. FunctionNoProtoType *NewIP =
  3796. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3797. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3798. }
  3799. auto *New = new (*this, TypeAlignment)
  3800. FunctionNoProtoType(ResultTy, Canonical, Info);
  3801. Types.push_back(New);
  3802. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  3803. return QualType(New, 0);
  3804. }
  3805. CanQualType
  3806. ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
  3807. CanQualType CanResultType = getCanonicalType(ResultType);
  3808. // Canonical result types do not have ARC lifetime qualifiers.
  3809. if (CanResultType.getQualifiers().hasObjCLifetime()) {
  3810. Qualifiers Qs = CanResultType.getQualifiers();
  3811. Qs.removeObjCLifetime();
  3812. return CanQualType::CreateUnsafe(
  3813. getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
  3814. }
  3815. return CanResultType;
  3816. }
  3817. static bool isCanonicalExceptionSpecification(
  3818. const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
  3819. if (ESI.Type == EST_None)
  3820. return true;
  3821. if (!NoexceptInType)
  3822. return false;
  3823. // C++17 onwards: exception specification is part of the type, as a simple
  3824. // boolean "can this function type throw".
  3825. if (ESI.Type == EST_BasicNoexcept)
  3826. return true;
  3827. // A noexcept(expr) specification is (possibly) canonical if expr is
  3828. // value-dependent.
  3829. if (ESI.Type == EST_DependentNoexcept)
  3830. return true;
  3831. // A dynamic exception specification is canonical if it only contains pack
  3832. // expansions (so we can't tell whether it's non-throwing) and all its
  3833. // contained types are canonical.
  3834. if (ESI.Type == EST_Dynamic) {
  3835. bool AnyPackExpansions = false;
  3836. for (QualType ET : ESI.Exceptions) {
  3837. if (!ET.isCanonical())
  3838. return false;
  3839. if (ET->getAs<PackExpansionType>())
  3840. AnyPackExpansions = true;
  3841. }
  3842. return AnyPackExpansions;
  3843. }
  3844. return false;
  3845. }
  3846. QualType ASTContext::getFunctionTypeInternal(
  3847. QualType ResultTy, ArrayRef<QualType> ArgArray,
  3848. const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
  3849. size_t NumArgs = ArgArray.size();
  3850. // Unique functions, to guarantee there is only one function of a particular
  3851. // structure.
  3852. llvm::FoldingSetNodeID ID;
  3853. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
  3854. *this, true);
  3855. QualType Canonical;
  3856. bool Unique = false;
  3857. void *InsertPos = nullptr;
  3858. if (FunctionProtoType *FPT =
  3859. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
  3860. QualType Existing = QualType(FPT, 0);
  3861. // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
  3862. // it so long as our exception specification doesn't contain a dependent
  3863. // noexcept expression, or we're just looking for a canonical type.
  3864. // Otherwise, we're going to need to create a type
  3865. // sugar node to hold the concrete expression.
  3866. if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
  3867. EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
  3868. return Existing;
  3869. // We need a new type sugar node for this one, to hold the new noexcept
  3870. // expression. We do no canonicalization here, but that's OK since we don't
  3871. // expect to see the same noexcept expression much more than once.
  3872. Canonical = getCanonicalType(Existing);
  3873. Unique = true;
  3874. }
  3875. bool NoexceptInType = getLangOpts().CPlusPlus17;
  3876. bool IsCanonicalExceptionSpec =
  3877. isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
  3878. // Determine whether the type being created is already canonical or not.
  3879. bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
  3880. isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
  3881. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  3882. if (!ArgArray[i].isCanonicalAsParam())
  3883. isCanonical = false;
  3884. if (OnlyWantCanonical)
  3885. assert(isCanonical &&
  3886. "given non-canonical parameters constructing canonical type");
  3887. // If this type isn't canonical, get the canonical version of it if we don't
  3888. // already have it. The exception spec is only partially part of the
  3889. // canonical type, and only in C++17 onwards.
  3890. if (!isCanonical && Canonical.isNull()) {
  3891. SmallVector<QualType, 16> CanonicalArgs;
  3892. CanonicalArgs.reserve(NumArgs);
  3893. for (unsigned i = 0; i != NumArgs; ++i)
  3894. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  3895. llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
  3896. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  3897. CanonicalEPI.HasTrailingReturn = false;
  3898. if (IsCanonicalExceptionSpec) {
  3899. // Exception spec is already OK.
  3900. } else if (NoexceptInType) {
  3901. switch (EPI.ExceptionSpec.Type) {
  3902. case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
  3903. // We don't know yet. It shouldn't matter what we pick here; no-one
  3904. // should ever look at this.
  3905. [[fallthrough]];
  3906. case EST_None: case EST_MSAny: case EST_NoexceptFalse:
  3907. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3908. break;
  3909. // A dynamic exception specification is almost always "not noexcept",
  3910. // with the exception that a pack expansion might expand to no types.
  3911. case EST_Dynamic: {
  3912. bool AnyPacks = false;
  3913. for (QualType ET : EPI.ExceptionSpec.Exceptions) {
  3914. if (ET->getAs<PackExpansionType>())
  3915. AnyPacks = true;
  3916. ExceptionTypeStorage.push_back(getCanonicalType(ET));
  3917. }
  3918. if (!AnyPacks)
  3919. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3920. else {
  3921. CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
  3922. CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
  3923. }
  3924. break;
  3925. }
  3926. case EST_DynamicNone:
  3927. case EST_BasicNoexcept:
  3928. case EST_NoexceptTrue:
  3929. case EST_NoThrow:
  3930. CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
  3931. break;
  3932. case EST_DependentNoexcept:
  3933. llvm_unreachable("dependent noexcept is already canonical");
  3934. }
  3935. } else {
  3936. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  3937. }
  3938. // Adjust the canonical function result type.
  3939. CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
  3940. Canonical =
  3941. getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
  3942. // Get the new insert position for the node we care about.
  3943. FunctionProtoType *NewIP =
  3944. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3945. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3946. }
  3947. // Compute the needed size to hold this FunctionProtoType and the
  3948. // various trailing objects.
  3949. auto ESH = FunctionProtoType::getExceptionSpecSize(
  3950. EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
  3951. size_t Size = FunctionProtoType::totalSizeToAlloc<
  3952. QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
  3953. FunctionType::ExceptionType, Expr *, FunctionDecl *,
  3954. FunctionProtoType::ExtParameterInfo, Qualifiers>(
  3955. NumArgs, EPI.Variadic, EPI.requiresFunctionProtoTypeExtraBitfields(),
  3956. ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
  3957. EPI.ExtParameterInfos ? NumArgs : 0,
  3958. EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
  3959. auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
  3960. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  3961. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
  3962. Types.push_back(FTP);
  3963. if (!Unique)
  3964. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  3965. return QualType(FTP, 0);
  3966. }
  3967. QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
  3968. llvm::FoldingSetNodeID ID;
  3969. PipeType::Profile(ID, T, ReadOnly);
  3970. void *InsertPos = nullptr;
  3971. if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
  3972. return QualType(PT, 0);
  3973. // If the pipe element type isn't canonical, this won't be a canonical type
  3974. // either, so fill in the canonical type field.
  3975. QualType Canonical;
  3976. if (!T.isCanonical()) {
  3977. Canonical = getPipeType(getCanonicalType(T), ReadOnly);
  3978. // Get the new insert position for the node we care about.
  3979. PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3980. assert(!NewIP && "Shouldn't be in the map!");
  3981. (void)NewIP;
  3982. }
  3983. auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
  3984. Types.push_back(New);
  3985. PipeTypes.InsertNode(New, InsertPos);
  3986. return QualType(New, 0);
  3987. }
  3988. QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
  3989. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  3990. return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
  3991. : Ty;
  3992. }
  3993. QualType ASTContext::getReadPipeType(QualType T) const {
  3994. return getPipeType(T, true);
  3995. }
  3996. QualType ASTContext::getWritePipeType(QualType T) const {
  3997. return getPipeType(T, false);
  3998. }
  3999. QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
  4000. llvm::FoldingSetNodeID ID;
  4001. BitIntType::Profile(ID, IsUnsigned, NumBits);
  4002. void *InsertPos = nullptr;
  4003. if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
  4004. return QualType(EIT, 0);
  4005. auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
  4006. BitIntTypes.InsertNode(New, InsertPos);
  4007. Types.push_back(New);
  4008. return QualType(New, 0);
  4009. }
  4010. QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
  4011. Expr *NumBitsExpr) const {
  4012. assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
  4013. llvm::FoldingSetNodeID ID;
  4014. DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
  4015. void *InsertPos = nullptr;
  4016. if (DependentBitIntType *Existing =
  4017. DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
  4018. return QualType(Existing, 0);
  4019. auto *New = new (*this, TypeAlignment)
  4020. DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
  4021. DependentBitIntTypes.InsertNode(New, InsertPos);
  4022. Types.push_back(New);
  4023. return QualType(New, 0);
  4024. }
  4025. #ifndef NDEBUG
  4026. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  4027. if (!isa<CXXRecordDecl>(D)) return false;
  4028. const auto *RD = cast<CXXRecordDecl>(D);
  4029. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  4030. return true;
  4031. if (RD->getDescribedClassTemplate() &&
  4032. !isa<ClassTemplateSpecializationDecl>(RD))
  4033. return true;
  4034. return false;
  4035. }
  4036. #endif
  4037. /// getInjectedClassNameType - Return the unique reference to the
  4038. /// injected class name type for the specified templated declaration.
  4039. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  4040. QualType TST) const {
  4041. assert(NeedsInjectedClassNameType(Decl));
  4042. if (Decl->TypeForDecl) {
  4043. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  4044. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  4045. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  4046. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  4047. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  4048. } else {
  4049. Type *newType =
  4050. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  4051. Decl->TypeForDecl = newType;
  4052. Types.push_back(newType);
  4053. }
  4054. return QualType(Decl->TypeForDecl, 0);
  4055. }
  4056. /// getTypeDeclType - Return the unique reference to the type for the
  4057. /// specified type declaration.
  4058. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  4059. assert(Decl && "Passed null for Decl param");
  4060. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  4061. if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  4062. return getTypedefType(Typedef);
  4063. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  4064. "Template type parameter types are always available.");
  4065. if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
  4066. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  4067. assert(!NeedsInjectedClassNameType(Record));
  4068. return getRecordType(Record);
  4069. } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
  4070. assert(Enum->isFirstDecl() && "enum has previous declaration");
  4071. return getEnumType(Enum);
  4072. } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  4073. return getUnresolvedUsingType(Using);
  4074. } else
  4075. llvm_unreachable("TypeDecl without a type?");
  4076. return QualType(Decl->TypeForDecl, 0);
  4077. }
  4078. /// getTypedefType - Return the unique reference to the type for the
  4079. /// specified typedef name decl.
  4080. QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  4081. QualType Underlying) const {
  4082. if (!Decl->TypeForDecl) {
  4083. if (Underlying.isNull())
  4084. Underlying = Decl->getUnderlyingType();
  4085. auto *NewType = new (*this, TypeAlignment) TypedefType(
  4086. Type::Typedef, Decl, QualType(), getCanonicalType(Underlying));
  4087. Decl->TypeForDecl = NewType;
  4088. Types.push_back(NewType);
  4089. return QualType(NewType, 0);
  4090. }
  4091. if (Underlying.isNull() || Decl->getUnderlyingType() == Underlying)
  4092. return QualType(Decl->TypeForDecl, 0);
  4093. assert(hasSameType(Decl->getUnderlyingType(), Underlying));
  4094. llvm::FoldingSetNodeID ID;
  4095. TypedefType::Profile(ID, Decl, Underlying);
  4096. void *InsertPos = nullptr;
  4097. if (TypedefType *T = TypedefTypes.FindNodeOrInsertPos(ID, InsertPos)) {
  4098. assert(!T->typeMatchesDecl() &&
  4099. "non-divergent case should be handled with TypeDecl");
  4100. return QualType(T, 0);
  4101. }
  4102. void *Mem =
  4103. Allocate(TypedefType::totalSizeToAlloc<QualType>(true), TypeAlignment);
  4104. auto *NewType = new (Mem) TypedefType(Type::Typedef, Decl, Underlying,
  4105. getCanonicalType(Underlying));
  4106. TypedefTypes.InsertNode(NewType, InsertPos);
  4107. Types.push_back(NewType);
  4108. return QualType(NewType, 0);
  4109. }
  4110. QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
  4111. QualType Underlying) const {
  4112. llvm::FoldingSetNodeID ID;
  4113. UsingType::Profile(ID, Found, Underlying);
  4114. void *InsertPos = nullptr;
  4115. if (UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos))
  4116. return QualType(T, 0);
  4117. const Type *TypeForDecl =
  4118. cast<TypeDecl>(Found->getTargetDecl())->getTypeForDecl();
  4119. assert(!Underlying.hasLocalQualifiers());
  4120. QualType Canon = Underlying->getCanonicalTypeInternal();
  4121. assert(TypeForDecl->getCanonicalTypeInternal() == Canon);
  4122. if (Underlying.getTypePtr() == TypeForDecl)
  4123. Underlying = QualType();
  4124. void *Mem =
  4125. Allocate(UsingType::totalSizeToAlloc<QualType>(!Underlying.isNull()),
  4126. TypeAlignment);
  4127. UsingType *NewType = new (Mem) UsingType(Found, Underlying, Canon);
  4128. Types.push_back(NewType);
  4129. UsingTypes.InsertNode(NewType, InsertPos);
  4130. return QualType(NewType, 0);
  4131. }
  4132. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  4133. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  4134. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  4135. if (PrevDecl->TypeForDecl)
  4136. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  4137. auto *newType = new (*this, TypeAlignment) RecordType(Decl);
  4138. Decl->TypeForDecl = newType;
  4139. Types.push_back(newType);
  4140. return QualType(newType, 0);
  4141. }
  4142. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  4143. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  4144. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  4145. if (PrevDecl->TypeForDecl)
  4146. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  4147. auto *newType = new (*this, TypeAlignment) EnumType(Decl);
  4148. Decl->TypeForDecl = newType;
  4149. Types.push_back(newType);
  4150. return QualType(newType, 0);
  4151. }
  4152. QualType ASTContext::getUnresolvedUsingType(
  4153. const UnresolvedUsingTypenameDecl *Decl) const {
  4154. if (Decl->TypeForDecl)
  4155. return QualType(Decl->TypeForDecl, 0);
  4156. if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
  4157. Decl->getCanonicalDecl())
  4158. if (CanonicalDecl->TypeForDecl)
  4159. return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
  4160. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
  4161. Decl->TypeForDecl = newType;
  4162. Types.push_back(newType);
  4163. return QualType(newType, 0);
  4164. }
  4165. QualType ASTContext::getAttributedType(attr::Kind attrKind,
  4166. QualType modifiedType,
  4167. QualType equivalentType) const {
  4168. llvm::FoldingSetNodeID id;
  4169. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  4170. void *insertPos = nullptr;
  4171. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  4172. if (type) return QualType(type, 0);
  4173. QualType canon = getCanonicalType(equivalentType);
  4174. type = new (*this, TypeAlignment)
  4175. AttributedType(canon, attrKind, modifiedType, equivalentType);
  4176. Types.push_back(type);
  4177. AttributedTypes.InsertNode(type, insertPos);
  4178. return QualType(type, 0);
  4179. }
  4180. QualType ASTContext::getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
  4181. QualType Wrapped) {
  4182. llvm::FoldingSetNodeID ID;
  4183. BTFTagAttributedType::Profile(ID, Wrapped, BTFAttr);
  4184. void *InsertPos = nullptr;
  4185. BTFTagAttributedType *Ty =
  4186. BTFTagAttributedTypes.FindNodeOrInsertPos(ID, InsertPos);
  4187. if (Ty)
  4188. return QualType(Ty, 0);
  4189. QualType Canon = getCanonicalType(Wrapped);
  4190. Ty = new (*this, TypeAlignment) BTFTagAttributedType(Canon, Wrapped, BTFAttr);
  4191. Types.push_back(Ty);
  4192. BTFTagAttributedTypes.InsertNode(Ty, InsertPos);
  4193. return QualType(Ty, 0);
  4194. }
  4195. /// Retrieve a substitution-result type.
  4196. QualType ASTContext::getSubstTemplateTypeParmType(
  4197. QualType Replacement, Decl *AssociatedDecl, unsigned Index,
  4198. std::optional<unsigned> PackIndex) const {
  4199. llvm::FoldingSetNodeID ID;
  4200. SubstTemplateTypeParmType::Profile(ID, Replacement, AssociatedDecl, Index,
  4201. PackIndex);
  4202. void *InsertPos = nullptr;
  4203. SubstTemplateTypeParmType *SubstParm =
  4204. SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4205. if (!SubstParm) {
  4206. void *Mem = Allocate(SubstTemplateTypeParmType::totalSizeToAlloc<QualType>(
  4207. !Replacement.isCanonical()),
  4208. TypeAlignment);
  4209. SubstParm = new (Mem) SubstTemplateTypeParmType(Replacement, AssociatedDecl,
  4210. Index, PackIndex);
  4211. Types.push_back(SubstParm);
  4212. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  4213. }
  4214. return QualType(SubstParm, 0);
  4215. }
  4216. /// Retrieve a
  4217. QualType
  4218. ASTContext::getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
  4219. unsigned Index, bool Final,
  4220. const TemplateArgument &ArgPack) {
  4221. #ifndef NDEBUG
  4222. for (const auto &P : ArgPack.pack_elements())
  4223. assert(P.getKind() == TemplateArgument::Type && "Pack contains a non-type");
  4224. #endif
  4225. llvm::FoldingSetNodeID ID;
  4226. SubstTemplateTypeParmPackType::Profile(ID, AssociatedDecl, Index, Final,
  4227. ArgPack);
  4228. void *InsertPos = nullptr;
  4229. if (SubstTemplateTypeParmPackType *SubstParm =
  4230. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  4231. return QualType(SubstParm, 0);
  4232. QualType Canon;
  4233. {
  4234. TemplateArgument CanonArgPack = getCanonicalTemplateArgument(ArgPack);
  4235. if (!AssociatedDecl->isCanonicalDecl() ||
  4236. !CanonArgPack.structurallyEquals(ArgPack)) {
  4237. Canon = getSubstTemplateTypeParmPackType(
  4238. AssociatedDecl->getCanonicalDecl(), Index, Final, CanonArgPack);
  4239. [[maybe_unused]] const auto *Nothing =
  4240. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  4241. assert(!Nothing);
  4242. }
  4243. }
  4244. auto *SubstParm = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(
  4245. Canon, AssociatedDecl, Index, Final, ArgPack);
  4246. Types.push_back(SubstParm);
  4247. SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
  4248. return QualType(SubstParm, 0);
  4249. }
  4250. /// Retrieve the template type parameter type for a template
  4251. /// parameter or parameter pack with the given depth, index, and (optionally)
  4252. /// name.
  4253. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  4254. bool ParameterPack,
  4255. TemplateTypeParmDecl *TTPDecl) const {
  4256. llvm::FoldingSetNodeID ID;
  4257. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  4258. void *InsertPos = nullptr;
  4259. TemplateTypeParmType *TypeParm
  4260. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4261. if (TypeParm)
  4262. return QualType(TypeParm, 0);
  4263. if (TTPDecl) {
  4264. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  4265. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  4266. TemplateTypeParmType *TypeCheck
  4267. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4268. assert(!TypeCheck && "Template type parameter canonical type broken");
  4269. (void)TypeCheck;
  4270. } else
  4271. TypeParm = new (*this, TypeAlignment)
  4272. TemplateTypeParmType(Depth, Index, ParameterPack);
  4273. Types.push_back(TypeParm);
  4274. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  4275. return QualType(TypeParm, 0);
  4276. }
  4277. TypeSourceInfo *
  4278. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  4279. SourceLocation NameLoc,
  4280. const TemplateArgumentListInfo &Args,
  4281. QualType Underlying) const {
  4282. assert(!Name.getAsDependentTemplateName() &&
  4283. "No dependent template names here!");
  4284. QualType TST =
  4285. getTemplateSpecializationType(Name, Args.arguments(), Underlying);
  4286. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  4287. TemplateSpecializationTypeLoc TL =
  4288. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  4289. TL.setTemplateKeywordLoc(SourceLocation());
  4290. TL.setTemplateNameLoc(NameLoc);
  4291. TL.setLAngleLoc(Args.getLAngleLoc());
  4292. TL.setRAngleLoc(Args.getRAngleLoc());
  4293. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  4294. TL.setArgLocInfo(i, Args[i].getLocInfo());
  4295. return DI;
  4296. }
  4297. QualType
  4298. ASTContext::getTemplateSpecializationType(TemplateName Template,
  4299. ArrayRef<TemplateArgumentLoc> Args,
  4300. QualType Underlying) const {
  4301. assert(!Template.getAsDependentTemplateName() &&
  4302. "No dependent template names here!");
  4303. SmallVector<TemplateArgument, 4> ArgVec;
  4304. ArgVec.reserve(Args.size());
  4305. for (const TemplateArgumentLoc &Arg : Args)
  4306. ArgVec.push_back(Arg.getArgument());
  4307. return getTemplateSpecializationType(Template, ArgVec, Underlying);
  4308. }
  4309. #ifndef NDEBUG
  4310. static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
  4311. for (const TemplateArgument &Arg : Args)
  4312. if (Arg.isPackExpansion())
  4313. return true;
  4314. return true;
  4315. }
  4316. #endif
  4317. QualType
  4318. ASTContext::getTemplateSpecializationType(TemplateName Template,
  4319. ArrayRef<TemplateArgument> Args,
  4320. QualType Underlying) const {
  4321. assert(!Template.getAsDependentTemplateName() &&
  4322. "No dependent template names here!");
  4323. // Look through qualified template names.
  4324. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  4325. Template = QTN->getUnderlyingTemplate();
  4326. const auto *TD = Template.getAsTemplateDecl();
  4327. bool IsTypeAlias = TD && TD->isTypeAlias();
  4328. QualType CanonType;
  4329. if (!Underlying.isNull())
  4330. CanonType = getCanonicalType(Underlying);
  4331. else {
  4332. // We can get here with an alias template when the specialization contains
  4333. // a pack expansion that does not match up with a parameter pack.
  4334. assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
  4335. "Caller must compute aliased type");
  4336. IsTypeAlias = false;
  4337. CanonType = getCanonicalTemplateSpecializationType(Template, Args);
  4338. }
  4339. // Allocate the (non-canonical) template specialization type, but don't
  4340. // try to unique it: these types typically have location information that
  4341. // we don't unique and don't want to lose.
  4342. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  4343. sizeof(TemplateArgument) * Args.size() +
  4344. (IsTypeAlias? sizeof(QualType) : 0),
  4345. TypeAlignment);
  4346. auto *Spec
  4347. = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
  4348. IsTypeAlias ? Underlying : QualType());
  4349. Types.push_back(Spec);
  4350. return QualType(Spec, 0);
  4351. }
  4352. QualType ASTContext::getCanonicalTemplateSpecializationType(
  4353. TemplateName Template, ArrayRef<TemplateArgument> Args) const {
  4354. assert(!Template.getAsDependentTemplateName() &&
  4355. "No dependent template names here!");
  4356. // Look through qualified template names.
  4357. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  4358. Template = TemplateName(QTN->getUnderlyingTemplate());
  4359. // Build the canonical template specialization type.
  4360. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  4361. bool AnyNonCanonArgs = false;
  4362. auto CanonArgs =
  4363. ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
  4364. // Determine whether this canonical template specialization type already
  4365. // exists.
  4366. llvm::FoldingSetNodeID ID;
  4367. TemplateSpecializationType::Profile(ID, CanonTemplate,
  4368. CanonArgs, *this);
  4369. void *InsertPos = nullptr;
  4370. TemplateSpecializationType *Spec
  4371. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4372. if (!Spec) {
  4373. // Allocate a new canonical template specialization type.
  4374. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  4375. sizeof(TemplateArgument) * CanonArgs.size()),
  4376. TypeAlignment);
  4377. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  4378. CanonArgs,
  4379. QualType(), QualType());
  4380. Types.push_back(Spec);
  4381. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  4382. }
  4383. assert(Spec->isDependentType() &&
  4384. "Non-dependent template-id type must have a canonical type");
  4385. return QualType(Spec, 0);
  4386. }
  4387. QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  4388. NestedNameSpecifier *NNS,
  4389. QualType NamedType,
  4390. TagDecl *OwnedTagDecl) const {
  4391. llvm::FoldingSetNodeID ID;
  4392. ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
  4393. void *InsertPos = nullptr;
  4394. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  4395. if (T)
  4396. return QualType(T, 0);
  4397. QualType Canon = NamedType;
  4398. if (!Canon.isCanonical()) {
  4399. Canon = getCanonicalType(NamedType);
  4400. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  4401. assert(!CheckT && "Elaborated canonical type broken");
  4402. (void)CheckT;
  4403. }
  4404. void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
  4405. TypeAlignment);
  4406. T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
  4407. Types.push_back(T);
  4408. ElaboratedTypes.InsertNode(T, InsertPos);
  4409. return QualType(T, 0);
  4410. }
  4411. QualType
  4412. ASTContext::getParenType(QualType InnerType) const {
  4413. llvm::FoldingSetNodeID ID;
  4414. ParenType::Profile(ID, InnerType);
  4415. void *InsertPos = nullptr;
  4416. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  4417. if (T)
  4418. return QualType(T, 0);
  4419. QualType Canon = InnerType;
  4420. if (!Canon.isCanonical()) {
  4421. Canon = getCanonicalType(InnerType);
  4422. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  4423. assert(!CheckT && "Paren canonical type broken");
  4424. (void)CheckT;
  4425. }
  4426. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  4427. Types.push_back(T);
  4428. ParenTypes.InsertNode(T, InsertPos);
  4429. return QualType(T, 0);
  4430. }
  4431. QualType
  4432. ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
  4433. const IdentifierInfo *MacroII) const {
  4434. QualType Canon = UnderlyingTy;
  4435. if (!Canon.isCanonical())
  4436. Canon = getCanonicalType(UnderlyingTy);
  4437. auto *newType = new (*this, TypeAlignment)
  4438. MacroQualifiedType(UnderlyingTy, Canon, MacroII);
  4439. Types.push_back(newType);
  4440. return QualType(newType, 0);
  4441. }
  4442. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  4443. NestedNameSpecifier *NNS,
  4444. const IdentifierInfo *Name,
  4445. QualType Canon) const {
  4446. if (Canon.isNull()) {
  4447. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  4448. if (CanonNNS != NNS)
  4449. Canon = getDependentNameType(Keyword, CanonNNS, Name);
  4450. }
  4451. llvm::FoldingSetNodeID ID;
  4452. DependentNameType::Profile(ID, Keyword, NNS, Name);
  4453. void *InsertPos = nullptr;
  4454. DependentNameType *T
  4455. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  4456. if (T)
  4457. return QualType(T, 0);
  4458. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  4459. Types.push_back(T);
  4460. DependentNameTypes.InsertNode(T, InsertPos);
  4461. return QualType(T, 0);
  4462. }
  4463. QualType ASTContext::getDependentTemplateSpecializationType(
  4464. ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
  4465. const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const {
  4466. // TODO: avoid this copy
  4467. SmallVector<TemplateArgument, 16> ArgCopy;
  4468. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  4469. ArgCopy.push_back(Args[I].getArgument());
  4470. return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
  4471. }
  4472. QualType
  4473. ASTContext::getDependentTemplateSpecializationType(
  4474. ElaboratedTypeKeyword Keyword,
  4475. NestedNameSpecifier *NNS,
  4476. const IdentifierInfo *Name,
  4477. ArrayRef<TemplateArgument> Args) const {
  4478. assert((!NNS || NNS->isDependent()) &&
  4479. "nested-name-specifier must be dependent");
  4480. llvm::FoldingSetNodeID ID;
  4481. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  4482. Name, Args);
  4483. void *InsertPos = nullptr;
  4484. DependentTemplateSpecializationType *T
  4485. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4486. if (T)
  4487. return QualType(T, 0);
  4488. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  4489. ElaboratedTypeKeyword CanonKeyword = Keyword;
  4490. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  4491. bool AnyNonCanonArgs = false;
  4492. auto CanonArgs =
  4493. ::getCanonicalTemplateArguments(*this, Args, AnyNonCanonArgs);
  4494. QualType Canon;
  4495. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  4496. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  4497. Name,
  4498. CanonArgs);
  4499. // Find the insert position again.
  4500. [[maybe_unused]] auto *Nothing =
  4501. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4502. assert(!Nothing && "canonical type broken");
  4503. }
  4504. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  4505. sizeof(TemplateArgument) * Args.size()),
  4506. TypeAlignment);
  4507. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  4508. Name, Args, Canon);
  4509. Types.push_back(T);
  4510. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  4511. return QualType(T, 0);
  4512. }
  4513. TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
  4514. TemplateArgument Arg;
  4515. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  4516. QualType ArgType = getTypeDeclType(TTP);
  4517. if (TTP->isParameterPack())
  4518. ArgType = getPackExpansionType(ArgType, std::nullopt);
  4519. Arg = TemplateArgument(ArgType);
  4520. } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4521. QualType T =
  4522. NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
  4523. // For class NTTPs, ensure we include the 'const' so the type matches that
  4524. // of a real template argument.
  4525. // FIXME: It would be more faithful to model this as something like an
  4526. // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
  4527. if (T->isRecordType())
  4528. T.addConst();
  4529. Expr *E = new (*this) DeclRefExpr(
  4530. *this, NTTP, /*RefersToEnclosingVariableOrCapture*/ false, T,
  4531. Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
  4532. if (NTTP->isParameterPack())
  4533. E = new (*this)
  4534. PackExpansionExpr(DependentTy, E, NTTP->getLocation(), std::nullopt);
  4535. Arg = TemplateArgument(E);
  4536. } else {
  4537. auto *TTP = cast<TemplateTemplateParmDecl>(Param);
  4538. if (TTP->isParameterPack())
  4539. Arg = TemplateArgument(TemplateName(TTP), std::optional<unsigned>());
  4540. else
  4541. Arg = TemplateArgument(TemplateName(TTP));
  4542. }
  4543. if (Param->isTemplateParameterPack())
  4544. Arg = TemplateArgument::CreatePackCopy(*this, Arg);
  4545. return Arg;
  4546. }
  4547. void
  4548. ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
  4549. SmallVectorImpl<TemplateArgument> &Args) {
  4550. Args.reserve(Args.size() + Params->size());
  4551. for (NamedDecl *Param : *Params)
  4552. Args.push_back(getInjectedTemplateArg(Param));
  4553. }
  4554. QualType ASTContext::getPackExpansionType(QualType Pattern,
  4555. std::optional<unsigned> NumExpansions,
  4556. bool ExpectPackInType) {
  4557. assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
  4558. "Pack expansions must expand one or more parameter packs");
  4559. llvm::FoldingSetNodeID ID;
  4560. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  4561. void *InsertPos = nullptr;
  4562. PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  4563. if (T)
  4564. return QualType(T, 0);
  4565. QualType Canon;
  4566. if (!Pattern.isCanonical()) {
  4567. Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
  4568. /*ExpectPackInType=*/false);
  4569. // Find the insert position again, in case we inserted an element into
  4570. // PackExpansionTypes and invalidated our insert position.
  4571. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  4572. }
  4573. T = new (*this, TypeAlignment)
  4574. PackExpansionType(Pattern, Canon, NumExpansions);
  4575. Types.push_back(T);
  4576. PackExpansionTypes.InsertNode(T, InsertPos);
  4577. return QualType(T, 0);
  4578. }
  4579. /// CmpProtocolNames - Comparison predicate for sorting protocols
  4580. /// alphabetically.
  4581. static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
  4582. ObjCProtocolDecl *const *RHS) {
  4583. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  4584. }
  4585. static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
  4586. if (Protocols.empty()) return true;
  4587. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  4588. return false;
  4589. for (unsigned i = 1; i != Protocols.size(); ++i)
  4590. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  4591. Protocols[i]->getCanonicalDecl() != Protocols[i])
  4592. return false;
  4593. return true;
  4594. }
  4595. static void
  4596. SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
  4597. // Sort protocols, keyed by name.
  4598. llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
  4599. // Canonicalize.
  4600. for (ObjCProtocolDecl *&P : Protocols)
  4601. P = P->getCanonicalDecl();
  4602. // Remove duplicates.
  4603. auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
  4604. Protocols.erase(ProtocolsEnd, Protocols.end());
  4605. }
  4606. QualType ASTContext::getObjCObjectType(QualType BaseType,
  4607. ObjCProtocolDecl * const *Protocols,
  4608. unsigned NumProtocols) const {
  4609. return getObjCObjectType(BaseType, {},
  4610. llvm::ArrayRef(Protocols, NumProtocols),
  4611. /*isKindOf=*/false);
  4612. }
  4613. QualType ASTContext::getObjCObjectType(
  4614. QualType baseType,
  4615. ArrayRef<QualType> typeArgs,
  4616. ArrayRef<ObjCProtocolDecl *> protocols,
  4617. bool isKindOf) const {
  4618. // If the base type is an interface and there aren't any protocols or
  4619. // type arguments to add, then the interface type will do just fine.
  4620. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  4621. isa<ObjCInterfaceType>(baseType))
  4622. return baseType;
  4623. // Look in the folding set for an existing type.
  4624. llvm::FoldingSetNodeID ID;
  4625. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  4626. void *InsertPos = nullptr;
  4627. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  4628. return QualType(QT, 0);
  4629. // Determine the type arguments to be used for canonicalization,
  4630. // which may be explicitly specified here or written on the base
  4631. // type.
  4632. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  4633. if (effectiveTypeArgs.empty()) {
  4634. if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
  4635. effectiveTypeArgs = baseObject->getTypeArgs();
  4636. }
  4637. // Build the canonical type, which has the canonical base type and a
  4638. // sorted-and-uniqued list of protocols and the type arguments
  4639. // canonicalized.
  4640. QualType canonical;
  4641. bool typeArgsAreCanonical = llvm::all_of(
  4642. effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
  4643. bool protocolsSorted = areSortedAndUniqued(protocols);
  4644. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  4645. // Determine the canonical type arguments.
  4646. ArrayRef<QualType> canonTypeArgs;
  4647. SmallVector<QualType, 4> canonTypeArgsVec;
  4648. if (!typeArgsAreCanonical) {
  4649. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  4650. for (auto typeArg : effectiveTypeArgs)
  4651. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  4652. canonTypeArgs = canonTypeArgsVec;
  4653. } else {
  4654. canonTypeArgs = effectiveTypeArgs;
  4655. }
  4656. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  4657. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  4658. if (!protocolsSorted) {
  4659. canonProtocolsVec.append(protocols.begin(), protocols.end());
  4660. SortAndUniqueProtocols(canonProtocolsVec);
  4661. canonProtocols = canonProtocolsVec;
  4662. } else {
  4663. canonProtocols = protocols;
  4664. }
  4665. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  4666. canonProtocols, isKindOf);
  4667. // Regenerate InsertPos.
  4668. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  4669. }
  4670. unsigned size = sizeof(ObjCObjectTypeImpl);
  4671. size += typeArgs.size() * sizeof(QualType);
  4672. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4673. void *mem = Allocate(size, TypeAlignment);
  4674. auto *T =
  4675. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  4676. isKindOf);
  4677. Types.push_back(T);
  4678. ObjCObjectTypes.InsertNode(T, InsertPos);
  4679. return QualType(T, 0);
  4680. }
  4681. /// Apply Objective-C protocol qualifiers to the given type.
  4682. /// If this is for the canonical type of a type parameter, we can apply
  4683. /// protocol qualifiers on the ObjCObjectPointerType.
  4684. QualType
  4685. ASTContext::applyObjCProtocolQualifiers(QualType type,
  4686. ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
  4687. bool allowOnPointerType) const {
  4688. hasError = false;
  4689. if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
  4690. return getObjCTypeParamType(objT->getDecl(), protocols);
  4691. }
  4692. // Apply protocol qualifiers to ObjCObjectPointerType.
  4693. if (allowOnPointerType) {
  4694. if (const auto *objPtr =
  4695. dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
  4696. const ObjCObjectType *objT = objPtr->getObjectType();
  4697. // Merge protocol lists and construct ObjCObjectType.
  4698. SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
  4699. protocolsVec.append(objT->qual_begin(),
  4700. objT->qual_end());
  4701. protocolsVec.append(protocols.begin(), protocols.end());
  4702. ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
  4703. type = getObjCObjectType(
  4704. objT->getBaseType(),
  4705. objT->getTypeArgsAsWritten(),
  4706. protocols,
  4707. objT->isKindOfTypeAsWritten());
  4708. return getObjCObjectPointerType(type);
  4709. }
  4710. }
  4711. // Apply protocol qualifiers to ObjCObjectType.
  4712. if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
  4713. // FIXME: Check for protocols to which the class type is already
  4714. // known to conform.
  4715. return getObjCObjectType(objT->getBaseType(),
  4716. objT->getTypeArgsAsWritten(),
  4717. protocols,
  4718. objT->isKindOfTypeAsWritten());
  4719. }
  4720. // If the canonical type is ObjCObjectType, ...
  4721. if (type->isObjCObjectType()) {
  4722. // Silently overwrite any existing protocol qualifiers.
  4723. // TODO: determine whether that's the right thing to do.
  4724. // FIXME: Check for protocols to which the class type is already
  4725. // known to conform.
  4726. return getObjCObjectType(type, {}, protocols, false);
  4727. }
  4728. // id<protocol-list>
  4729. if (type->isObjCIdType()) {
  4730. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4731. type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
  4732. objPtr->isKindOfType());
  4733. return getObjCObjectPointerType(type);
  4734. }
  4735. // Class<protocol-list>
  4736. if (type->isObjCClassType()) {
  4737. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4738. type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
  4739. objPtr->isKindOfType());
  4740. return getObjCObjectPointerType(type);
  4741. }
  4742. hasError = true;
  4743. return type;
  4744. }
  4745. QualType
  4746. ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  4747. ArrayRef<ObjCProtocolDecl *> protocols) const {
  4748. // Look in the folding set for an existing type.
  4749. llvm::FoldingSetNodeID ID;
  4750. ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
  4751. void *InsertPos = nullptr;
  4752. if (ObjCTypeParamType *TypeParam =
  4753. ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
  4754. return QualType(TypeParam, 0);
  4755. // We canonicalize to the underlying type.
  4756. QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
  4757. if (!protocols.empty()) {
  4758. // Apply the protocol qualifers.
  4759. bool hasError;
  4760. Canonical = getCanonicalType(applyObjCProtocolQualifiers(
  4761. Canonical, protocols, hasError, true /*allowOnPointerType*/));
  4762. assert(!hasError && "Error when apply protocol qualifier to bound type");
  4763. }
  4764. unsigned size = sizeof(ObjCTypeParamType);
  4765. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4766. void *mem = Allocate(size, TypeAlignment);
  4767. auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
  4768. Types.push_back(newType);
  4769. ObjCTypeParamTypes.InsertNode(newType, InsertPos);
  4770. return QualType(newType, 0);
  4771. }
  4772. void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
  4773. ObjCTypeParamDecl *New) const {
  4774. New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
  4775. // Update TypeForDecl after updating TypeSourceInfo.
  4776. auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
  4777. SmallVector<ObjCProtocolDecl *, 8> protocols;
  4778. protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
  4779. QualType UpdatedTy = getObjCTypeParamType(New, protocols);
  4780. New->setTypeForDecl(UpdatedTy.getTypePtr());
  4781. }
  4782. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  4783. /// protocol list adopt all protocols in QT's qualified-id protocol
  4784. /// list.
  4785. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  4786. ObjCInterfaceDecl *IC) {
  4787. if (!QT->isObjCQualifiedIdType())
  4788. return false;
  4789. if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
  4790. // If both the right and left sides have qualifiers.
  4791. for (auto *Proto : OPT->quals()) {
  4792. if (!IC->ClassImplementsProtocol(Proto, false))
  4793. return false;
  4794. }
  4795. return true;
  4796. }
  4797. return false;
  4798. }
  4799. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  4800. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  4801. /// of protocols.
  4802. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  4803. ObjCInterfaceDecl *IDecl) {
  4804. if (!QT->isObjCQualifiedIdType())
  4805. return false;
  4806. const auto *OPT = QT->getAs<ObjCObjectPointerType>();
  4807. if (!OPT)
  4808. return false;
  4809. if (!IDecl->hasDefinition())
  4810. return false;
  4811. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  4812. CollectInheritedProtocols(IDecl, InheritedProtocols);
  4813. if (InheritedProtocols.empty())
  4814. return false;
  4815. // Check that if every protocol in list of id<plist> conforms to a protocol
  4816. // of IDecl's, then bridge casting is ok.
  4817. bool Conforms = false;
  4818. for (auto *Proto : OPT->quals()) {
  4819. Conforms = false;
  4820. for (auto *PI : InheritedProtocols) {
  4821. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  4822. Conforms = true;
  4823. break;
  4824. }
  4825. }
  4826. if (!Conforms)
  4827. break;
  4828. }
  4829. if (Conforms)
  4830. return true;
  4831. for (auto *PI : InheritedProtocols) {
  4832. // If both the right and left sides have qualifiers.
  4833. bool Adopts = false;
  4834. for (auto *Proto : OPT->quals()) {
  4835. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  4836. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  4837. break;
  4838. }
  4839. if (!Adopts)
  4840. return false;
  4841. }
  4842. return true;
  4843. }
  4844. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  4845. /// the given object type.
  4846. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  4847. llvm::FoldingSetNodeID ID;
  4848. ObjCObjectPointerType::Profile(ID, ObjectT);
  4849. void *InsertPos = nullptr;
  4850. if (ObjCObjectPointerType *QT =
  4851. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  4852. return QualType(QT, 0);
  4853. // Find the canonical object type.
  4854. QualType Canonical;
  4855. if (!ObjectT.isCanonical()) {
  4856. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  4857. // Regenerate InsertPos.
  4858. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  4859. }
  4860. // No match.
  4861. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  4862. auto *QType =
  4863. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  4864. Types.push_back(QType);
  4865. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  4866. return QualType(QType, 0);
  4867. }
  4868. /// getObjCInterfaceType - Return the unique reference to the type for the
  4869. /// specified ObjC interface decl. The list of protocols is optional.
  4870. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  4871. ObjCInterfaceDecl *PrevDecl) const {
  4872. if (Decl->TypeForDecl)
  4873. return QualType(Decl->TypeForDecl, 0);
  4874. if (PrevDecl) {
  4875. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  4876. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  4877. return QualType(PrevDecl->TypeForDecl, 0);
  4878. }
  4879. // Prefer the definition, if there is one.
  4880. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  4881. Decl = Def;
  4882. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  4883. auto *T = new (Mem) ObjCInterfaceType(Decl);
  4884. Decl->TypeForDecl = T;
  4885. Types.push_back(T);
  4886. return QualType(T, 0);
  4887. }
  4888. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  4889. /// TypeOfExprType AST's (since expression's are never shared). For example,
  4890. /// multiple declarations that refer to "typeof(x)" all contain different
  4891. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  4892. /// on canonical type's (which are always unique).
  4893. QualType ASTContext::getTypeOfExprType(Expr *tofExpr, TypeOfKind Kind) const {
  4894. TypeOfExprType *toe;
  4895. if (tofExpr->isTypeDependent()) {
  4896. llvm::FoldingSetNodeID ID;
  4897. DependentTypeOfExprType::Profile(ID, *this, tofExpr,
  4898. Kind == TypeOfKind::Unqualified);
  4899. void *InsertPos = nullptr;
  4900. DependentTypeOfExprType *Canon =
  4901. DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  4902. if (Canon) {
  4903. // We already have a "canonical" version of an identical, dependent
  4904. // typeof(expr) type. Use that as our canonical type.
  4905. toe = new (*this, TypeAlignment)
  4906. TypeOfExprType(tofExpr, Kind, QualType((TypeOfExprType *)Canon, 0));
  4907. } else {
  4908. // Build a new, canonical typeof(expr) type.
  4909. Canon = new (*this, TypeAlignment)
  4910. DependentTypeOfExprType(*this, tofExpr, Kind);
  4911. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  4912. toe = Canon;
  4913. }
  4914. } else {
  4915. QualType Canonical = getCanonicalType(tofExpr->getType());
  4916. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Kind, Canonical);
  4917. }
  4918. Types.push_back(toe);
  4919. return QualType(toe, 0);
  4920. }
  4921. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  4922. /// TypeOfType nodes. The only motivation to unique these nodes would be
  4923. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  4924. /// an issue. This doesn't affect the type checker, since it operates
  4925. /// on canonical types (which are always unique).
  4926. QualType ASTContext::getTypeOfType(QualType tofType, TypeOfKind Kind) const {
  4927. QualType Canonical = getCanonicalType(tofType);
  4928. auto *tot =
  4929. new (*this, TypeAlignment) TypeOfType(tofType, Canonical, Kind);
  4930. Types.push_back(tot);
  4931. return QualType(tot, 0);
  4932. }
  4933. /// getReferenceQualifiedType - Given an expr, will return the type for
  4934. /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
  4935. /// and class member access into account.
  4936. QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
  4937. // C++11 [dcl.type.simple]p4:
  4938. // [...]
  4939. QualType T = E->getType();
  4940. switch (E->getValueKind()) {
  4941. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  4942. // type of e;
  4943. case VK_XValue:
  4944. return getRValueReferenceType(T);
  4945. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  4946. // type of e;
  4947. case VK_LValue:
  4948. return getLValueReferenceType(T);
  4949. // - otherwise, decltype(e) is the type of e.
  4950. case VK_PRValue:
  4951. return T;
  4952. }
  4953. llvm_unreachable("Unknown value kind");
  4954. }
  4955. /// Unlike many "get<Type>" functions, we don't unique DecltypeType
  4956. /// nodes. This would never be helpful, since each such type has its own
  4957. /// expression, and would not give a significant memory saving, since there
  4958. /// is an Expr tree under each such type.
  4959. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  4960. DecltypeType *dt;
  4961. // C++11 [temp.type]p2:
  4962. // If an expression e involves a template parameter, decltype(e) denotes a
  4963. // unique dependent type. Two such decltype-specifiers refer to the same
  4964. // type only if their expressions are equivalent (14.5.6.1).
  4965. if (e->isInstantiationDependent()) {
  4966. llvm::FoldingSetNodeID ID;
  4967. DependentDecltypeType::Profile(ID, *this, e);
  4968. void *InsertPos = nullptr;
  4969. DependentDecltypeType *Canon
  4970. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  4971. if (!Canon) {
  4972. // Build a new, canonical decltype(expr) type.
  4973. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  4974. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  4975. }
  4976. dt = new (*this, TypeAlignment)
  4977. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  4978. } else {
  4979. dt = new (*this, TypeAlignment)
  4980. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  4981. }
  4982. Types.push_back(dt);
  4983. return QualType(dt, 0);
  4984. }
  4985. /// getUnaryTransformationType - We don't unique these, since the memory
  4986. /// savings are minimal and these are rare.
  4987. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  4988. QualType UnderlyingType,
  4989. UnaryTransformType::UTTKind Kind)
  4990. const {
  4991. UnaryTransformType *ut = nullptr;
  4992. if (BaseType->isDependentType()) {
  4993. // Look in the folding set for an existing type.
  4994. llvm::FoldingSetNodeID ID;
  4995. DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
  4996. void *InsertPos = nullptr;
  4997. DependentUnaryTransformType *Canon
  4998. = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
  4999. if (!Canon) {
  5000. // Build a new, canonical __underlying_type(type) type.
  5001. Canon = new (*this, TypeAlignment)
  5002. DependentUnaryTransformType(*this, getCanonicalType(BaseType),
  5003. Kind);
  5004. DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
  5005. }
  5006. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  5007. QualType(), Kind,
  5008. QualType(Canon, 0));
  5009. } else {
  5010. QualType CanonType = getCanonicalType(UnderlyingType);
  5011. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  5012. UnderlyingType, Kind,
  5013. CanonType);
  5014. }
  5015. Types.push_back(ut);
  5016. return QualType(ut, 0);
  5017. }
  5018. QualType ASTContext::getAutoTypeInternal(
  5019. QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
  5020. bool IsPack, ConceptDecl *TypeConstraintConcept,
  5021. ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
  5022. if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
  5023. !TypeConstraintConcept && !IsDependent)
  5024. return getAutoDeductType();
  5025. // Look in the folding set for an existing type.
  5026. void *InsertPos = nullptr;
  5027. llvm::FoldingSetNodeID ID;
  5028. AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
  5029. TypeConstraintConcept, TypeConstraintArgs);
  5030. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  5031. return QualType(AT, 0);
  5032. QualType Canon;
  5033. if (!IsCanon) {
  5034. if (!DeducedType.isNull()) {
  5035. Canon = DeducedType.getCanonicalType();
  5036. } else if (TypeConstraintConcept) {
  5037. Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
  5038. nullptr, {}, true);
  5039. // Find the insert position again.
  5040. [[maybe_unused]] auto *Nothing =
  5041. AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
  5042. assert(!Nothing && "canonical type broken");
  5043. }
  5044. }
  5045. void *Mem = Allocate(sizeof(AutoType) +
  5046. sizeof(TemplateArgument) * TypeConstraintArgs.size(),
  5047. TypeAlignment);
  5048. auto *AT = new (Mem) AutoType(
  5049. DeducedType, Keyword,
  5050. (IsDependent ? TypeDependence::DependentInstantiation
  5051. : TypeDependence::None) |
  5052. (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
  5053. Canon, TypeConstraintConcept, TypeConstraintArgs);
  5054. Types.push_back(AT);
  5055. AutoTypes.InsertNode(AT, InsertPos);
  5056. return QualType(AT, 0);
  5057. }
  5058. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  5059. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  5060. /// canonical deduced-but-dependent 'auto' type.
  5061. QualType
  5062. ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
  5063. bool IsDependent, bool IsPack,
  5064. ConceptDecl *TypeConstraintConcept,
  5065. ArrayRef<TemplateArgument> TypeConstraintArgs) const {
  5066. assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
  5067. assert((!IsDependent || DeducedType.isNull()) &&
  5068. "A dependent auto should be undeduced");
  5069. return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
  5070. TypeConstraintConcept, TypeConstraintArgs);
  5071. }
  5072. /// Return the uniqued reference to the deduced template specialization type
  5073. /// which has been deduced to the given type, or to the canonical undeduced
  5074. /// such type, or the canonical deduced-but-dependent such type.
  5075. QualType ASTContext::getDeducedTemplateSpecializationType(
  5076. TemplateName Template, QualType DeducedType, bool IsDependent) const {
  5077. // Look in the folding set for an existing type.
  5078. void *InsertPos = nullptr;
  5079. llvm::FoldingSetNodeID ID;
  5080. DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
  5081. IsDependent);
  5082. if (DeducedTemplateSpecializationType *DTST =
  5083. DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
  5084. return QualType(DTST, 0);
  5085. auto *DTST = new (*this, TypeAlignment)
  5086. DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
  5087. llvm::FoldingSetNodeID TempID;
  5088. DTST->Profile(TempID);
  5089. assert(ID == TempID && "ID does not match");
  5090. Types.push_back(DTST);
  5091. DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
  5092. return QualType(DTST, 0);
  5093. }
  5094. /// getAtomicType - Return the uniqued reference to the atomic type for
  5095. /// the given value type.
  5096. QualType ASTContext::getAtomicType(QualType T) const {
  5097. // Unique pointers, to guarantee there is only one pointer of a particular
  5098. // structure.
  5099. llvm::FoldingSetNodeID ID;
  5100. AtomicType::Profile(ID, T);
  5101. void *InsertPos = nullptr;
  5102. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  5103. return QualType(AT, 0);
  5104. // If the atomic value type isn't canonical, this won't be a canonical type
  5105. // either, so fill in the canonical type field.
  5106. QualType Canonical;
  5107. if (!T.isCanonical()) {
  5108. Canonical = getAtomicType(getCanonicalType(T));
  5109. // Get the new insert position for the node we care about.
  5110. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  5111. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  5112. }
  5113. auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  5114. Types.push_back(New);
  5115. AtomicTypes.InsertNode(New, InsertPos);
  5116. return QualType(New, 0);
  5117. }
  5118. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  5119. QualType ASTContext::getAutoDeductType() const {
  5120. if (AutoDeductTy.isNull())
  5121. AutoDeductTy = QualType(new (*this, TypeAlignment)
  5122. AutoType(QualType(), AutoTypeKeyword::Auto,
  5123. TypeDependence::None, QualType(),
  5124. /*concept*/ nullptr, /*args*/ {}),
  5125. 0);
  5126. return AutoDeductTy;
  5127. }
  5128. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  5129. QualType ASTContext::getAutoRRefDeductType() const {
  5130. if (AutoRRefDeductTy.isNull())
  5131. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  5132. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  5133. return AutoRRefDeductTy;
  5134. }
  5135. /// getTagDeclType - Return the unique reference to the type for the
  5136. /// specified TagDecl (struct/union/class/enum) decl.
  5137. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  5138. assert(Decl);
  5139. // FIXME: What is the design on getTagDeclType when it requires casting
  5140. // away const? mutable?
  5141. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  5142. }
  5143. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  5144. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  5145. /// needs to agree with the definition in <stddef.h>.
  5146. CanQualType ASTContext::getSizeType() const {
  5147. return getFromTargetType(Target->getSizeType());
  5148. }
  5149. /// Return the unique signed counterpart of the integer type
  5150. /// corresponding to size_t.
  5151. CanQualType ASTContext::getSignedSizeType() const {
  5152. return getFromTargetType(Target->getSignedSizeType());
  5153. }
  5154. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  5155. CanQualType ASTContext::getIntMaxType() const {
  5156. return getFromTargetType(Target->getIntMaxType());
  5157. }
  5158. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  5159. CanQualType ASTContext::getUIntMaxType() const {
  5160. return getFromTargetType(Target->getUIntMaxType());
  5161. }
  5162. /// getSignedWCharType - Return the type of "signed wchar_t".
  5163. /// Used when in C++, as a GCC extension.
  5164. QualType ASTContext::getSignedWCharType() const {
  5165. // FIXME: derive from "Target" ?
  5166. return WCharTy;
  5167. }
  5168. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  5169. /// Used when in C++, as a GCC extension.
  5170. QualType ASTContext::getUnsignedWCharType() const {
  5171. // FIXME: derive from "Target" ?
  5172. return UnsignedIntTy;
  5173. }
  5174. QualType ASTContext::getIntPtrType() const {
  5175. return getFromTargetType(Target->getIntPtrType());
  5176. }
  5177. QualType ASTContext::getUIntPtrType() const {
  5178. return getCorrespondingUnsignedType(getIntPtrType());
  5179. }
  5180. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  5181. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  5182. QualType ASTContext::getPointerDiffType() const {
  5183. return getFromTargetType(Target->getPtrDiffType(LangAS::Default));
  5184. }
  5185. /// Return the unique unsigned counterpart of "ptrdiff_t"
  5186. /// integer type. The standard (C11 7.21.6.1p7) refers to this type
  5187. /// in the definition of %tu format specifier.
  5188. QualType ASTContext::getUnsignedPointerDiffType() const {
  5189. return getFromTargetType(Target->getUnsignedPtrDiffType(LangAS::Default));
  5190. }
  5191. /// Return the unique type for "pid_t" defined in
  5192. /// <sys/types.h>. We need this to compute the correct type for vfork().
  5193. QualType ASTContext::getProcessIDType() const {
  5194. return getFromTargetType(Target->getProcessIDType());
  5195. }
  5196. //===----------------------------------------------------------------------===//
  5197. // Type Operators
  5198. //===----------------------------------------------------------------------===//
  5199. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  5200. // Push qualifiers into arrays, and then discard any remaining
  5201. // qualifiers.
  5202. T = getCanonicalType(T);
  5203. T = getVariableArrayDecayedType(T);
  5204. const Type *Ty = T.getTypePtr();
  5205. QualType Result;
  5206. if (isa<ArrayType>(Ty)) {
  5207. Result = getArrayDecayedType(QualType(Ty,0));
  5208. } else if (isa<FunctionType>(Ty)) {
  5209. Result = getPointerType(QualType(Ty, 0));
  5210. } else {
  5211. Result = QualType(Ty, 0);
  5212. }
  5213. return CanQualType::CreateUnsafe(Result);
  5214. }
  5215. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  5216. Qualifiers &quals) {
  5217. SplitQualType splitType = type.getSplitUnqualifiedType();
  5218. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  5219. // the unqualified desugared type and then drops it on the floor.
  5220. // We then have to strip that sugar back off with
  5221. // getUnqualifiedDesugaredType(), which is silly.
  5222. const auto *AT =
  5223. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  5224. // If we don't have an array, just use the results in splitType.
  5225. if (!AT) {
  5226. quals = splitType.Quals;
  5227. return QualType(splitType.Ty, 0);
  5228. }
  5229. // Otherwise, recurse on the array's element type.
  5230. QualType elementType = AT->getElementType();
  5231. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  5232. // If that didn't change the element type, AT has no qualifiers, so we
  5233. // can just use the results in splitType.
  5234. if (elementType == unqualElementType) {
  5235. assert(quals.empty()); // from the recursive call
  5236. quals = splitType.Quals;
  5237. return QualType(splitType.Ty, 0);
  5238. }
  5239. // Otherwise, add in the qualifiers from the outermost type, then
  5240. // build the type back up.
  5241. quals.addConsistentQualifiers(splitType.Quals);
  5242. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  5243. return getConstantArrayType(unqualElementType, CAT->getSize(),
  5244. CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
  5245. }
  5246. if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  5247. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  5248. }
  5249. if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
  5250. return getVariableArrayType(unqualElementType,
  5251. VAT->getSizeExpr(),
  5252. VAT->getSizeModifier(),
  5253. VAT->getIndexTypeCVRQualifiers(),
  5254. VAT->getBracketsRange());
  5255. }
  5256. const auto *DSAT = cast<DependentSizedArrayType>(AT);
  5257. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  5258. DSAT->getSizeModifier(), 0,
  5259. SourceRange());
  5260. }
  5261. /// Attempt to unwrap two types that may both be array types with the same bound
  5262. /// (or both be array types of unknown bound) for the purpose of comparing the
  5263. /// cv-decomposition of two types per C++ [conv.qual].
  5264. ///
  5265. /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
  5266. /// C++20 [conv.qual], if permitted by the current language mode.
  5267. void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
  5268. bool AllowPiMismatch) {
  5269. while (true) {
  5270. auto *AT1 = getAsArrayType(T1);
  5271. if (!AT1)
  5272. return;
  5273. auto *AT2 = getAsArrayType(T2);
  5274. if (!AT2)
  5275. return;
  5276. // If we don't have two array types with the same constant bound nor two
  5277. // incomplete array types, we've unwrapped everything we can.
  5278. // C++20 also permits one type to be a constant array type and the other
  5279. // to be an incomplete array type.
  5280. // FIXME: Consider also unwrapping array of unknown bound and VLA.
  5281. if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
  5282. auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
  5283. if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
  5284. (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
  5285. isa<IncompleteArrayType>(AT2))))
  5286. return;
  5287. } else if (isa<IncompleteArrayType>(AT1)) {
  5288. if (!(isa<IncompleteArrayType>(AT2) ||
  5289. (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
  5290. isa<ConstantArrayType>(AT2))))
  5291. return;
  5292. } else {
  5293. return;
  5294. }
  5295. T1 = AT1->getElementType();
  5296. T2 = AT2->getElementType();
  5297. }
  5298. }
  5299. /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
  5300. ///
  5301. /// If T1 and T2 are both pointer types of the same kind, or both array types
  5302. /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
  5303. /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
  5304. ///
  5305. /// This function will typically be called in a loop that successively
  5306. /// "unwraps" pointer and pointer-to-member types to compare them at each
  5307. /// level.
  5308. ///
  5309. /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
  5310. /// C++20 [conv.qual], if permitted by the current language mode.
  5311. ///
  5312. /// \return \c true if a pointer type was unwrapped, \c false if we reached a
  5313. /// pair of types that can't be unwrapped further.
  5314. bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
  5315. bool AllowPiMismatch) {
  5316. UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
  5317. const auto *T1PtrType = T1->getAs<PointerType>();
  5318. const auto *T2PtrType = T2->getAs<PointerType>();
  5319. if (T1PtrType && T2PtrType) {
  5320. T1 = T1PtrType->getPointeeType();
  5321. T2 = T2PtrType->getPointeeType();
  5322. return true;
  5323. }
  5324. const auto *T1MPType = T1->getAs<MemberPointerType>();
  5325. const auto *T2MPType = T2->getAs<MemberPointerType>();
  5326. if (T1MPType && T2MPType &&
  5327. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  5328. QualType(T2MPType->getClass(), 0))) {
  5329. T1 = T1MPType->getPointeeType();
  5330. T2 = T2MPType->getPointeeType();
  5331. return true;
  5332. }
  5333. if (getLangOpts().ObjC) {
  5334. const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
  5335. const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
  5336. if (T1OPType && T2OPType) {
  5337. T1 = T1OPType->getPointeeType();
  5338. T2 = T2OPType->getPointeeType();
  5339. return true;
  5340. }
  5341. }
  5342. // FIXME: Block pointers, too?
  5343. return false;
  5344. }
  5345. bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
  5346. while (true) {
  5347. Qualifiers Quals;
  5348. T1 = getUnqualifiedArrayType(T1, Quals);
  5349. T2 = getUnqualifiedArrayType(T2, Quals);
  5350. if (hasSameType(T1, T2))
  5351. return true;
  5352. if (!UnwrapSimilarTypes(T1, T2))
  5353. return false;
  5354. }
  5355. }
  5356. bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
  5357. while (true) {
  5358. Qualifiers Quals1, Quals2;
  5359. T1 = getUnqualifiedArrayType(T1, Quals1);
  5360. T2 = getUnqualifiedArrayType(T2, Quals2);
  5361. Quals1.removeCVRQualifiers();
  5362. Quals2.removeCVRQualifiers();
  5363. if (Quals1 != Quals2)
  5364. return false;
  5365. if (hasSameType(T1, T2))
  5366. return true;
  5367. if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
  5368. return false;
  5369. }
  5370. }
  5371. DeclarationNameInfo
  5372. ASTContext::getNameForTemplate(TemplateName Name,
  5373. SourceLocation NameLoc) const {
  5374. switch (Name.getKind()) {
  5375. case TemplateName::QualifiedTemplate:
  5376. case TemplateName::Template:
  5377. // DNInfo work in progress: CHECKME: what about DNLoc?
  5378. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  5379. NameLoc);
  5380. case TemplateName::OverloadedTemplate: {
  5381. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  5382. // DNInfo work in progress: CHECKME: what about DNLoc?
  5383. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  5384. }
  5385. case TemplateName::AssumedTemplate: {
  5386. AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
  5387. return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
  5388. }
  5389. case TemplateName::DependentTemplate: {
  5390. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  5391. DeclarationName DName;
  5392. if (DTN->isIdentifier()) {
  5393. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  5394. return DeclarationNameInfo(DName, NameLoc);
  5395. } else {
  5396. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  5397. // DNInfo work in progress: FIXME: source locations?
  5398. DeclarationNameLoc DNLoc =
  5399. DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
  5400. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  5401. }
  5402. }
  5403. case TemplateName::SubstTemplateTemplateParm: {
  5404. SubstTemplateTemplateParmStorage *subst
  5405. = Name.getAsSubstTemplateTemplateParm();
  5406. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  5407. NameLoc);
  5408. }
  5409. case TemplateName::SubstTemplateTemplateParmPack: {
  5410. SubstTemplateTemplateParmPackStorage *subst
  5411. = Name.getAsSubstTemplateTemplateParmPack();
  5412. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  5413. NameLoc);
  5414. }
  5415. case TemplateName::UsingTemplate:
  5416. return DeclarationNameInfo(Name.getAsUsingShadowDecl()->getDeclName(),
  5417. NameLoc);
  5418. }
  5419. llvm_unreachable("bad template name kind!");
  5420. }
  5421. TemplateName
  5422. ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
  5423. switch (Name.getKind()) {
  5424. case TemplateName::UsingTemplate:
  5425. case TemplateName::QualifiedTemplate:
  5426. case TemplateName::Template: {
  5427. TemplateDecl *Template = Name.getAsTemplateDecl();
  5428. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
  5429. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  5430. // The canonical template name is the canonical template declaration.
  5431. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  5432. }
  5433. case TemplateName::OverloadedTemplate:
  5434. case TemplateName::AssumedTemplate:
  5435. llvm_unreachable("cannot canonicalize unresolved template");
  5436. case TemplateName::DependentTemplate: {
  5437. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  5438. assert(DTN && "Non-dependent template names must refer to template decls.");
  5439. return DTN->CanonicalTemplateName;
  5440. }
  5441. case TemplateName::SubstTemplateTemplateParm: {
  5442. SubstTemplateTemplateParmStorage *subst
  5443. = Name.getAsSubstTemplateTemplateParm();
  5444. return getCanonicalTemplateName(subst->getReplacement());
  5445. }
  5446. case TemplateName::SubstTemplateTemplateParmPack: {
  5447. SubstTemplateTemplateParmPackStorage *subst =
  5448. Name.getAsSubstTemplateTemplateParmPack();
  5449. TemplateArgument canonArgPack =
  5450. getCanonicalTemplateArgument(subst->getArgumentPack());
  5451. return getSubstTemplateTemplateParmPack(
  5452. canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
  5453. subst->getFinal(), subst->getIndex());
  5454. }
  5455. }
  5456. llvm_unreachable("bad template name!");
  5457. }
  5458. bool ASTContext::hasSameTemplateName(const TemplateName &X,
  5459. const TemplateName &Y) const {
  5460. return getCanonicalTemplateName(X).getAsVoidPointer() ==
  5461. getCanonicalTemplateName(Y).getAsVoidPointer();
  5462. }
  5463. bool ASTContext::isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const {
  5464. if (!XCE != !YCE)
  5465. return false;
  5466. if (!XCE)
  5467. return true;
  5468. llvm::FoldingSetNodeID XCEID, YCEID;
  5469. XCE->Profile(XCEID, *this, /*Canonical=*/true);
  5470. YCE->Profile(YCEID, *this, /*Canonical=*/true);
  5471. return XCEID == YCEID;
  5472. }
  5473. bool ASTContext::isSameTypeConstraint(const TypeConstraint *XTC,
  5474. const TypeConstraint *YTC) const {
  5475. if (!XTC != !YTC)
  5476. return false;
  5477. if (!XTC)
  5478. return true;
  5479. auto *NCX = XTC->getNamedConcept();
  5480. auto *NCY = YTC->getNamedConcept();
  5481. if (!NCX || !NCY || !isSameEntity(NCX, NCY))
  5482. return false;
  5483. if (XTC->hasExplicitTemplateArgs() != YTC->hasExplicitTemplateArgs())
  5484. return false;
  5485. if (XTC->hasExplicitTemplateArgs())
  5486. if (XTC->getTemplateArgsAsWritten()->NumTemplateArgs !=
  5487. YTC->getTemplateArgsAsWritten()->NumTemplateArgs)
  5488. return false;
  5489. // Compare slowly by profiling.
  5490. //
  5491. // We couldn't compare the profiling result for the template
  5492. // args here. Consider the following example in different modules:
  5493. //
  5494. // template <__integer_like _Tp, C<_Tp> Sentinel>
  5495. // constexpr _Tp operator()(_Tp &&__t, Sentinel &&last) const {
  5496. // return __t;
  5497. // }
  5498. //
  5499. // When we compare the profiling result for `C<_Tp>` in different
  5500. // modules, it will compare the type of `_Tp` in different modules.
  5501. // However, the type of `_Tp` in different modules refer to different
  5502. // types here naturally. So we couldn't compare the profiling result
  5503. // for the template args directly.
  5504. return isSameConstraintExpr(XTC->getImmediatelyDeclaredConstraint(),
  5505. YTC->getImmediatelyDeclaredConstraint());
  5506. }
  5507. bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
  5508. const NamedDecl *Y) const {
  5509. if (X->getKind() != Y->getKind())
  5510. return false;
  5511. if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
  5512. auto *TY = cast<TemplateTypeParmDecl>(Y);
  5513. if (TX->isParameterPack() != TY->isParameterPack())
  5514. return false;
  5515. if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
  5516. return false;
  5517. return isSameTypeConstraint(TX->getTypeConstraint(),
  5518. TY->getTypeConstraint());
  5519. }
  5520. if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
  5521. auto *TY = cast<NonTypeTemplateParmDecl>(Y);
  5522. return TX->isParameterPack() == TY->isParameterPack() &&
  5523. TX->getASTContext().hasSameType(TX->getType(), TY->getType()) &&
  5524. isSameConstraintExpr(TX->getPlaceholderTypeConstraint(),
  5525. TY->getPlaceholderTypeConstraint());
  5526. }
  5527. auto *TX = cast<TemplateTemplateParmDecl>(X);
  5528. auto *TY = cast<TemplateTemplateParmDecl>(Y);
  5529. return TX->isParameterPack() == TY->isParameterPack() &&
  5530. isSameTemplateParameterList(TX->getTemplateParameters(),
  5531. TY->getTemplateParameters());
  5532. }
  5533. bool ASTContext::isSameTemplateParameterList(
  5534. const TemplateParameterList *X, const TemplateParameterList *Y) const {
  5535. if (X->size() != Y->size())
  5536. return false;
  5537. for (unsigned I = 0, N = X->size(); I != N; ++I)
  5538. if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
  5539. return false;
  5540. return isSameConstraintExpr(X->getRequiresClause(), Y->getRequiresClause());
  5541. }
  5542. bool ASTContext::isSameDefaultTemplateArgument(const NamedDecl *X,
  5543. const NamedDecl *Y) const {
  5544. // If the type parameter isn't the same already, we don't need to check the
  5545. // default argument further.
  5546. if (!isSameTemplateParameter(X, Y))
  5547. return false;
  5548. if (auto *TTPX = dyn_cast<TemplateTypeParmDecl>(X)) {
  5549. auto *TTPY = cast<TemplateTypeParmDecl>(Y);
  5550. if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
  5551. return false;
  5552. return hasSameType(TTPX->getDefaultArgument(), TTPY->getDefaultArgument());
  5553. }
  5554. if (auto *NTTPX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
  5555. auto *NTTPY = cast<NonTypeTemplateParmDecl>(Y);
  5556. if (!NTTPX->hasDefaultArgument() || !NTTPY->hasDefaultArgument())
  5557. return false;
  5558. Expr *DefaultArgumentX = NTTPX->getDefaultArgument()->IgnoreImpCasts();
  5559. Expr *DefaultArgumentY = NTTPY->getDefaultArgument()->IgnoreImpCasts();
  5560. llvm::FoldingSetNodeID XID, YID;
  5561. DefaultArgumentX->Profile(XID, *this, /*Canonical=*/true);
  5562. DefaultArgumentY->Profile(YID, *this, /*Canonical=*/true);
  5563. return XID == YID;
  5564. }
  5565. auto *TTPX = cast<TemplateTemplateParmDecl>(X);
  5566. auto *TTPY = cast<TemplateTemplateParmDecl>(Y);
  5567. if (!TTPX->hasDefaultArgument() || !TTPY->hasDefaultArgument())
  5568. return false;
  5569. const TemplateArgument &TAX = TTPX->getDefaultArgument().getArgument();
  5570. const TemplateArgument &TAY = TTPY->getDefaultArgument().getArgument();
  5571. return hasSameTemplateName(TAX.getAsTemplate(), TAY.getAsTemplate());
  5572. }
  5573. static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
  5574. if (auto *NS = X->getAsNamespace())
  5575. return NS;
  5576. if (auto *NAS = X->getAsNamespaceAlias())
  5577. return NAS->getNamespace();
  5578. return nullptr;
  5579. }
  5580. static bool isSameQualifier(const NestedNameSpecifier *X,
  5581. const NestedNameSpecifier *Y) {
  5582. if (auto *NSX = getNamespace(X)) {
  5583. auto *NSY = getNamespace(Y);
  5584. if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
  5585. return false;
  5586. } else if (X->getKind() != Y->getKind())
  5587. return false;
  5588. // FIXME: For namespaces and types, we're permitted to check that the entity
  5589. // is named via the same tokens. We should probably do so.
  5590. switch (X->getKind()) {
  5591. case NestedNameSpecifier::Identifier:
  5592. if (X->getAsIdentifier() != Y->getAsIdentifier())
  5593. return false;
  5594. break;
  5595. case NestedNameSpecifier::Namespace:
  5596. case NestedNameSpecifier::NamespaceAlias:
  5597. // We've already checked that we named the same namespace.
  5598. break;
  5599. case NestedNameSpecifier::TypeSpec:
  5600. case NestedNameSpecifier::TypeSpecWithTemplate:
  5601. if (X->getAsType()->getCanonicalTypeInternal() !=
  5602. Y->getAsType()->getCanonicalTypeInternal())
  5603. return false;
  5604. break;
  5605. case NestedNameSpecifier::Global:
  5606. case NestedNameSpecifier::Super:
  5607. return true;
  5608. }
  5609. // Recurse into earlier portion of NNS, if any.
  5610. auto *PX = X->getPrefix();
  5611. auto *PY = Y->getPrefix();
  5612. if (PX && PY)
  5613. return isSameQualifier(PX, PY);
  5614. return !PX && !PY;
  5615. }
  5616. /// Determine whether the attributes we can overload on are identical for A and
  5617. /// B. Will ignore any overloadable attrs represented in the type of A and B.
  5618. static bool hasSameOverloadableAttrs(const FunctionDecl *A,
  5619. const FunctionDecl *B) {
  5620. // Note that pass_object_size attributes are represented in the function's
  5621. // ExtParameterInfo, so we don't need to check them here.
  5622. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  5623. auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
  5624. auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
  5625. for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
  5626. std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  5627. std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  5628. // Return false if the number of enable_if attributes is different.
  5629. if (!Cand1A || !Cand2A)
  5630. return false;
  5631. Cand1ID.clear();
  5632. Cand2ID.clear();
  5633. (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
  5634. (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
  5635. // Return false if any of the enable_if expressions of A and B are
  5636. // different.
  5637. if (Cand1ID != Cand2ID)
  5638. return false;
  5639. }
  5640. return true;
  5641. }
  5642. bool ASTContext::FriendsDifferByConstraints(const FunctionDecl *X,
  5643. const FunctionDecl *Y) const {
  5644. // If these aren't friends, then they aren't friends that differ by
  5645. // constraints.
  5646. if (!X->getFriendObjectKind() || !Y->getFriendObjectKind())
  5647. return false;
  5648. // If the two functions share lexical declaration context, they are not in
  5649. // separate instantations, and thus in the same scope.
  5650. if (X->getLexicalDeclContext() == Y->getLexicalDeclContext())
  5651. return false;
  5652. if (!X->getDescribedFunctionTemplate()) {
  5653. assert(!Y->getDescribedFunctionTemplate() &&
  5654. "How would these be the same if they aren't both templates?");
  5655. // If these friends don't have constraints, they aren't constrained, and
  5656. // thus don't fall under temp.friend p9. Else the simple presence of a
  5657. // constraint makes them unique.
  5658. return X->getTrailingRequiresClause();
  5659. }
  5660. return X->FriendConstraintRefersToEnclosingTemplate();
  5661. }
  5662. bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) const {
  5663. if (X == Y)
  5664. return true;
  5665. if (X->getDeclName() != Y->getDeclName())
  5666. return false;
  5667. // Must be in the same context.
  5668. //
  5669. // Note that we can't use DeclContext::Equals here, because the DeclContexts
  5670. // could be two different declarations of the same function. (We will fix the
  5671. // semantic DC to refer to the primary definition after merging.)
  5672. if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
  5673. cast<Decl>(Y->getDeclContext()->getRedeclContext())))
  5674. return false;
  5675. // Two typedefs refer to the same entity if they have the same underlying
  5676. // type.
  5677. if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
  5678. if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
  5679. return hasSameType(TypedefX->getUnderlyingType(),
  5680. TypedefY->getUnderlyingType());
  5681. // Must have the same kind.
  5682. if (X->getKind() != Y->getKind())
  5683. return false;
  5684. // Objective-C classes and protocols with the same name always match.
  5685. if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
  5686. return true;
  5687. if (isa<ClassTemplateSpecializationDecl>(X)) {
  5688. // No need to handle these here: we merge them when adding them to the
  5689. // template.
  5690. return false;
  5691. }
  5692. // Compatible tags match.
  5693. if (const auto *TagX = dyn_cast<TagDecl>(X)) {
  5694. const auto *TagY = cast<TagDecl>(Y);
  5695. return (TagX->getTagKind() == TagY->getTagKind()) ||
  5696. ((TagX->getTagKind() == TTK_Struct ||
  5697. TagX->getTagKind() == TTK_Class ||
  5698. TagX->getTagKind() == TTK_Interface) &&
  5699. (TagY->getTagKind() == TTK_Struct ||
  5700. TagY->getTagKind() == TTK_Class ||
  5701. TagY->getTagKind() == TTK_Interface));
  5702. }
  5703. // Functions with the same type and linkage match.
  5704. // FIXME: This needs to cope with merging of prototyped/non-prototyped
  5705. // functions, etc.
  5706. if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
  5707. const auto *FuncY = cast<FunctionDecl>(Y);
  5708. if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
  5709. const auto *CtorY = cast<CXXConstructorDecl>(Y);
  5710. if (CtorX->getInheritedConstructor() &&
  5711. !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
  5712. CtorY->getInheritedConstructor().getConstructor()))
  5713. return false;
  5714. }
  5715. if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
  5716. return false;
  5717. // Multiversioned functions with different feature strings are represented
  5718. // as separate declarations.
  5719. if (FuncX->isMultiVersion()) {
  5720. const auto *TAX = FuncX->getAttr<TargetAttr>();
  5721. const auto *TAY = FuncY->getAttr<TargetAttr>();
  5722. assert(TAX && TAY && "Multiversion Function without target attribute");
  5723. if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
  5724. return false;
  5725. }
  5726. if (!isSameConstraintExpr(FuncX->getTrailingRequiresClause(),
  5727. FuncY->getTrailingRequiresClause()))
  5728. return false;
  5729. // Constrained friends are different in certain cases, see: [temp.friend]p9.
  5730. if (FriendsDifferByConstraints(FuncX, FuncY))
  5731. return false;
  5732. auto GetTypeAsWritten = [](const FunctionDecl *FD) {
  5733. // Map to the first declaration that we've already merged into this one.
  5734. // The TSI of redeclarations might not match (due to calling conventions
  5735. // being inherited onto the type but not the TSI), but the TSI type of
  5736. // the first declaration of the function should match across modules.
  5737. FD = FD->getCanonicalDecl();
  5738. return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
  5739. : FD->getType();
  5740. };
  5741. QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
  5742. if (!hasSameType(XT, YT)) {
  5743. // We can get functions with different types on the redecl chain in C++17
  5744. // if they have differing exception specifications and at least one of
  5745. // the excpetion specs is unresolved.
  5746. auto *XFPT = XT->getAs<FunctionProtoType>();
  5747. auto *YFPT = YT->getAs<FunctionProtoType>();
  5748. if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
  5749. (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
  5750. isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
  5751. hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
  5752. return true;
  5753. return false;
  5754. }
  5755. return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
  5756. hasSameOverloadableAttrs(FuncX, FuncY);
  5757. }
  5758. // Variables with the same type and linkage match.
  5759. if (const auto *VarX = dyn_cast<VarDecl>(X)) {
  5760. const auto *VarY = cast<VarDecl>(Y);
  5761. if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
  5762. if (hasSameType(VarX->getType(), VarY->getType()))
  5763. return true;
  5764. // We can get decls with different types on the redecl chain. Eg.
  5765. // template <typename T> struct S { static T Var[]; }; // #1
  5766. // template <typename T> T S<T>::Var[sizeof(T)]; // #2
  5767. // Only? happens when completing an incomplete array type. In this case
  5768. // when comparing #1 and #2 we should go through their element type.
  5769. const ArrayType *VarXTy = getAsArrayType(VarX->getType());
  5770. const ArrayType *VarYTy = getAsArrayType(VarY->getType());
  5771. if (!VarXTy || !VarYTy)
  5772. return false;
  5773. if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
  5774. return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
  5775. }
  5776. return false;
  5777. }
  5778. // Namespaces with the same name and inlinedness match.
  5779. if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
  5780. const auto *NamespaceY = cast<NamespaceDecl>(Y);
  5781. return NamespaceX->isInline() == NamespaceY->isInline();
  5782. }
  5783. // Identical template names and kinds match if their template parameter lists
  5784. // and patterns match.
  5785. if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
  5786. const auto *TemplateY = cast<TemplateDecl>(Y);
  5787. // ConceptDecl wouldn't be the same if their constraint expression differs.
  5788. if (const auto *ConceptX = dyn_cast<ConceptDecl>(X)) {
  5789. const auto *ConceptY = cast<ConceptDecl>(Y);
  5790. const Expr *XCE = ConceptX->getConstraintExpr();
  5791. const Expr *YCE = ConceptY->getConstraintExpr();
  5792. assert(XCE && YCE && "ConceptDecl without constraint expression?");
  5793. llvm::FoldingSetNodeID XID, YID;
  5794. XCE->Profile(XID, *this, /*Canonical=*/true);
  5795. YCE->Profile(YID, *this, /*Canonical=*/true);
  5796. if (XID != YID)
  5797. return false;
  5798. }
  5799. return isSameEntity(TemplateX->getTemplatedDecl(),
  5800. TemplateY->getTemplatedDecl()) &&
  5801. isSameTemplateParameterList(TemplateX->getTemplateParameters(),
  5802. TemplateY->getTemplateParameters());
  5803. }
  5804. // Fields with the same name and the same type match.
  5805. if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
  5806. const auto *FDY = cast<FieldDecl>(Y);
  5807. // FIXME: Also check the bitwidth is odr-equivalent, if any.
  5808. return hasSameType(FDX->getType(), FDY->getType());
  5809. }
  5810. // Indirect fields with the same target field match.
  5811. if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
  5812. const auto *IFDY = cast<IndirectFieldDecl>(Y);
  5813. return IFDX->getAnonField()->getCanonicalDecl() ==
  5814. IFDY->getAnonField()->getCanonicalDecl();
  5815. }
  5816. // Enumerators with the same name match.
  5817. if (isa<EnumConstantDecl>(X))
  5818. // FIXME: Also check the value is odr-equivalent.
  5819. return true;
  5820. // Using shadow declarations with the same target match.
  5821. if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
  5822. const auto *USY = cast<UsingShadowDecl>(Y);
  5823. return USX->getTargetDecl() == USY->getTargetDecl();
  5824. }
  5825. // Using declarations with the same qualifier match. (We already know that
  5826. // the name matches.)
  5827. if (const auto *UX = dyn_cast<UsingDecl>(X)) {
  5828. const auto *UY = cast<UsingDecl>(Y);
  5829. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  5830. UX->hasTypename() == UY->hasTypename() &&
  5831. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  5832. }
  5833. if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
  5834. const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
  5835. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  5836. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  5837. }
  5838. if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
  5839. return isSameQualifier(
  5840. UX->getQualifier(),
  5841. cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
  5842. }
  5843. // Using-pack declarations are only created by instantiation, and match if
  5844. // they're instantiated from matching UnresolvedUsing...Decls.
  5845. if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
  5846. return declaresSameEntity(
  5847. UX->getInstantiatedFromUsingDecl(),
  5848. cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
  5849. }
  5850. // Namespace alias definitions with the same target match.
  5851. if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
  5852. const auto *NAY = cast<NamespaceAliasDecl>(Y);
  5853. return NAX->getNamespace()->Equals(NAY->getNamespace());
  5854. }
  5855. return false;
  5856. }
  5857. TemplateArgument
  5858. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  5859. switch (Arg.getKind()) {
  5860. case TemplateArgument::Null:
  5861. return Arg;
  5862. case TemplateArgument::Expression:
  5863. return Arg;
  5864. case TemplateArgument::Declaration: {
  5865. auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  5866. return TemplateArgument(D, getCanonicalType(Arg.getParamTypeForDecl()));
  5867. }
  5868. case TemplateArgument::NullPtr:
  5869. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  5870. /*isNullPtr*/true);
  5871. case TemplateArgument::Template:
  5872. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  5873. case TemplateArgument::TemplateExpansion:
  5874. return TemplateArgument(getCanonicalTemplateName(
  5875. Arg.getAsTemplateOrTemplatePattern()),
  5876. Arg.getNumTemplateExpansions());
  5877. case TemplateArgument::Integral:
  5878. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  5879. case TemplateArgument::Type:
  5880. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  5881. case TemplateArgument::Pack: {
  5882. bool AnyNonCanonArgs = false;
  5883. auto CanonArgs = ::getCanonicalTemplateArguments(
  5884. *this, Arg.pack_elements(), AnyNonCanonArgs);
  5885. if (!AnyNonCanonArgs)
  5886. return Arg;
  5887. return TemplateArgument::CreatePackCopy(const_cast<ASTContext &>(*this),
  5888. CanonArgs);
  5889. }
  5890. }
  5891. // Silence GCC warning
  5892. llvm_unreachable("Unhandled template argument kind");
  5893. }
  5894. NestedNameSpecifier *
  5895. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  5896. if (!NNS)
  5897. return nullptr;
  5898. switch (NNS->getKind()) {
  5899. case NestedNameSpecifier::Identifier:
  5900. // Canonicalize the prefix but keep the identifier the same.
  5901. return NestedNameSpecifier::Create(*this,
  5902. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  5903. NNS->getAsIdentifier());
  5904. case NestedNameSpecifier::Namespace:
  5905. // A namespace is canonical; build a nested-name-specifier with
  5906. // this namespace and no prefix.
  5907. return NestedNameSpecifier::Create(*this, nullptr,
  5908. NNS->getAsNamespace()->getOriginalNamespace());
  5909. case NestedNameSpecifier::NamespaceAlias:
  5910. // A namespace is canonical; build a nested-name-specifier with
  5911. // this namespace and no prefix.
  5912. return NestedNameSpecifier::Create(*this, nullptr,
  5913. NNS->getAsNamespaceAlias()->getNamespace()
  5914. ->getOriginalNamespace());
  5915. // The difference between TypeSpec and TypeSpecWithTemplate is that the
  5916. // latter will have the 'template' keyword when printed.
  5917. case NestedNameSpecifier::TypeSpec:
  5918. case NestedNameSpecifier::TypeSpecWithTemplate: {
  5919. const Type *T = getCanonicalType(NNS->getAsType());
  5920. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  5921. // break it apart into its prefix and identifier, then reconsititute those
  5922. // as the canonical nested-name-specifier. This is required to canonicalize
  5923. // a dependent nested-name-specifier involving typedefs of dependent-name
  5924. // types, e.g.,
  5925. // typedef typename T::type T1;
  5926. // typedef typename T1::type T2;
  5927. if (const auto *DNT = T->getAs<DependentNameType>())
  5928. return NestedNameSpecifier::Create(
  5929. *this, DNT->getQualifier(),
  5930. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  5931. if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
  5932. return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
  5933. const_cast<Type *>(T));
  5934. // TODO: Set 'Template' parameter to true for other template types.
  5935. return NestedNameSpecifier::Create(*this, nullptr, false,
  5936. const_cast<Type *>(T));
  5937. }
  5938. case NestedNameSpecifier::Global:
  5939. case NestedNameSpecifier::Super:
  5940. // The global specifier and __super specifer are canonical and unique.
  5941. return NNS;
  5942. }
  5943. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  5944. }
  5945. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  5946. // Handle the non-qualified case efficiently.
  5947. if (!T.hasLocalQualifiers()) {
  5948. // Handle the common positive case fast.
  5949. if (const auto *AT = dyn_cast<ArrayType>(T))
  5950. return AT;
  5951. }
  5952. // Handle the common negative case fast.
  5953. if (!isa<ArrayType>(T.getCanonicalType()))
  5954. return nullptr;
  5955. // Apply any qualifiers from the array type to the element type. This
  5956. // implements C99 6.7.3p8: "If the specification of an array type includes
  5957. // any type qualifiers, the element type is so qualified, not the array type."
  5958. // If we get here, we either have type qualifiers on the type, or we have
  5959. // sugar such as a typedef in the way. If we have type qualifiers on the type
  5960. // we must propagate them down into the element type.
  5961. SplitQualType split = T.getSplitDesugaredType();
  5962. Qualifiers qs = split.Quals;
  5963. // If we have a simple case, just return now.
  5964. const auto *ATy = dyn_cast<ArrayType>(split.Ty);
  5965. if (!ATy || qs.empty())
  5966. return ATy;
  5967. // Otherwise, we have an array and we have qualifiers on it. Push the
  5968. // qualifiers into the array element type and return a new array type.
  5969. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  5970. if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
  5971. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  5972. CAT->getSizeExpr(),
  5973. CAT->getSizeModifier(),
  5974. CAT->getIndexTypeCVRQualifiers()));
  5975. if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
  5976. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  5977. IAT->getSizeModifier(),
  5978. IAT->getIndexTypeCVRQualifiers()));
  5979. if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
  5980. return cast<ArrayType>(
  5981. getDependentSizedArrayType(NewEltTy,
  5982. DSAT->getSizeExpr(),
  5983. DSAT->getSizeModifier(),
  5984. DSAT->getIndexTypeCVRQualifiers(),
  5985. DSAT->getBracketsRange()));
  5986. const auto *VAT = cast<VariableArrayType>(ATy);
  5987. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  5988. VAT->getSizeExpr(),
  5989. VAT->getSizeModifier(),
  5990. VAT->getIndexTypeCVRQualifiers(),
  5991. VAT->getBracketsRange()));
  5992. }
  5993. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  5994. if (T->isArrayType() || T->isFunctionType())
  5995. return getDecayedType(T);
  5996. return T;
  5997. }
  5998. QualType ASTContext::getSignatureParameterType(QualType T) const {
  5999. T = getVariableArrayDecayedType(T);
  6000. T = getAdjustedParameterType(T);
  6001. return T.getUnqualifiedType();
  6002. }
  6003. QualType ASTContext::getExceptionObjectType(QualType T) const {
  6004. // C++ [except.throw]p3:
  6005. // A throw-expression initializes a temporary object, called the exception
  6006. // object, the type of which is determined by removing any top-level
  6007. // cv-qualifiers from the static type of the operand of throw and adjusting
  6008. // the type from "array of T" or "function returning T" to "pointer to T"
  6009. // or "pointer to function returning T", [...]
  6010. T = getVariableArrayDecayedType(T);
  6011. if (T->isArrayType() || T->isFunctionType())
  6012. T = getDecayedType(T);
  6013. return T.getUnqualifiedType();
  6014. }
  6015. /// getArrayDecayedType - Return the properly qualified result of decaying the
  6016. /// specified array type to a pointer. This operation is non-trivial when
  6017. /// handling typedefs etc. The canonical type of "T" must be an array type,
  6018. /// this returns a pointer to a properly qualified element of the array.
  6019. ///
  6020. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  6021. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  6022. // Get the element type with 'getAsArrayType' so that we don't lose any
  6023. // typedefs in the element type of the array. This also handles propagation
  6024. // of type qualifiers from the array type into the element type if present
  6025. // (C99 6.7.3p8).
  6026. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  6027. assert(PrettyArrayType && "Not an array type!");
  6028. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  6029. // int x[restrict 4] -> int *restrict
  6030. QualType Result = getQualifiedType(PtrTy,
  6031. PrettyArrayType->getIndexTypeQualifiers());
  6032. // int x[_Nullable] -> int * _Nullable
  6033. if (auto Nullability = Ty->getNullability()) {
  6034. Result = const_cast<ASTContext *>(this)->getAttributedType(
  6035. AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
  6036. }
  6037. return Result;
  6038. }
  6039. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  6040. return getBaseElementType(array->getElementType());
  6041. }
  6042. QualType ASTContext::getBaseElementType(QualType type) const {
  6043. Qualifiers qs;
  6044. while (true) {
  6045. SplitQualType split = type.getSplitDesugaredType();
  6046. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  6047. if (!array) break;
  6048. type = array->getElementType();
  6049. qs.addConsistentQualifiers(split.Quals);
  6050. }
  6051. return getQualifiedType(type, qs);
  6052. }
  6053. /// getConstantArrayElementCount - Returns number of constant array elements.
  6054. uint64_t
  6055. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  6056. uint64_t ElementCount = 1;
  6057. do {
  6058. ElementCount *= CA->getSize().getZExtValue();
  6059. CA = dyn_cast_or_null<ConstantArrayType>(
  6060. CA->getElementType()->getAsArrayTypeUnsafe());
  6061. } while (CA);
  6062. return ElementCount;
  6063. }
  6064. uint64_t ASTContext::getArrayInitLoopExprElementCount(
  6065. const ArrayInitLoopExpr *AILE) const {
  6066. if (!AILE)
  6067. return 0;
  6068. uint64_t ElementCount = 1;
  6069. do {
  6070. ElementCount *= AILE->getArraySize().getZExtValue();
  6071. AILE = dyn_cast<ArrayInitLoopExpr>(AILE->getSubExpr());
  6072. } while (AILE);
  6073. return ElementCount;
  6074. }
  6075. /// getFloatingRank - Return a relative rank for floating point types.
  6076. /// This routine will assert if passed a built-in type that isn't a float.
  6077. static FloatingRank getFloatingRank(QualType T) {
  6078. if (const auto *CT = T->getAs<ComplexType>())
  6079. return getFloatingRank(CT->getElementType());
  6080. switch (T->castAs<BuiltinType>()->getKind()) {
  6081. default: llvm_unreachable("getFloatingRank(): not a floating type");
  6082. case BuiltinType::Float16: return Float16Rank;
  6083. case BuiltinType::Half: return HalfRank;
  6084. case BuiltinType::Float: return FloatRank;
  6085. case BuiltinType::Double: return DoubleRank;
  6086. case BuiltinType::LongDouble: return LongDoubleRank;
  6087. case BuiltinType::Float128: return Float128Rank;
  6088. case BuiltinType::BFloat16: return BFloat16Rank;
  6089. case BuiltinType::Ibm128: return Ibm128Rank;
  6090. }
  6091. }
  6092. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  6093. /// point types, ignoring the domain of the type (i.e. 'double' ==
  6094. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  6095. /// LHS < RHS, return -1.
  6096. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  6097. FloatingRank LHSR = getFloatingRank(LHS);
  6098. FloatingRank RHSR = getFloatingRank(RHS);
  6099. if (LHSR == RHSR)
  6100. return 0;
  6101. if (LHSR > RHSR)
  6102. return 1;
  6103. return -1;
  6104. }
  6105. int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
  6106. if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
  6107. return 0;
  6108. return getFloatingTypeOrder(LHS, RHS);
  6109. }
  6110. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  6111. /// routine will assert if passed a built-in type that isn't an integer or enum,
  6112. /// or if it is not canonicalized.
  6113. unsigned ASTContext::getIntegerRank(const Type *T) const {
  6114. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  6115. // Results in this 'losing' to any type of the same size, but winning if
  6116. // larger.
  6117. if (const auto *EIT = dyn_cast<BitIntType>(T))
  6118. return 0 + (EIT->getNumBits() << 3);
  6119. switch (cast<BuiltinType>(T)->getKind()) {
  6120. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  6121. case BuiltinType::Bool:
  6122. return 1 + (getIntWidth(BoolTy) << 3);
  6123. case BuiltinType::Char_S:
  6124. case BuiltinType::Char_U:
  6125. case BuiltinType::SChar:
  6126. case BuiltinType::UChar:
  6127. return 2 + (getIntWidth(CharTy) << 3);
  6128. case BuiltinType::Short:
  6129. case BuiltinType::UShort:
  6130. return 3 + (getIntWidth(ShortTy) << 3);
  6131. case BuiltinType::Int:
  6132. case BuiltinType::UInt:
  6133. return 4 + (getIntWidth(IntTy) << 3);
  6134. case BuiltinType::Long:
  6135. case BuiltinType::ULong:
  6136. return 5 + (getIntWidth(LongTy) << 3);
  6137. case BuiltinType::LongLong:
  6138. case BuiltinType::ULongLong:
  6139. return 6 + (getIntWidth(LongLongTy) << 3);
  6140. case BuiltinType::Int128:
  6141. case BuiltinType::UInt128:
  6142. return 7 + (getIntWidth(Int128Ty) << 3);
  6143. // "The ranks of char8_t, char16_t, char32_t, and wchar_t equal the ranks of
  6144. // their underlying types" [c++20 conv.rank]
  6145. case BuiltinType::Char8:
  6146. return getIntegerRank(UnsignedCharTy.getTypePtr());
  6147. case BuiltinType::Char16:
  6148. return getIntegerRank(
  6149. getFromTargetType(Target->getChar16Type()).getTypePtr());
  6150. case BuiltinType::Char32:
  6151. return getIntegerRank(
  6152. getFromTargetType(Target->getChar32Type()).getTypePtr());
  6153. case BuiltinType::WChar_S:
  6154. case BuiltinType::WChar_U:
  6155. return getIntegerRank(
  6156. getFromTargetType(Target->getWCharType()).getTypePtr());
  6157. }
  6158. }
  6159. /// Whether this is a promotable bitfield reference according
  6160. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  6161. ///
  6162. /// \returns the type this bit-field will promote to, or NULL if no
  6163. /// promotion occurs.
  6164. QualType ASTContext::isPromotableBitField(Expr *E) const {
  6165. if (E->isTypeDependent() || E->isValueDependent())
  6166. return {};
  6167. // C++ [conv.prom]p5:
  6168. // If the bit-field has an enumerated type, it is treated as any other
  6169. // value of that type for promotion purposes.
  6170. if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
  6171. return {};
  6172. // FIXME: We should not do this unless E->refersToBitField() is true. This
  6173. // matters in C where getSourceBitField() will find bit-fields for various
  6174. // cases where the source expression is not a bit-field designator.
  6175. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  6176. if (!Field)
  6177. return {};
  6178. QualType FT = Field->getType();
  6179. uint64_t BitWidth = Field->getBitWidthValue(*this);
  6180. uint64_t IntSize = getTypeSize(IntTy);
  6181. // C++ [conv.prom]p5:
  6182. // A prvalue for an integral bit-field can be converted to a prvalue of type
  6183. // int if int can represent all the values of the bit-field; otherwise, it
  6184. // can be converted to unsigned int if unsigned int can represent all the
  6185. // values of the bit-field. If the bit-field is larger yet, no integral
  6186. // promotion applies to it.
  6187. // C11 6.3.1.1/2:
  6188. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  6189. // If an int can represent all values of the original type (as restricted by
  6190. // the width, for a bit-field), the value is converted to an int; otherwise,
  6191. // it is converted to an unsigned int.
  6192. //
  6193. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  6194. // We perform that promotion here to match GCC and C++.
  6195. // FIXME: C does not permit promotion of an enum bit-field whose rank is
  6196. // greater than that of 'int'. We perform that promotion to match GCC.
  6197. if (BitWidth < IntSize)
  6198. return IntTy;
  6199. if (BitWidth == IntSize)
  6200. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  6201. // Bit-fields wider than int are not subject to promotions, and therefore act
  6202. // like the base type. GCC has some weird bugs in this area that we
  6203. // deliberately do not follow (GCC follows a pre-standard resolution to
  6204. // C's DR315 which treats bit-width as being part of the type, and this leaks
  6205. // into their semantics in some cases).
  6206. return {};
  6207. }
  6208. /// getPromotedIntegerType - Returns the type that Promotable will
  6209. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  6210. /// integer type.
  6211. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  6212. assert(!Promotable.isNull());
  6213. assert(isPromotableIntegerType(Promotable));
  6214. if (const auto *ET = Promotable->getAs<EnumType>())
  6215. return ET->getDecl()->getPromotionType();
  6216. if (const auto *BT = Promotable->getAs<BuiltinType>()) {
  6217. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  6218. // (3.9.1) can be converted to a prvalue of the first of the following
  6219. // types that can represent all the values of its underlying type:
  6220. // int, unsigned int, long int, unsigned long int, long long int, or
  6221. // unsigned long long int [...]
  6222. // FIXME: Is there some better way to compute this?
  6223. if (BT->getKind() == BuiltinType::WChar_S ||
  6224. BT->getKind() == BuiltinType::WChar_U ||
  6225. BT->getKind() == BuiltinType::Char8 ||
  6226. BT->getKind() == BuiltinType::Char16 ||
  6227. BT->getKind() == BuiltinType::Char32) {
  6228. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  6229. uint64_t FromSize = getTypeSize(BT);
  6230. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  6231. LongLongTy, UnsignedLongLongTy };
  6232. for (const auto &PT : PromoteTypes) {
  6233. uint64_t ToSize = getTypeSize(PT);
  6234. if (FromSize < ToSize ||
  6235. (FromSize == ToSize && FromIsSigned == PT->isSignedIntegerType()))
  6236. return PT;
  6237. }
  6238. llvm_unreachable("char type should fit into long long");
  6239. }
  6240. }
  6241. // At this point, we should have a signed or unsigned integer type.
  6242. if (Promotable->isSignedIntegerType())
  6243. return IntTy;
  6244. uint64_t PromotableSize = getIntWidth(Promotable);
  6245. uint64_t IntSize = getIntWidth(IntTy);
  6246. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  6247. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  6248. }
  6249. /// Recurses in pointer/array types until it finds an objc retainable
  6250. /// type and returns its ownership.
  6251. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  6252. while (!T.isNull()) {
  6253. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  6254. return T.getObjCLifetime();
  6255. if (T->isArrayType())
  6256. T = getBaseElementType(T);
  6257. else if (const auto *PT = T->getAs<PointerType>())
  6258. T = PT->getPointeeType();
  6259. else if (const auto *RT = T->getAs<ReferenceType>())
  6260. T = RT->getPointeeType();
  6261. else
  6262. break;
  6263. }
  6264. return Qualifiers::OCL_None;
  6265. }
  6266. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  6267. // Incomplete enum types are not treated as integer types.
  6268. // FIXME: In C++, enum types are never integer types.
  6269. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  6270. return ET->getDecl()->getIntegerType().getTypePtr();
  6271. return nullptr;
  6272. }
  6273. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  6274. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  6275. /// LHS < RHS, return -1.
  6276. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  6277. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  6278. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  6279. // Unwrap enums to their underlying type.
  6280. if (const auto *ET = dyn_cast<EnumType>(LHSC))
  6281. LHSC = getIntegerTypeForEnum(ET);
  6282. if (const auto *ET = dyn_cast<EnumType>(RHSC))
  6283. RHSC = getIntegerTypeForEnum(ET);
  6284. if (LHSC == RHSC) return 0;
  6285. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  6286. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  6287. unsigned LHSRank = getIntegerRank(LHSC);
  6288. unsigned RHSRank = getIntegerRank(RHSC);
  6289. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  6290. if (LHSRank == RHSRank) return 0;
  6291. return LHSRank > RHSRank ? 1 : -1;
  6292. }
  6293. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  6294. if (LHSUnsigned) {
  6295. // If the unsigned [LHS] type is larger, return it.
  6296. if (LHSRank >= RHSRank)
  6297. return 1;
  6298. // If the signed type can represent all values of the unsigned type, it
  6299. // wins. Because we are dealing with 2's complement and types that are
  6300. // powers of two larger than each other, this is always safe.
  6301. return -1;
  6302. }
  6303. // If the unsigned [RHS] type is larger, return it.
  6304. if (RHSRank >= LHSRank)
  6305. return -1;
  6306. // If the signed type can represent all values of the unsigned type, it
  6307. // wins. Because we are dealing with 2's complement and types that are
  6308. // powers of two larger than each other, this is always safe.
  6309. return 1;
  6310. }
  6311. TypedefDecl *ASTContext::getCFConstantStringDecl() const {
  6312. if (CFConstantStringTypeDecl)
  6313. return CFConstantStringTypeDecl;
  6314. assert(!CFConstantStringTagDecl &&
  6315. "tag and typedef should be initialized together");
  6316. CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
  6317. CFConstantStringTagDecl->startDefinition();
  6318. struct {
  6319. QualType Type;
  6320. const char *Name;
  6321. } Fields[5];
  6322. unsigned Count = 0;
  6323. /// Objective-C ABI
  6324. ///
  6325. /// typedef struct __NSConstantString_tag {
  6326. /// const int *isa;
  6327. /// int flags;
  6328. /// const char *str;
  6329. /// long length;
  6330. /// } __NSConstantString;
  6331. ///
  6332. /// Swift ABI (4.1, 4.2)
  6333. ///
  6334. /// typedef struct __NSConstantString_tag {
  6335. /// uintptr_t _cfisa;
  6336. /// uintptr_t _swift_rc;
  6337. /// _Atomic(uint64_t) _cfinfoa;
  6338. /// const char *_ptr;
  6339. /// uint32_t _length;
  6340. /// } __NSConstantString;
  6341. ///
  6342. /// Swift ABI (5.0)
  6343. ///
  6344. /// typedef struct __NSConstantString_tag {
  6345. /// uintptr_t _cfisa;
  6346. /// uintptr_t _swift_rc;
  6347. /// _Atomic(uint64_t) _cfinfoa;
  6348. /// const char *_ptr;
  6349. /// uintptr_t _length;
  6350. /// } __NSConstantString;
  6351. const auto CFRuntime = getLangOpts().CFRuntime;
  6352. if (static_cast<unsigned>(CFRuntime) <
  6353. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
  6354. Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
  6355. Fields[Count++] = { IntTy, "flags" };
  6356. Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
  6357. Fields[Count++] = { LongTy, "length" };
  6358. } else {
  6359. Fields[Count++] = { getUIntPtrType(), "_cfisa" };
  6360. Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
  6361. Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
  6362. Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
  6363. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  6364. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  6365. Fields[Count++] = { IntTy, "_ptr" };
  6366. else
  6367. Fields[Count++] = { getUIntPtrType(), "_ptr" };
  6368. }
  6369. // Create fields
  6370. for (unsigned i = 0; i < Count; ++i) {
  6371. FieldDecl *Field =
  6372. FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
  6373. SourceLocation(), &Idents.get(Fields[i].Name),
  6374. Fields[i].Type, /*TInfo=*/nullptr,
  6375. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  6376. Field->setAccess(AS_public);
  6377. CFConstantStringTagDecl->addDecl(Field);
  6378. }
  6379. CFConstantStringTagDecl->completeDefinition();
  6380. // This type is designed to be compatible with NSConstantString, but cannot
  6381. // use the same name, since NSConstantString is an interface.
  6382. auto tagType = getTagDeclType(CFConstantStringTagDecl);
  6383. CFConstantStringTypeDecl =
  6384. buildImplicitTypedef(tagType, "__NSConstantString");
  6385. return CFConstantStringTypeDecl;
  6386. }
  6387. RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
  6388. if (!CFConstantStringTagDecl)
  6389. getCFConstantStringDecl(); // Build the tag and the typedef.
  6390. return CFConstantStringTagDecl;
  6391. }
  6392. // getCFConstantStringType - Return the type used for constant CFStrings.
  6393. QualType ASTContext::getCFConstantStringType() const {
  6394. return getTypedefType(getCFConstantStringDecl());
  6395. }
  6396. QualType ASTContext::getObjCSuperType() const {
  6397. if (ObjCSuperType.isNull()) {
  6398. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  6399. getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
  6400. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  6401. }
  6402. return ObjCSuperType;
  6403. }
  6404. void ASTContext::setCFConstantStringType(QualType T) {
  6405. const auto *TD = T->castAs<TypedefType>();
  6406. CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
  6407. const auto *TagType =
  6408. CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
  6409. CFConstantStringTagDecl = TagType->getDecl();
  6410. }
  6411. QualType ASTContext::getBlockDescriptorType() const {
  6412. if (BlockDescriptorType)
  6413. return getTagDeclType(BlockDescriptorType);
  6414. RecordDecl *RD;
  6415. // FIXME: Needs the FlagAppleBlock bit.
  6416. RD = buildImplicitRecord("__block_descriptor");
  6417. RD->startDefinition();
  6418. QualType FieldTypes[] = {
  6419. UnsignedLongTy,
  6420. UnsignedLongTy,
  6421. };
  6422. static const char *const FieldNames[] = {
  6423. "reserved",
  6424. "Size"
  6425. };
  6426. for (size_t i = 0; i < 2; ++i) {
  6427. FieldDecl *Field = FieldDecl::Create(
  6428. *this, RD, SourceLocation(), SourceLocation(),
  6429. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  6430. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  6431. Field->setAccess(AS_public);
  6432. RD->addDecl(Field);
  6433. }
  6434. RD->completeDefinition();
  6435. BlockDescriptorType = RD;
  6436. return getTagDeclType(BlockDescriptorType);
  6437. }
  6438. QualType ASTContext::getBlockDescriptorExtendedType() const {
  6439. if (BlockDescriptorExtendedType)
  6440. return getTagDeclType(BlockDescriptorExtendedType);
  6441. RecordDecl *RD;
  6442. // FIXME: Needs the FlagAppleBlock bit.
  6443. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  6444. RD->startDefinition();
  6445. QualType FieldTypes[] = {
  6446. UnsignedLongTy,
  6447. UnsignedLongTy,
  6448. getPointerType(VoidPtrTy),
  6449. getPointerType(VoidPtrTy)
  6450. };
  6451. static const char *const FieldNames[] = {
  6452. "reserved",
  6453. "Size",
  6454. "CopyFuncPtr",
  6455. "DestroyFuncPtr"
  6456. };
  6457. for (size_t i = 0; i < 4; ++i) {
  6458. FieldDecl *Field = FieldDecl::Create(
  6459. *this, RD, SourceLocation(), SourceLocation(),
  6460. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  6461. /*BitWidth=*/nullptr,
  6462. /*Mutable=*/false, ICIS_NoInit);
  6463. Field->setAccess(AS_public);
  6464. RD->addDecl(Field);
  6465. }
  6466. RD->completeDefinition();
  6467. BlockDescriptorExtendedType = RD;
  6468. return getTagDeclType(BlockDescriptorExtendedType);
  6469. }
  6470. OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
  6471. const auto *BT = dyn_cast<BuiltinType>(T);
  6472. if (!BT) {
  6473. if (isa<PipeType>(T))
  6474. return OCLTK_Pipe;
  6475. return OCLTK_Default;
  6476. }
  6477. switch (BT->getKind()) {
  6478. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6479. case BuiltinType::Id: \
  6480. return OCLTK_Image;
  6481. #include "clang/Basic/OpenCLImageTypes.def"
  6482. case BuiltinType::OCLClkEvent:
  6483. return OCLTK_ClkEvent;
  6484. case BuiltinType::OCLEvent:
  6485. return OCLTK_Event;
  6486. case BuiltinType::OCLQueue:
  6487. return OCLTK_Queue;
  6488. case BuiltinType::OCLReserveID:
  6489. return OCLTK_ReserveID;
  6490. case BuiltinType::OCLSampler:
  6491. return OCLTK_Sampler;
  6492. default:
  6493. return OCLTK_Default;
  6494. }
  6495. }
  6496. LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
  6497. return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
  6498. }
  6499. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  6500. /// requires copy/dispose. Note that this must match the logic
  6501. /// in buildByrefHelpers.
  6502. bool ASTContext::BlockRequiresCopying(QualType Ty,
  6503. const VarDecl *D) {
  6504. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  6505. const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
  6506. if (!copyExpr && record->hasTrivialDestructor()) return false;
  6507. return true;
  6508. }
  6509. // The block needs copy/destroy helpers if Ty is non-trivial to destructively
  6510. // move or destroy.
  6511. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
  6512. return true;
  6513. if (!Ty->isObjCRetainableType()) return false;
  6514. Qualifiers qs = Ty.getQualifiers();
  6515. // If we have lifetime, that dominates.
  6516. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  6517. switch (lifetime) {
  6518. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  6519. // These are just bits as far as the runtime is concerned.
  6520. case Qualifiers::OCL_ExplicitNone:
  6521. case Qualifiers::OCL_Autoreleasing:
  6522. return false;
  6523. // These cases should have been taken care of when checking the type's
  6524. // non-triviality.
  6525. case Qualifiers::OCL_Weak:
  6526. case Qualifiers::OCL_Strong:
  6527. llvm_unreachable("impossible");
  6528. }
  6529. llvm_unreachable("fell out of lifetime switch!");
  6530. }
  6531. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  6532. Ty->isObjCObjectPointerType());
  6533. }
  6534. bool ASTContext::getByrefLifetime(QualType Ty,
  6535. Qualifiers::ObjCLifetime &LifeTime,
  6536. bool &HasByrefExtendedLayout) const {
  6537. if (!getLangOpts().ObjC ||
  6538. getLangOpts().getGC() != LangOptions::NonGC)
  6539. return false;
  6540. HasByrefExtendedLayout = false;
  6541. if (Ty->isRecordType()) {
  6542. HasByrefExtendedLayout = true;
  6543. LifeTime = Qualifiers::OCL_None;
  6544. } else if ((LifeTime = Ty.getObjCLifetime())) {
  6545. // Honor the ARC qualifiers.
  6546. } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
  6547. // The MRR rule.
  6548. LifeTime = Qualifiers::OCL_ExplicitNone;
  6549. } else {
  6550. LifeTime = Qualifiers::OCL_None;
  6551. }
  6552. return true;
  6553. }
  6554. CanQualType ASTContext::getNSUIntegerType() const {
  6555. assert(Target && "Expected target to be initialized");
  6556. const llvm::Triple &T = Target->getTriple();
  6557. // Windows is LLP64 rather than LP64
  6558. if (T.isOSWindows() && T.isArch64Bit())
  6559. return UnsignedLongLongTy;
  6560. return UnsignedLongTy;
  6561. }
  6562. CanQualType ASTContext::getNSIntegerType() const {
  6563. assert(Target && "Expected target to be initialized");
  6564. const llvm::Triple &T = Target->getTriple();
  6565. // Windows is LLP64 rather than LP64
  6566. if (T.isOSWindows() && T.isArch64Bit())
  6567. return LongLongTy;
  6568. return LongTy;
  6569. }
  6570. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  6571. if (!ObjCInstanceTypeDecl)
  6572. ObjCInstanceTypeDecl =
  6573. buildImplicitTypedef(getObjCIdType(), "instancetype");
  6574. return ObjCInstanceTypeDecl;
  6575. }
  6576. // This returns true if a type has been typedefed to BOOL:
  6577. // typedef <type> BOOL;
  6578. static bool isTypeTypedefedAsBOOL(QualType T) {
  6579. if (const auto *TT = dyn_cast<TypedefType>(T))
  6580. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  6581. return II->isStr("BOOL");
  6582. return false;
  6583. }
  6584. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  6585. /// purpose.
  6586. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  6587. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  6588. return CharUnits::Zero();
  6589. CharUnits sz = getTypeSizeInChars(type);
  6590. // Make all integer and enum types at least as large as an int
  6591. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  6592. sz = std::max(sz, getTypeSizeInChars(IntTy));
  6593. // Treat arrays as pointers, since that's how they're passed in.
  6594. else if (type->isArrayType())
  6595. sz = getTypeSizeInChars(VoidPtrTy);
  6596. return sz;
  6597. }
  6598. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  6599. return getTargetInfo().getCXXABI().isMicrosoft() &&
  6600. VD->isStaticDataMember() &&
  6601. VD->getType()->isIntegralOrEnumerationType() &&
  6602. !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
  6603. }
  6604. ASTContext::InlineVariableDefinitionKind
  6605. ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
  6606. if (!VD->isInline())
  6607. return InlineVariableDefinitionKind::None;
  6608. // In almost all cases, it's a weak definition.
  6609. auto *First = VD->getFirstDecl();
  6610. if (First->isInlineSpecified() || !First->isStaticDataMember())
  6611. return InlineVariableDefinitionKind::Weak;
  6612. // If there's a file-context declaration in this translation unit, it's a
  6613. // non-discardable definition.
  6614. for (auto *D : VD->redecls())
  6615. if (D->getLexicalDeclContext()->isFileContext() &&
  6616. !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
  6617. return InlineVariableDefinitionKind::Strong;
  6618. // If we've not seen one yet, we don't know.
  6619. return InlineVariableDefinitionKind::WeakUnknown;
  6620. }
  6621. static std::string charUnitsToString(const CharUnits &CU) {
  6622. return llvm::itostr(CU.getQuantity());
  6623. }
  6624. /// getObjCEncodingForBlock - Return the encoded type for this block
  6625. /// declaration.
  6626. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  6627. std::string S;
  6628. const BlockDecl *Decl = Expr->getBlockDecl();
  6629. QualType BlockTy =
  6630. Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
  6631. QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
  6632. // Encode result type.
  6633. if (getLangOpts().EncodeExtendedBlockSig)
  6634. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
  6635. true /*Extended*/);
  6636. else
  6637. getObjCEncodingForType(BlockReturnTy, S);
  6638. // Compute size of all parameters.
  6639. // Start with computing size of a pointer in number of bytes.
  6640. // FIXME: There might(should) be a better way of doing this computation!
  6641. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  6642. CharUnits ParmOffset = PtrSize;
  6643. for (auto *PI : Decl->parameters()) {
  6644. QualType PType = PI->getType();
  6645. CharUnits sz = getObjCEncodingTypeSize(PType);
  6646. if (sz.isZero())
  6647. continue;
  6648. assert(sz.isPositive() && "BlockExpr - Incomplete param type");
  6649. ParmOffset += sz;
  6650. }
  6651. // Size of the argument frame
  6652. S += charUnitsToString(ParmOffset);
  6653. // Block pointer and offset.
  6654. S += "@?0";
  6655. // Argument types.
  6656. ParmOffset = PtrSize;
  6657. for (auto *PVDecl : Decl->parameters()) {
  6658. QualType PType = PVDecl->getOriginalType();
  6659. if (const auto *AT =
  6660. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6661. // Use array's original type only if it has known number of
  6662. // elements.
  6663. if (!isa<ConstantArrayType>(AT))
  6664. PType = PVDecl->getType();
  6665. } else if (PType->isFunctionType())
  6666. PType = PVDecl->getType();
  6667. if (getLangOpts().EncodeExtendedBlockSig)
  6668. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  6669. S, true /*Extended*/);
  6670. else
  6671. getObjCEncodingForType(PType, S);
  6672. S += charUnitsToString(ParmOffset);
  6673. ParmOffset += getObjCEncodingTypeSize(PType);
  6674. }
  6675. return S;
  6676. }
  6677. std::string
  6678. ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
  6679. std::string S;
  6680. // Encode result type.
  6681. getObjCEncodingForType(Decl->getReturnType(), S);
  6682. CharUnits ParmOffset;
  6683. // Compute size of all parameters.
  6684. for (auto *PI : Decl->parameters()) {
  6685. QualType PType = PI->getType();
  6686. CharUnits sz = getObjCEncodingTypeSize(PType);
  6687. if (sz.isZero())
  6688. continue;
  6689. assert(sz.isPositive() &&
  6690. "getObjCEncodingForFunctionDecl - Incomplete param type");
  6691. ParmOffset += sz;
  6692. }
  6693. S += charUnitsToString(ParmOffset);
  6694. ParmOffset = CharUnits::Zero();
  6695. // Argument types.
  6696. for (auto *PVDecl : Decl->parameters()) {
  6697. QualType PType = PVDecl->getOriginalType();
  6698. if (const auto *AT =
  6699. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6700. // Use array's original type only if it has known number of
  6701. // elements.
  6702. if (!isa<ConstantArrayType>(AT))
  6703. PType = PVDecl->getType();
  6704. } else if (PType->isFunctionType())
  6705. PType = PVDecl->getType();
  6706. getObjCEncodingForType(PType, S);
  6707. S += charUnitsToString(ParmOffset);
  6708. ParmOffset += getObjCEncodingTypeSize(PType);
  6709. }
  6710. return S;
  6711. }
  6712. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  6713. /// method parameter or return type. If Extended, include class names and
  6714. /// block object types.
  6715. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  6716. QualType T, std::string& S,
  6717. bool Extended) const {
  6718. // Encode type qualifier, 'in', 'inout', etc. for the parameter.
  6719. getObjCEncodingForTypeQualifier(QT, S);
  6720. // Encode parameter type.
  6721. ObjCEncOptions Options = ObjCEncOptions()
  6722. .setExpandPointedToStructures()
  6723. .setExpandStructures()
  6724. .setIsOutermostType();
  6725. if (Extended)
  6726. Options.setEncodeBlockParameters().setEncodeClassNames();
  6727. getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
  6728. }
  6729. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  6730. /// declaration.
  6731. std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  6732. bool Extended) const {
  6733. // FIXME: This is not very efficient.
  6734. // Encode return type.
  6735. std::string S;
  6736. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  6737. Decl->getReturnType(), S, Extended);
  6738. // Compute size of all parameters.
  6739. // Start with computing size of a pointer in number of bytes.
  6740. // FIXME: There might(should) be a better way of doing this computation!
  6741. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  6742. // The first two arguments (self and _cmd) are pointers; account for
  6743. // their size.
  6744. CharUnits ParmOffset = 2 * PtrSize;
  6745. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  6746. E = Decl->sel_param_end(); PI != E; ++PI) {
  6747. QualType PType = (*PI)->getType();
  6748. CharUnits sz = getObjCEncodingTypeSize(PType);
  6749. if (sz.isZero())
  6750. continue;
  6751. assert(sz.isPositive() &&
  6752. "getObjCEncodingForMethodDecl - Incomplete param type");
  6753. ParmOffset += sz;
  6754. }
  6755. S += charUnitsToString(ParmOffset);
  6756. S += "@0:";
  6757. S += charUnitsToString(PtrSize);
  6758. // Argument types.
  6759. ParmOffset = 2 * PtrSize;
  6760. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  6761. E = Decl->sel_param_end(); PI != E; ++PI) {
  6762. const ParmVarDecl *PVDecl = *PI;
  6763. QualType PType = PVDecl->getOriginalType();
  6764. if (const auto *AT =
  6765. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6766. // Use array's original type only if it has known number of
  6767. // elements.
  6768. if (!isa<ConstantArrayType>(AT))
  6769. PType = PVDecl->getType();
  6770. } else if (PType->isFunctionType())
  6771. PType = PVDecl->getType();
  6772. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  6773. PType, S, Extended);
  6774. S += charUnitsToString(ParmOffset);
  6775. ParmOffset += getObjCEncodingTypeSize(PType);
  6776. }
  6777. return S;
  6778. }
  6779. ObjCPropertyImplDecl *
  6780. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  6781. const ObjCPropertyDecl *PD,
  6782. const Decl *Container) const {
  6783. if (!Container)
  6784. return nullptr;
  6785. if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
  6786. for (auto *PID : CID->property_impls())
  6787. if (PID->getPropertyDecl() == PD)
  6788. return PID;
  6789. } else {
  6790. const auto *OID = cast<ObjCImplementationDecl>(Container);
  6791. for (auto *PID : OID->property_impls())
  6792. if (PID->getPropertyDecl() == PD)
  6793. return PID;
  6794. }
  6795. return nullptr;
  6796. }
  6797. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  6798. /// property declaration. If non-NULL, Container must be either an
  6799. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  6800. /// NULL when getting encodings for protocol properties.
  6801. /// Property attributes are stored as a comma-delimited C string. The simple
  6802. /// attributes readonly and bycopy are encoded as single characters. The
  6803. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  6804. /// encoded as single characters, followed by an identifier. Property types
  6805. /// are also encoded as a parametrized attribute. The characters used to encode
  6806. /// these attributes are defined by the following enumeration:
  6807. /// @code
  6808. /// enum PropertyAttributes {
  6809. /// kPropertyReadOnly = 'R', // property is read-only.
  6810. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  6811. /// kPropertyByref = '&', // property is a reference to the value last assigned
  6812. /// kPropertyDynamic = 'D', // property is dynamic
  6813. /// kPropertyGetter = 'G', // followed by getter selector name
  6814. /// kPropertySetter = 'S', // followed by setter selector name
  6815. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  6816. /// kPropertyType = 'T' // followed by old-style type encoding.
  6817. /// kPropertyWeak = 'W' // 'weak' property
  6818. /// kPropertyStrong = 'P' // property GC'able
  6819. /// kPropertyNonAtomic = 'N' // property non-atomic
  6820. /// };
  6821. /// @endcode
  6822. std::string
  6823. ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  6824. const Decl *Container) const {
  6825. // Collect information from the property implementation decl(s).
  6826. bool Dynamic = false;
  6827. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  6828. if (ObjCPropertyImplDecl *PropertyImpDecl =
  6829. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  6830. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6831. Dynamic = true;
  6832. else
  6833. SynthesizePID = PropertyImpDecl;
  6834. }
  6835. // FIXME: This is not very efficient.
  6836. std::string S = "T";
  6837. // Encode result type.
  6838. // GCC has some special rules regarding encoding of properties which
  6839. // closely resembles encoding of ivars.
  6840. getObjCEncodingForPropertyType(PD->getType(), S);
  6841. if (PD->isReadOnly()) {
  6842. S += ",R";
  6843. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
  6844. S += ",C";
  6845. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
  6846. S += ",&";
  6847. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
  6848. S += ",W";
  6849. } else {
  6850. switch (PD->getSetterKind()) {
  6851. case ObjCPropertyDecl::Assign: break;
  6852. case ObjCPropertyDecl::Copy: S += ",C"; break;
  6853. case ObjCPropertyDecl::Retain: S += ",&"; break;
  6854. case ObjCPropertyDecl::Weak: S += ",W"; break;
  6855. }
  6856. }
  6857. // It really isn't clear at all what this means, since properties
  6858. // are "dynamic by default".
  6859. if (Dynamic)
  6860. S += ",D";
  6861. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
  6862. S += ",N";
  6863. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
  6864. S += ",G";
  6865. S += PD->getGetterName().getAsString();
  6866. }
  6867. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
  6868. S += ",S";
  6869. S += PD->getSetterName().getAsString();
  6870. }
  6871. if (SynthesizePID) {
  6872. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  6873. S += ",V";
  6874. S += OID->getNameAsString();
  6875. }
  6876. // FIXME: OBJCGC: weak & strong
  6877. return S;
  6878. }
  6879. /// getLegacyIntegralTypeEncoding -
  6880. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  6881. /// 'l' or 'L' , but not always. For typedefs, we need to use
  6882. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  6883. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  6884. if (PointeeTy->getAs<TypedefType>()) {
  6885. if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
  6886. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  6887. PointeeTy = UnsignedIntTy;
  6888. else
  6889. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  6890. PointeeTy = IntTy;
  6891. }
  6892. }
  6893. }
  6894. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  6895. const FieldDecl *Field,
  6896. QualType *NotEncodedT) const {
  6897. // We follow the behavior of gcc, expanding structures which are
  6898. // directly pointed to, and expanding embedded structures. Note that
  6899. // these rules are sufficient to prevent recursive encoding of the
  6900. // same type.
  6901. getObjCEncodingForTypeImpl(T, S,
  6902. ObjCEncOptions()
  6903. .setExpandPointedToStructures()
  6904. .setExpandStructures()
  6905. .setIsOutermostType(),
  6906. Field, NotEncodedT);
  6907. }
  6908. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  6909. std::string& S) const {
  6910. // Encode result type.
  6911. // GCC has some special rules regarding encoding of properties which
  6912. // closely resembles encoding of ivars.
  6913. getObjCEncodingForTypeImpl(T, S,
  6914. ObjCEncOptions()
  6915. .setExpandPointedToStructures()
  6916. .setExpandStructures()
  6917. .setIsOutermostType()
  6918. .setEncodingProperty(),
  6919. /*Field=*/nullptr);
  6920. }
  6921. static char getObjCEncodingForPrimitiveType(const ASTContext *C,
  6922. const BuiltinType *BT) {
  6923. BuiltinType::Kind kind = BT->getKind();
  6924. switch (kind) {
  6925. case BuiltinType::Void: return 'v';
  6926. case BuiltinType::Bool: return 'B';
  6927. case BuiltinType::Char8:
  6928. case BuiltinType::Char_U:
  6929. case BuiltinType::UChar: return 'C';
  6930. case BuiltinType::Char16:
  6931. case BuiltinType::UShort: return 'S';
  6932. case BuiltinType::Char32:
  6933. case BuiltinType::UInt: return 'I';
  6934. case BuiltinType::ULong:
  6935. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  6936. case BuiltinType::UInt128: return 'T';
  6937. case BuiltinType::ULongLong: return 'Q';
  6938. case BuiltinType::Char_S:
  6939. case BuiltinType::SChar: return 'c';
  6940. case BuiltinType::Short: return 's';
  6941. case BuiltinType::WChar_S:
  6942. case BuiltinType::WChar_U:
  6943. case BuiltinType::Int: return 'i';
  6944. case BuiltinType::Long:
  6945. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  6946. case BuiltinType::LongLong: return 'q';
  6947. case BuiltinType::Int128: return 't';
  6948. case BuiltinType::Float: return 'f';
  6949. case BuiltinType::Double: return 'd';
  6950. case BuiltinType::LongDouble: return 'D';
  6951. case BuiltinType::NullPtr: return '*'; // like char*
  6952. case BuiltinType::BFloat16:
  6953. case BuiltinType::Float16:
  6954. case BuiltinType::Float128:
  6955. case BuiltinType::Ibm128:
  6956. case BuiltinType::Half:
  6957. case BuiltinType::ShortAccum:
  6958. case BuiltinType::Accum:
  6959. case BuiltinType::LongAccum:
  6960. case BuiltinType::UShortAccum:
  6961. case BuiltinType::UAccum:
  6962. case BuiltinType::ULongAccum:
  6963. case BuiltinType::ShortFract:
  6964. case BuiltinType::Fract:
  6965. case BuiltinType::LongFract:
  6966. case BuiltinType::UShortFract:
  6967. case BuiltinType::UFract:
  6968. case BuiltinType::ULongFract:
  6969. case BuiltinType::SatShortAccum:
  6970. case BuiltinType::SatAccum:
  6971. case BuiltinType::SatLongAccum:
  6972. case BuiltinType::SatUShortAccum:
  6973. case BuiltinType::SatUAccum:
  6974. case BuiltinType::SatULongAccum:
  6975. case BuiltinType::SatShortFract:
  6976. case BuiltinType::SatFract:
  6977. case BuiltinType::SatLongFract:
  6978. case BuiltinType::SatUShortFract:
  6979. case BuiltinType::SatUFract:
  6980. case BuiltinType::SatULongFract:
  6981. // FIXME: potentially need @encodes for these!
  6982. return ' ';
  6983. #define SVE_TYPE(Name, Id, SingletonId) \
  6984. case BuiltinType::Id:
  6985. #include "clang/Basic/AArch64SVEACLETypes.def"
  6986. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  6987. #include "clang/Basic/RISCVVTypes.def"
  6988. {
  6989. DiagnosticsEngine &Diags = C->getDiagnostics();
  6990. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  6991. "cannot yet @encode type %0");
  6992. Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
  6993. return ' ';
  6994. }
  6995. case BuiltinType::ObjCId:
  6996. case BuiltinType::ObjCClass:
  6997. case BuiltinType::ObjCSel:
  6998. llvm_unreachable("@encoding ObjC primitive type");
  6999. // OpenCL and placeholder types don't need @encodings.
  7000. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  7001. case BuiltinType::Id:
  7002. #include "clang/Basic/OpenCLImageTypes.def"
  7003. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  7004. case BuiltinType::Id:
  7005. #include "clang/Basic/OpenCLExtensionTypes.def"
  7006. case BuiltinType::OCLEvent:
  7007. case BuiltinType::OCLClkEvent:
  7008. case BuiltinType::OCLQueue:
  7009. case BuiltinType::OCLReserveID:
  7010. case BuiltinType::OCLSampler:
  7011. case BuiltinType::Dependent:
  7012. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  7013. case BuiltinType::Id:
  7014. #include "clang/Basic/PPCTypes.def"
  7015. #define BUILTIN_TYPE(KIND, ID)
  7016. #define PLACEHOLDER_TYPE(KIND, ID) \
  7017. case BuiltinType::KIND:
  7018. #include "clang/AST/BuiltinTypes.def"
  7019. llvm_unreachable("invalid builtin type for @encode");
  7020. }
  7021. llvm_unreachable("invalid BuiltinType::Kind value");
  7022. }
  7023. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  7024. EnumDecl *Enum = ET->getDecl();
  7025. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  7026. if (!Enum->isFixed())
  7027. return 'i';
  7028. // The encoding of a fixed enum type matches its fixed underlying type.
  7029. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  7030. return getObjCEncodingForPrimitiveType(C, BT);
  7031. }
  7032. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  7033. QualType T, const FieldDecl *FD) {
  7034. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  7035. S += 'b';
  7036. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  7037. // The GNU runtime requires more information; bitfields are encoded as b,
  7038. // then the offset (in bits) of the first element, then the type of the
  7039. // bitfield, then the size in bits. For example, in this structure:
  7040. //
  7041. // struct
  7042. // {
  7043. // int integer;
  7044. // int flags:2;
  7045. // };
  7046. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  7047. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  7048. // information is not especially sensible, but we're stuck with it for
  7049. // compatibility with GCC, although providing it breaks anything that
  7050. // actually uses runtime introspection and wants to work on both runtimes...
  7051. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  7052. uint64_t Offset;
  7053. if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
  7054. Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
  7055. IVD);
  7056. } else {
  7057. const RecordDecl *RD = FD->getParent();
  7058. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  7059. Offset = RL.getFieldOffset(FD->getFieldIndex());
  7060. }
  7061. S += llvm::utostr(Offset);
  7062. if (const auto *ET = T->getAs<EnumType>())
  7063. S += ObjCEncodingForEnumType(Ctx, ET);
  7064. else {
  7065. const auto *BT = T->castAs<BuiltinType>();
  7066. S += getObjCEncodingForPrimitiveType(Ctx, BT);
  7067. }
  7068. }
  7069. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  7070. }
  7071. // Helper function for determining whether the encoded type string would include
  7072. // a template specialization type.
  7073. static bool hasTemplateSpecializationInEncodedString(const Type *T,
  7074. bool VisitBasesAndFields) {
  7075. T = T->getBaseElementTypeUnsafe();
  7076. if (auto *PT = T->getAs<PointerType>())
  7077. return hasTemplateSpecializationInEncodedString(
  7078. PT->getPointeeType().getTypePtr(), false);
  7079. auto *CXXRD = T->getAsCXXRecordDecl();
  7080. if (!CXXRD)
  7081. return false;
  7082. if (isa<ClassTemplateSpecializationDecl>(CXXRD))
  7083. return true;
  7084. if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
  7085. return false;
  7086. for (auto B : CXXRD->bases())
  7087. if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
  7088. true))
  7089. return true;
  7090. for (auto *FD : CXXRD->fields())
  7091. if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
  7092. true))
  7093. return true;
  7094. return false;
  7095. }
  7096. // FIXME: Use SmallString for accumulating string.
  7097. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
  7098. const ObjCEncOptions Options,
  7099. const FieldDecl *FD,
  7100. QualType *NotEncodedT) const {
  7101. CanQualType CT = getCanonicalType(T);
  7102. switch (CT->getTypeClass()) {
  7103. case Type::Builtin:
  7104. case Type::Enum:
  7105. if (FD && FD->isBitField())
  7106. return EncodeBitField(this, S, T, FD);
  7107. if (const auto *BT = dyn_cast<BuiltinType>(CT))
  7108. S += getObjCEncodingForPrimitiveType(this, BT);
  7109. else
  7110. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  7111. return;
  7112. case Type::Complex:
  7113. S += 'j';
  7114. getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
  7115. ObjCEncOptions(),
  7116. /*Field=*/nullptr);
  7117. return;
  7118. case Type::Atomic:
  7119. S += 'A';
  7120. getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
  7121. ObjCEncOptions(),
  7122. /*Field=*/nullptr);
  7123. return;
  7124. // encoding for pointer or reference types.
  7125. case Type::Pointer:
  7126. case Type::LValueReference:
  7127. case Type::RValueReference: {
  7128. QualType PointeeTy;
  7129. if (isa<PointerType>(CT)) {
  7130. const auto *PT = T->castAs<PointerType>();
  7131. if (PT->isObjCSelType()) {
  7132. S += ':';
  7133. return;
  7134. }
  7135. PointeeTy = PT->getPointeeType();
  7136. } else {
  7137. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  7138. }
  7139. bool isReadOnly = false;
  7140. // For historical/compatibility reasons, the read-only qualifier of the
  7141. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  7142. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  7143. // Also, do not emit the 'r' for anything but the outermost type!
  7144. if (T->getAs<TypedefType>()) {
  7145. if (Options.IsOutermostType() && T.isConstQualified()) {
  7146. isReadOnly = true;
  7147. S += 'r';
  7148. }
  7149. } else if (Options.IsOutermostType()) {
  7150. QualType P = PointeeTy;
  7151. while (auto PT = P->getAs<PointerType>())
  7152. P = PT->getPointeeType();
  7153. if (P.isConstQualified()) {
  7154. isReadOnly = true;
  7155. S += 'r';
  7156. }
  7157. }
  7158. if (isReadOnly) {
  7159. // Another legacy compatibility encoding. Some ObjC qualifier and type
  7160. // combinations need to be rearranged.
  7161. // Rewrite "in const" from "nr" to "rn"
  7162. if (StringRef(S).endswith("nr"))
  7163. S.replace(S.end()-2, S.end(), "rn");
  7164. }
  7165. if (PointeeTy->isCharType()) {
  7166. // char pointer types should be encoded as '*' unless it is a
  7167. // type that has been typedef'd to 'BOOL'.
  7168. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  7169. S += '*';
  7170. return;
  7171. }
  7172. } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
  7173. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  7174. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  7175. S += '#';
  7176. return;
  7177. }
  7178. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  7179. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  7180. S += '@';
  7181. return;
  7182. }
  7183. // If the encoded string for the class includes template names, just emit
  7184. // "^v" for pointers to the class.
  7185. if (getLangOpts().CPlusPlus &&
  7186. (!getLangOpts().EncodeCXXClassTemplateSpec &&
  7187. hasTemplateSpecializationInEncodedString(
  7188. RTy, Options.ExpandPointedToStructures()))) {
  7189. S += "^v";
  7190. return;
  7191. }
  7192. // fall through...
  7193. }
  7194. S += '^';
  7195. getLegacyIntegralTypeEncoding(PointeeTy);
  7196. ObjCEncOptions NewOptions;
  7197. if (Options.ExpandPointedToStructures())
  7198. NewOptions.setExpandStructures();
  7199. getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
  7200. /*Field=*/nullptr, NotEncodedT);
  7201. return;
  7202. }
  7203. case Type::ConstantArray:
  7204. case Type::IncompleteArray:
  7205. case Type::VariableArray: {
  7206. const auto *AT = cast<ArrayType>(CT);
  7207. if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
  7208. // Incomplete arrays are encoded as a pointer to the array element.
  7209. S += '^';
  7210. getObjCEncodingForTypeImpl(
  7211. AT->getElementType(), S,
  7212. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
  7213. } else {
  7214. S += '[';
  7215. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7216. S += llvm::utostr(CAT->getSize().getZExtValue());
  7217. else {
  7218. //Variable length arrays are encoded as a regular array with 0 elements.
  7219. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  7220. "Unknown array type!");
  7221. S += '0';
  7222. }
  7223. getObjCEncodingForTypeImpl(
  7224. AT->getElementType(), S,
  7225. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
  7226. NotEncodedT);
  7227. S += ']';
  7228. }
  7229. return;
  7230. }
  7231. case Type::FunctionNoProto:
  7232. case Type::FunctionProto:
  7233. S += '?';
  7234. return;
  7235. case Type::Record: {
  7236. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  7237. S += RDecl->isUnion() ? '(' : '{';
  7238. // Anonymous structures print as '?'
  7239. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  7240. S += II->getName();
  7241. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  7242. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  7243. llvm::raw_string_ostream OS(S);
  7244. printTemplateArgumentList(OS, TemplateArgs.asArray(),
  7245. getPrintingPolicy());
  7246. }
  7247. } else {
  7248. S += '?';
  7249. }
  7250. if (Options.ExpandStructures()) {
  7251. S += '=';
  7252. if (!RDecl->isUnion()) {
  7253. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  7254. } else {
  7255. for (const auto *Field : RDecl->fields()) {
  7256. if (FD) {
  7257. S += '"';
  7258. S += Field->getNameAsString();
  7259. S += '"';
  7260. }
  7261. // Special case bit-fields.
  7262. if (Field->isBitField()) {
  7263. getObjCEncodingForTypeImpl(Field->getType(), S,
  7264. ObjCEncOptions().setExpandStructures(),
  7265. Field);
  7266. } else {
  7267. QualType qt = Field->getType();
  7268. getLegacyIntegralTypeEncoding(qt);
  7269. getObjCEncodingForTypeImpl(
  7270. qt, S,
  7271. ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
  7272. NotEncodedT);
  7273. }
  7274. }
  7275. }
  7276. }
  7277. S += RDecl->isUnion() ? ')' : '}';
  7278. return;
  7279. }
  7280. case Type::BlockPointer: {
  7281. const auto *BT = T->castAs<BlockPointerType>();
  7282. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  7283. if (Options.EncodeBlockParameters()) {
  7284. const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
  7285. S += '<';
  7286. // Block return type
  7287. getObjCEncodingForTypeImpl(FT->getReturnType(), S,
  7288. Options.forComponentType(), FD, NotEncodedT);
  7289. // Block self
  7290. S += "@?";
  7291. // Block parameters
  7292. if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
  7293. for (const auto &I : FPT->param_types())
  7294. getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
  7295. NotEncodedT);
  7296. }
  7297. S += '>';
  7298. }
  7299. return;
  7300. }
  7301. case Type::ObjCObject: {
  7302. // hack to match legacy encoding of *id and *Class
  7303. QualType Ty = getObjCObjectPointerType(CT);
  7304. if (Ty->isObjCIdType()) {
  7305. S += "{objc_object=}";
  7306. return;
  7307. }
  7308. else if (Ty->isObjCClassType()) {
  7309. S += "{objc_class=}";
  7310. return;
  7311. }
  7312. // TODO: Double check to make sure this intentionally falls through.
  7313. [[fallthrough]];
  7314. }
  7315. case Type::ObjCInterface: {
  7316. // Ignore protocol qualifiers when mangling at this level.
  7317. // @encode(class_name)
  7318. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  7319. S += '{';
  7320. S += OI->getObjCRuntimeNameAsString();
  7321. if (Options.ExpandStructures()) {
  7322. S += '=';
  7323. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  7324. DeepCollectObjCIvars(OI, true, Ivars);
  7325. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  7326. const FieldDecl *Field = Ivars[i];
  7327. if (Field->isBitField())
  7328. getObjCEncodingForTypeImpl(Field->getType(), S,
  7329. ObjCEncOptions().setExpandStructures(),
  7330. Field);
  7331. else
  7332. getObjCEncodingForTypeImpl(Field->getType(), S,
  7333. ObjCEncOptions().setExpandStructures(), FD,
  7334. NotEncodedT);
  7335. }
  7336. }
  7337. S += '}';
  7338. return;
  7339. }
  7340. case Type::ObjCObjectPointer: {
  7341. const auto *OPT = T->castAs<ObjCObjectPointerType>();
  7342. if (OPT->isObjCIdType()) {
  7343. S += '@';
  7344. return;
  7345. }
  7346. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  7347. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  7348. // Since this is a binary compatibility issue, need to consult with
  7349. // runtime folks. Fortunately, this is a *very* obscure construct.
  7350. S += '#';
  7351. return;
  7352. }
  7353. if (OPT->isObjCQualifiedIdType()) {
  7354. getObjCEncodingForTypeImpl(
  7355. getObjCIdType(), S,
  7356. Options.keepingOnly(ObjCEncOptions()
  7357. .setExpandPointedToStructures()
  7358. .setExpandStructures()),
  7359. FD);
  7360. if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
  7361. // Note that we do extended encoding of protocol qualifier list
  7362. // Only when doing ivar or property encoding.
  7363. S += '"';
  7364. for (const auto *I : OPT->quals()) {
  7365. S += '<';
  7366. S += I->getObjCRuntimeNameAsString();
  7367. S += '>';
  7368. }
  7369. S += '"';
  7370. }
  7371. return;
  7372. }
  7373. S += '@';
  7374. if (OPT->getInterfaceDecl() &&
  7375. (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
  7376. S += '"';
  7377. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  7378. for (const auto *I : OPT->quals()) {
  7379. S += '<';
  7380. S += I->getObjCRuntimeNameAsString();
  7381. S += '>';
  7382. }
  7383. S += '"';
  7384. }
  7385. return;
  7386. }
  7387. // gcc just blithely ignores member pointers.
  7388. // FIXME: we should do better than that. 'M' is available.
  7389. case Type::MemberPointer:
  7390. // This matches gcc's encoding, even though technically it is insufficient.
  7391. //FIXME. We should do a better job than gcc.
  7392. case Type::Vector:
  7393. case Type::ExtVector:
  7394. // Until we have a coherent encoding of these three types, issue warning.
  7395. if (NotEncodedT)
  7396. *NotEncodedT = T;
  7397. return;
  7398. case Type::ConstantMatrix:
  7399. if (NotEncodedT)
  7400. *NotEncodedT = T;
  7401. return;
  7402. case Type::BitInt:
  7403. if (NotEncodedT)
  7404. *NotEncodedT = T;
  7405. return;
  7406. // We could see an undeduced auto type here during error recovery.
  7407. // Just ignore it.
  7408. case Type::Auto:
  7409. case Type::DeducedTemplateSpecialization:
  7410. return;
  7411. case Type::Pipe:
  7412. #define ABSTRACT_TYPE(KIND, BASE)
  7413. #define TYPE(KIND, BASE)
  7414. #define DEPENDENT_TYPE(KIND, BASE) \
  7415. case Type::KIND:
  7416. #define NON_CANONICAL_TYPE(KIND, BASE) \
  7417. case Type::KIND:
  7418. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  7419. case Type::KIND:
  7420. #include "clang/AST/TypeNodes.inc"
  7421. llvm_unreachable("@encode for dependent type!");
  7422. }
  7423. llvm_unreachable("bad type kind!");
  7424. }
  7425. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  7426. std::string &S,
  7427. const FieldDecl *FD,
  7428. bool includeVBases,
  7429. QualType *NotEncodedT) const {
  7430. assert(RDecl && "Expected non-null RecordDecl");
  7431. assert(!RDecl->isUnion() && "Should not be called for unions");
  7432. if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
  7433. return;
  7434. const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  7435. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  7436. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  7437. if (CXXRec) {
  7438. for (const auto &BI : CXXRec->bases()) {
  7439. if (!BI.isVirtual()) {
  7440. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  7441. if (base->isEmpty())
  7442. continue;
  7443. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  7444. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7445. std::make_pair(offs, base));
  7446. }
  7447. }
  7448. }
  7449. unsigned i = 0;
  7450. for (FieldDecl *Field : RDecl->fields()) {
  7451. if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
  7452. continue;
  7453. uint64_t offs = layout.getFieldOffset(i);
  7454. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7455. std::make_pair(offs, Field));
  7456. ++i;
  7457. }
  7458. if (CXXRec && includeVBases) {
  7459. for (const auto &BI : CXXRec->vbases()) {
  7460. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  7461. if (base->isEmpty())
  7462. continue;
  7463. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  7464. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  7465. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  7466. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  7467. std::make_pair(offs, base));
  7468. }
  7469. }
  7470. CharUnits size;
  7471. if (CXXRec) {
  7472. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  7473. } else {
  7474. size = layout.getSize();
  7475. }
  7476. #ifndef NDEBUG
  7477. uint64_t CurOffs = 0;
  7478. #endif
  7479. std::multimap<uint64_t, NamedDecl *>::iterator
  7480. CurLayObj = FieldOrBaseOffsets.begin();
  7481. if (CXXRec && CXXRec->isDynamicClass() &&
  7482. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  7483. if (FD) {
  7484. S += "\"_vptr$";
  7485. std::string recname = CXXRec->getNameAsString();
  7486. if (recname.empty()) recname = "?";
  7487. S += recname;
  7488. S += '"';
  7489. }
  7490. S += "^^?";
  7491. #ifndef NDEBUG
  7492. CurOffs += getTypeSize(VoidPtrTy);
  7493. #endif
  7494. }
  7495. if (!RDecl->hasFlexibleArrayMember()) {
  7496. // Mark the end of the structure.
  7497. uint64_t offs = toBits(size);
  7498. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7499. std::make_pair(offs, nullptr));
  7500. }
  7501. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  7502. #ifndef NDEBUG
  7503. assert(CurOffs <= CurLayObj->first);
  7504. if (CurOffs < CurLayObj->first) {
  7505. uint64_t padding = CurLayObj->first - CurOffs;
  7506. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  7507. // packing/alignment of members is different that normal, in which case
  7508. // the encoding will be out-of-sync with the real layout.
  7509. // If the runtime switches to just consider the size of types without
  7510. // taking into account alignment, we could make padding explicit in the
  7511. // encoding (e.g. using arrays of chars). The encoding strings would be
  7512. // longer then though.
  7513. CurOffs += padding;
  7514. }
  7515. #endif
  7516. NamedDecl *dcl = CurLayObj->second;
  7517. if (!dcl)
  7518. break; // reached end of structure.
  7519. if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
  7520. // We expand the bases without their virtual bases since those are going
  7521. // in the initial structure. Note that this differs from gcc which
  7522. // expands virtual bases each time one is encountered in the hierarchy,
  7523. // making the encoding type bigger than it really is.
  7524. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  7525. NotEncodedT);
  7526. assert(!base->isEmpty());
  7527. #ifndef NDEBUG
  7528. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  7529. #endif
  7530. } else {
  7531. const auto *field = cast<FieldDecl>(dcl);
  7532. if (FD) {
  7533. S += '"';
  7534. S += field->getNameAsString();
  7535. S += '"';
  7536. }
  7537. if (field->isBitField()) {
  7538. EncodeBitField(this, S, field->getType(), field);
  7539. #ifndef NDEBUG
  7540. CurOffs += field->getBitWidthValue(*this);
  7541. #endif
  7542. } else {
  7543. QualType qt = field->getType();
  7544. getLegacyIntegralTypeEncoding(qt);
  7545. getObjCEncodingForTypeImpl(
  7546. qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
  7547. FD, NotEncodedT);
  7548. #ifndef NDEBUG
  7549. CurOffs += getTypeSize(field->getType());
  7550. #endif
  7551. }
  7552. }
  7553. }
  7554. }
  7555. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  7556. std::string& S) const {
  7557. if (QT & Decl::OBJC_TQ_In)
  7558. S += 'n';
  7559. if (QT & Decl::OBJC_TQ_Inout)
  7560. S += 'N';
  7561. if (QT & Decl::OBJC_TQ_Out)
  7562. S += 'o';
  7563. if (QT & Decl::OBJC_TQ_Bycopy)
  7564. S += 'O';
  7565. if (QT & Decl::OBJC_TQ_Byref)
  7566. S += 'R';
  7567. if (QT & Decl::OBJC_TQ_Oneway)
  7568. S += 'V';
  7569. }
  7570. TypedefDecl *ASTContext::getObjCIdDecl() const {
  7571. if (!ObjCIdDecl) {
  7572. QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
  7573. T = getObjCObjectPointerType(T);
  7574. ObjCIdDecl = buildImplicitTypedef(T, "id");
  7575. }
  7576. return ObjCIdDecl;
  7577. }
  7578. TypedefDecl *ASTContext::getObjCSelDecl() const {
  7579. if (!ObjCSelDecl) {
  7580. QualType T = getPointerType(ObjCBuiltinSelTy);
  7581. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  7582. }
  7583. return ObjCSelDecl;
  7584. }
  7585. TypedefDecl *ASTContext::getObjCClassDecl() const {
  7586. if (!ObjCClassDecl) {
  7587. QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
  7588. T = getObjCObjectPointerType(T);
  7589. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  7590. }
  7591. return ObjCClassDecl;
  7592. }
  7593. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  7594. if (!ObjCProtocolClassDecl) {
  7595. ObjCProtocolClassDecl
  7596. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  7597. SourceLocation(),
  7598. &Idents.get("Protocol"),
  7599. /*typeParamList=*/nullptr,
  7600. /*PrevDecl=*/nullptr,
  7601. SourceLocation(), true);
  7602. }
  7603. return ObjCProtocolClassDecl;
  7604. }
  7605. //===----------------------------------------------------------------------===//
  7606. // __builtin_va_list Construction Functions
  7607. //===----------------------------------------------------------------------===//
  7608. static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
  7609. StringRef Name) {
  7610. // typedef char* __builtin[_ms]_va_list;
  7611. QualType T = Context->getPointerType(Context->CharTy);
  7612. return Context->buildImplicitTypedef(T, Name);
  7613. }
  7614. static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
  7615. return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
  7616. }
  7617. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  7618. return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
  7619. }
  7620. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  7621. // typedef void* __builtin_va_list;
  7622. QualType T = Context->getPointerType(Context->VoidTy);
  7623. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  7624. }
  7625. static TypedefDecl *
  7626. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  7627. // struct __va_list
  7628. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  7629. if (Context->getLangOpts().CPlusPlus) {
  7630. // namespace std { struct __va_list {
  7631. auto *NS = NamespaceDecl::Create(
  7632. const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
  7633. /*Inline=*/false, SourceLocation(), SourceLocation(),
  7634. &Context->Idents.get("std"),
  7635. /*PrevDecl=*/nullptr, /*Nested=*/false);
  7636. NS->setImplicit();
  7637. VaListTagDecl->setDeclContext(NS);
  7638. }
  7639. VaListTagDecl->startDefinition();
  7640. const size_t NumFields = 5;
  7641. QualType FieldTypes[NumFields];
  7642. const char *FieldNames[NumFields];
  7643. // void *__stack;
  7644. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  7645. FieldNames[0] = "__stack";
  7646. // void *__gr_top;
  7647. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  7648. FieldNames[1] = "__gr_top";
  7649. // void *__vr_top;
  7650. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7651. FieldNames[2] = "__vr_top";
  7652. // int __gr_offs;
  7653. FieldTypes[3] = Context->IntTy;
  7654. FieldNames[3] = "__gr_offs";
  7655. // int __vr_offs;
  7656. FieldTypes[4] = Context->IntTy;
  7657. FieldNames[4] = "__vr_offs";
  7658. // Create fields
  7659. for (unsigned i = 0; i < NumFields; ++i) {
  7660. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7661. VaListTagDecl,
  7662. SourceLocation(),
  7663. SourceLocation(),
  7664. &Context->Idents.get(FieldNames[i]),
  7665. FieldTypes[i], /*TInfo=*/nullptr,
  7666. /*BitWidth=*/nullptr,
  7667. /*Mutable=*/false,
  7668. ICIS_NoInit);
  7669. Field->setAccess(AS_public);
  7670. VaListTagDecl->addDecl(Field);
  7671. }
  7672. VaListTagDecl->completeDefinition();
  7673. Context->VaListTagDecl = VaListTagDecl;
  7674. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7675. // } __builtin_va_list;
  7676. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  7677. }
  7678. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  7679. // typedef struct __va_list_tag {
  7680. RecordDecl *VaListTagDecl;
  7681. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7682. VaListTagDecl->startDefinition();
  7683. const size_t NumFields = 5;
  7684. QualType FieldTypes[NumFields];
  7685. const char *FieldNames[NumFields];
  7686. // unsigned char gpr;
  7687. FieldTypes[0] = Context->UnsignedCharTy;
  7688. FieldNames[0] = "gpr";
  7689. // unsigned char fpr;
  7690. FieldTypes[1] = Context->UnsignedCharTy;
  7691. FieldNames[1] = "fpr";
  7692. // unsigned short reserved;
  7693. FieldTypes[2] = Context->UnsignedShortTy;
  7694. FieldNames[2] = "reserved";
  7695. // void* overflow_arg_area;
  7696. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7697. FieldNames[3] = "overflow_arg_area";
  7698. // void* reg_save_area;
  7699. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  7700. FieldNames[4] = "reg_save_area";
  7701. // Create fields
  7702. for (unsigned i = 0; i < NumFields; ++i) {
  7703. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  7704. SourceLocation(),
  7705. SourceLocation(),
  7706. &Context->Idents.get(FieldNames[i]),
  7707. FieldTypes[i], /*TInfo=*/nullptr,
  7708. /*BitWidth=*/nullptr,
  7709. /*Mutable=*/false,
  7710. ICIS_NoInit);
  7711. Field->setAccess(AS_public);
  7712. VaListTagDecl->addDecl(Field);
  7713. }
  7714. VaListTagDecl->completeDefinition();
  7715. Context->VaListTagDecl = VaListTagDecl;
  7716. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7717. // } __va_list_tag;
  7718. TypedefDecl *VaListTagTypedefDecl =
  7719. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  7720. QualType VaListTagTypedefType =
  7721. Context->getTypedefType(VaListTagTypedefDecl);
  7722. // typedef __va_list_tag __builtin_va_list[1];
  7723. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7724. QualType VaListTagArrayType
  7725. = Context->getConstantArrayType(VaListTagTypedefType,
  7726. Size, nullptr, ArrayType::Normal, 0);
  7727. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7728. }
  7729. static TypedefDecl *
  7730. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  7731. // struct __va_list_tag {
  7732. RecordDecl *VaListTagDecl;
  7733. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7734. VaListTagDecl->startDefinition();
  7735. const size_t NumFields = 4;
  7736. QualType FieldTypes[NumFields];
  7737. const char *FieldNames[NumFields];
  7738. // unsigned gp_offset;
  7739. FieldTypes[0] = Context->UnsignedIntTy;
  7740. FieldNames[0] = "gp_offset";
  7741. // unsigned fp_offset;
  7742. FieldTypes[1] = Context->UnsignedIntTy;
  7743. FieldNames[1] = "fp_offset";
  7744. // void* overflow_arg_area;
  7745. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7746. FieldNames[2] = "overflow_arg_area";
  7747. // void* reg_save_area;
  7748. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7749. FieldNames[3] = "reg_save_area";
  7750. // Create fields
  7751. for (unsigned i = 0; i < NumFields; ++i) {
  7752. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7753. VaListTagDecl,
  7754. SourceLocation(),
  7755. SourceLocation(),
  7756. &Context->Idents.get(FieldNames[i]),
  7757. FieldTypes[i], /*TInfo=*/nullptr,
  7758. /*BitWidth=*/nullptr,
  7759. /*Mutable=*/false,
  7760. ICIS_NoInit);
  7761. Field->setAccess(AS_public);
  7762. VaListTagDecl->addDecl(Field);
  7763. }
  7764. VaListTagDecl->completeDefinition();
  7765. Context->VaListTagDecl = VaListTagDecl;
  7766. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7767. // };
  7768. // typedef struct __va_list_tag __builtin_va_list[1];
  7769. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7770. QualType VaListTagArrayType = Context->getConstantArrayType(
  7771. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  7772. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7773. }
  7774. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  7775. // typedef int __builtin_va_list[4];
  7776. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  7777. QualType IntArrayType = Context->getConstantArrayType(
  7778. Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
  7779. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  7780. }
  7781. static TypedefDecl *
  7782. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  7783. // struct __va_list
  7784. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  7785. if (Context->getLangOpts().CPlusPlus) {
  7786. // namespace std { struct __va_list {
  7787. NamespaceDecl *NS;
  7788. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  7789. Context->getTranslationUnitDecl(),
  7790. /*Inline=*/false, SourceLocation(),
  7791. SourceLocation(), &Context->Idents.get("std"),
  7792. /*PrevDecl=*/nullptr, /*Nested=*/false);
  7793. NS->setImplicit();
  7794. VaListDecl->setDeclContext(NS);
  7795. }
  7796. VaListDecl->startDefinition();
  7797. // void * __ap;
  7798. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7799. VaListDecl,
  7800. SourceLocation(),
  7801. SourceLocation(),
  7802. &Context->Idents.get("__ap"),
  7803. Context->getPointerType(Context->VoidTy),
  7804. /*TInfo=*/nullptr,
  7805. /*BitWidth=*/nullptr,
  7806. /*Mutable=*/false,
  7807. ICIS_NoInit);
  7808. Field->setAccess(AS_public);
  7809. VaListDecl->addDecl(Field);
  7810. // };
  7811. VaListDecl->completeDefinition();
  7812. Context->VaListTagDecl = VaListDecl;
  7813. // typedef struct __va_list __builtin_va_list;
  7814. QualType T = Context->getRecordType(VaListDecl);
  7815. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  7816. }
  7817. static TypedefDecl *
  7818. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  7819. // struct __va_list_tag {
  7820. RecordDecl *VaListTagDecl;
  7821. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7822. VaListTagDecl->startDefinition();
  7823. const size_t NumFields = 4;
  7824. QualType FieldTypes[NumFields];
  7825. const char *FieldNames[NumFields];
  7826. // long __gpr;
  7827. FieldTypes[0] = Context->LongTy;
  7828. FieldNames[0] = "__gpr";
  7829. // long __fpr;
  7830. FieldTypes[1] = Context->LongTy;
  7831. FieldNames[1] = "__fpr";
  7832. // void *__overflow_arg_area;
  7833. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7834. FieldNames[2] = "__overflow_arg_area";
  7835. // void *__reg_save_area;
  7836. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7837. FieldNames[3] = "__reg_save_area";
  7838. // Create fields
  7839. for (unsigned i = 0; i < NumFields; ++i) {
  7840. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7841. VaListTagDecl,
  7842. SourceLocation(),
  7843. SourceLocation(),
  7844. &Context->Idents.get(FieldNames[i]),
  7845. FieldTypes[i], /*TInfo=*/nullptr,
  7846. /*BitWidth=*/nullptr,
  7847. /*Mutable=*/false,
  7848. ICIS_NoInit);
  7849. Field->setAccess(AS_public);
  7850. VaListTagDecl->addDecl(Field);
  7851. }
  7852. VaListTagDecl->completeDefinition();
  7853. Context->VaListTagDecl = VaListTagDecl;
  7854. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7855. // };
  7856. // typedef __va_list_tag __builtin_va_list[1];
  7857. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7858. QualType VaListTagArrayType = Context->getConstantArrayType(
  7859. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  7860. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7861. }
  7862. static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
  7863. // typedef struct __va_list_tag {
  7864. RecordDecl *VaListTagDecl;
  7865. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7866. VaListTagDecl->startDefinition();
  7867. const size_t NumFields = 3;
  7868. QualType FieldTypes[NumFields];
  7869. const char *FieldNames[NumFields];
  7870. // void *CurrentSavedRegisterArea;
  7871. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  7872. FieldNames[0] = "__current_saved_reg_area_pointer";
  7873. // void *SavedRegAreaEnd;
  7874. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  7875. FieldNames[1] = "__saved_reg_area_end_pointer";
  7876. // void *OverflowArea;
  7877. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7878. FieldNames[2] = "__overflow_area_pointer";
  7879. // Create fields
  7880. for (unsigned i = 0; i < NumFields; ++i) {
  7881. FieldDecl *Field = FieldDecl::Create(
  7882. const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
  7883. SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
  7884. /*TInfo=*/nullptr,
  7885. /*BitWidth=*/nullptr,
  7886. /*Mutable=*/false, ICIS_NoInit);
  7887. Field->setAccess(AS_public);
  7888. VaListTagDecl->addDecl(Field);
  7889. }
  7890. VaListTagDecl->completeDefinition();
  7891. Context->VaListTagDecl = VaListTagDecl;
  7892. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7893. // } __va_list_tag;
  7894. TypedefDecl *VaListTagTypedefDecl =
  7895. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  7896. QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
  7897. // typedef __va_list_tag __builtin_va_list[1];
  7898. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7899. QualType VaListTagArrayType = Context->getConstantArrayType(
  7900. VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
  7901. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7902. }
  7903. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  7904. TargetInfo::BuiltinVaListKind Kind) {
  7905. switch (Kind) {
  7906. case TargetInfo::CharPtrBuiltinVaList:
  7907. return CreateCharPtrBuiltinVaListDecl(Context);
  7908. case TargetInfo::VoidPtrBuiltinVaList:
  7909. return CreateVoidPtrBuiltinVaListDecl(Context);
  7910. case TargetInfo::AArch64ABIBuiltinVaList:
  7911. return CreateAArch64ABIBuiltinVaListDecl(Context);
  7912. case TargetInfo::PowerABIBuiltinVaList:
  7913. return CreatePowerABIBuiltinVaListDecl(Context);
  7914. case TargetInfo::X86_64ABIBuiltinVaList:
  7915. return CreateX86_64ABIBuiltinVaListDecl(Context);
  7916. case TargetInfo::PNaClABIBuiltinVaList:
  7917. return CreatePNaClABIBuiltinVaListDecl(Context);
  7918. case TargetInfo::AAPCSABIBuiltinVaList:
  7919. return CreateAAPCSABIBuiltinVaListDecl(Context);
  7920. case TargetInfo::SystemZBuiltinVaList:
  7921. return CreateSystemZBuiltinVaListDecl(Context);
  7922. case TargetInfo::HexagonBuiltinVaList:
  7923. return CreateHexagonBuiltinVaListDecl(Context);
  7924. }
  7925. llvm_unreachable("Unhandled __builtin_va_list type kind");
  7926. }
  7927. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  7928. if (!BuiltinVaListDecl) {
  7929. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  7930. assert(BuiltinVaListDecl->isImplicit());
  7931. }
  7932. return BuiltinVaListDecl;
  7933. }
  7934. Decl *ASTContext::getVaListTagDecl() const {
  7935. // Force the creation of VaListTagDecl by building the __builtin_va_list
  7936. // declaration.
  7937. if (!VaListTagDecl)
  7938. (void)getBuiltinVaListDecl();
  7939. return VaListTagDecl;
  7940. }
  7941. TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
  7942. if (!BuiltinMSVaListDecl)
  7943. BuiltinMSVaListDecl = CreateMSVaListDecl(this);
  7944. return BuiltinMSVaListDecl;
  7945. }
  7946. bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
  7947. // Allow redecl custom type checking builtin for HLSL.
  7948. if (LangOpts.HLSL && FD->getBuiltinID() != Builtin::NotBuiltin &&
  7949. BuiltinInfo.hasCustomTypechecking(FD->getBuiltinID()))
  7950. return true;
  7951. return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
  7952. }
  7953. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  7954. assert(ObjCConstantStringType.isNull() &&
  7955. "'NSConstantString' type already set!");
  7956. ObjCConstantStringType = getObjCInterfaceType(Decl);
  7957. }
  7958. /// Retrieve the template name that corresponds to a non-empty
  7959. /// lookup.
  7960. TemplateName
  7961. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  7962. UnresolvedSetIterator End) const {
  7963. unsigned size = End - Begin;
  7964. assert(size > 1 && "set is not overloaded!");
  7965. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  7966. size * sizeof(FunctionTemplateDecl*));
  7967. auto *OT = new (memory) OverloadedTemplateStorage(size);
  7968. NamedDecl **Storage = OT->getStorage();
  7969. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  7970. NamedDecl *D = *I;
  7971. assert(isa<FunctionTemplateDecl>(D) ||
  7972. isa<UnresolvedUsingValueDecl>(D) ||
  7973. (isa<UsingShadowDecl>(D) &&
  7974. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  7975. *Storage++ = D;
  7976. }
  7977. return TemplateName(OT);
  7978. }
  7979. /// Retrieve a template name representing an unqualified-id that has been
  7980. /// assumed to name a template for ADL purposes.
  7981. TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
  7982. auto *OT = new (*this) AssumedTemplateStorage(Name);
  7983. return TemplateName(OT);
  7984. }
  7985. /// Retrieve the template name that represents a qualified
  7986. /// template name such as \c std::vector.
  7987. TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  7988. bool TemplateKeyword,
  7989. TemplateName Template) const {
  7990. assert(NNS && "Missing nested-name-specifier in qualified template name");
  7991. // FIXME: Canonicalization?
  7992. llvm::FoldingSetNodeID ID;
  7993. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  7994. void *InsertPos = nullptr;
  7995. QualifiedTemplateName *QTN =
  7996. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7997. if (!QTN) {
  7998. QTN = new (*this, alignof(QualifiedTemplateName))
  7999. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  8000. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  8001. }
  8002. return TemplateName(QTN);
  8003. }
  8004. /// Retrieve the template name that represents a dependent
  8005. /// template name such as \c MetaFun::template apply.
  8006. TemplateName
  8007. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  8008. const IdentifierInfo *Name) const {
  8009. assert((!NNS || NNS->isDependent()) &&
  8010. "Nested name specifier must be dependent");
  8011. llvm::FoldingSetNodeID ID;
  8012. DependentTemplateName::Profile(ID, NNS, Name);
  8013. void *InsertPos = nullptr;
  8014. DependentTemplateName *QTN =
  8015. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  8016. if (QTN)
  8017. return TemplateName(QTN);
  8018. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  8019. if (CanonNNS == NNS) {
  8020. QTN = new (*this, alignof(DependentTemplateName))
  8021. DependentTemplateName(NNS, Name);
  8022. } else {
  8023. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  8024. QTN = new (*this, alignof(DependentTemplateName))
  8025. DependentTemplateName(NNS, Name, Canon);
  8026. DependentTemplateName *CheckQTN =
  8027. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  8028. assert(!CheckQTN && "Dependent type name canonicalization broken");
  8029. (void)CheckQTN;
  8030. }
  8031. DependentTemplateNames.InsertNode(QTN, InsertPos);
  8032. return TemplateName(QTN);
  8033. }
  8034. /// Retrieve the template name that represents a dependent
  8035. /// template name such as \c MetaFun::template operator+.
  8036. TemplateName
  8037. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  8038. OverloadedOperatorKind Operator) const {
  8039. assert((!NNS || NNS->isDependent()) &&
  8040. "Nested name specifier must be dependent");
  8041. llvm::FoldingSetNodeID ID;
  8042. DependentTemplateName::Profile(ID, NNS, Operator);
  8043. void *InsertPos = nullptr;
  8044. DependentTemplateName *QTN
  8045. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  8046. if (QTN)
  8047. return TemplateName(QTN);
  8048. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  8049. if (CanonNNS == NNS) {
  8050. QTN = new (*this, alignof(DependentTemplateName))
  8051. DependentTemplateName(NNS, Operator);
  8052. } else {
  8053. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  8054. QTN = new (*this, alignof(DependentTemplateName))
  8055. DependentTemplateName(NNS, Operator, Canon);
  8056. DependentTemplateName *CheckQTN
  8057. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  8058. assert(!CheckQTN && "Dependent template name canonicalization broken");
  8059. (void)CheckQTN;
  8060. }
  8061. DependentTemplateNames.InsertNode(QTN, InsertPos);
  8062. return TemplateName(QTN);
  8063. }
  8064. TemplateName ASTContext::getSubstTemplateTemplateParm(
  8065. TemplateName Replacement, Decl *AssociatedDecl, unsigned Index,
  8066. std::optional<unsigned> PackIndex) const {
  8067. llvm::FoldingSetNodeID ID;
  8068. SubstTemplateTemplateParmStorage::Profile(ID, Replacement, AssociatedDecl,
  8069. Index, PackIndex);
  8070. void *insertPos = nullptr;
  8071. SubstTemplateTemplateParmStorage *subst
  8072. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  8073. if (!subst) {
  8074. subst = new (*this) SubstTemplateTemplateParmStorage(
  8075. Replacement, AssociatedDecl, Index, PackIndex);
  8076. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  8077. }
  8078. return TemplateName(subst);
  8079. }
  8080. TemplateName
  8081. ASTContext::getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
  8082. Decl *AssociatedDecl,
  8083. unsigned Index, bool Final) const {
  8084. auto &Self = const_cast<ASTContext &>(*this);
  8085. llvm::FoldingSetNodeID ID;
  8086. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, ArgPack,
  8087. AssociatedDecl, Index, Final);
  8088. void *InsertPos = nullptr;
  8089. SubstTemplateTemplateParmPackStorage *Subst
  8090. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  8091. if (!Subst) {
  8092. Subst = new (*this) SubstTemplateTemplateParmPackStorage(
  8093. ArgPack.pack_elements(), AssociatedDecl, Index, Final);
  8094. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  8095. }
  8096. return TemplateName(Subst);
  8097. }
  8098. /// getFromTargetType - Given one of the integer types provided by
  8099. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  8100. /// is actually a value of type @c TargetInfo::IntType.
  8101. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  8102. switch (Type) {
  8103. case TargetInfo::NoInt: return {};
  8104. case TargetInfo::SignedChar: return SignedCharTy;
  8105. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  8106. case TargetInfo::SignedShort: return ShortTy;
  8107. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  8108. case TargetInfo::SignedInt: return IntTy;
  8109. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  8110. case TargetInfo::SignedLong: return LongTy;
  8111. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  8112. case TargetInfo::SignedLongLong: return LongLongTy;
  8113. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  8114. }
  8115. llvm_unreachable("Unhandled TargetInfo::IntType value");
  8116. }
  8117. //===----------------------------------------------------------------------===//
  8118. // Type Predicates.
  8119. //===----------------------------------------------------------------------===//
  8120. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  8121. /// garbage collection attribute.
  8122. ///
  8123. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  8124. if (getLangOpts().getGC() == LangOptions::NonGC)
  8125. return Qualifiers::GCNone;
  8126. assert(getLangOpts().ObjC);
  8127. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  8128. // Default behaviour under objective-C's gc is for ObjC pointers
  8129. // (or pointers to them) be treated as though they were declared
  8130. // as __strong.
  8131. if (GCAttrs == Qualifiers::GCNone) {
  8132. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  8133. return Qualifiers::Strong;
  8134. else if (Ty->isPointerType())
  8135. return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
  8136. } else {
  8137. // It's not valid to set GC attributes on anything that isn't a
  8138. // pointer.
  8139. #ifndef NDEBUG
  8140. QualType CT = Ty->getCanonicalTypeInternal();
  8141. while (const auto *AT = dyn_cast<ArrayType>(CT))
  8142. CT = AT->getElementType();
  8143. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  8144. #endif
  8145. }
  8146. return GCAttrs;
  8147. }
  8148. //===----------------------------------------------------------------------===//
  8149. // Type Compatibility Testing
  8150. //===----------------------------------------------------------------------===//
  8151. /// areCompatVectorTypes - Return true if the two specified vector types are
  8152. /// compatible.
  8153. static bool areCompatVectorTypes(const VectorType *LHS,
  8154. const VectorType *RHS) {
  8155. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  8156. return LHS->getElementType() == RHS->getElementType() &&
  8157. LHS->getNumElements() == RHS->getNumElements();
  8158. }
  8159. /// areCompatMatrixTypes - Return true if the two specified matrix types are
  8160. /// compatible.
  8161. static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
  8162. const ConstantMatrixType *RHS) {
  8163. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  8164. return LHS->getElementType() == RHS->getElementType() &&
  8165. LHS->getNumRows() == RHS->getNumRows() &&
  8166. LHS->getNumColumns() == RHS->getNumColumns();
  8167. }
  8168. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  8169. QualType SecondVec) {
  8170. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  8171. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  8172. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  8173. return true;
  8174. // Treat Neon vector types and most AltiVec vector types as if they are the
  8175. // equivalent GCC vector types.
  8176. const auto *First = FirstVec->castAs<VectorType>();
  8177. const auto *Second = SecondVec->castAs<VectorType>();
  8178. if (First->getNumElements() == Second->getNumElements() &&
  8179. hasSameType(First->getElementType(), Second->getElementType()) &&
  8180. First->getVectorKind() != VectorType::AltiVecPixel &&
  8181. First->getVectorKind() != VectorType::AltiVecBool &&
  8182. Second->getVectorKind() != VectorType::AltiVecPixel &&
  8183. Second->getVectorKind() != VectorType::AltiVecBool &&
  8184. First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
  8185. First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
  8186. Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
  8187. Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
  8188. return true;
  8189. return false;
  8190. }
  8191. /// getSVETypeSize - Return SVE vector or predicate register size.
  8192. static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
  8193. assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
  8194. return Ty->getKind() == BuiltinType::SveBool
  8195. ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
  8196. : Context.getLangOpts().VScaleMin * 128;
  8197. }
  8198. bool ASTContext::areCompatibleSveTypes(QualType FirstType,
  8199. QualType SecondType) {
  8200. assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
  8201. (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
  8202. "Expected SVE builtin type and vector type!");
  8203. auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
  8204. if (const auto *BT = FirstType->getAs<BuiltinType>()) {
  8205. if (const auto *VT = SecondType->getAs<VectorType>()) {
  8206. // Predicates have the same representation as uint8 so we also have to
  8207. // check the kind to make these types incompatible.
  8208. if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  8209. return BT->getKind() == BuiltinType::SveBool;
  8210. else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
  8211. return VT->getElementType().getCanonicalType() ==
  8212. FirstType->getSveEltType(*this);
  8213. else if (VT->getVectorKind() == VectorType::GenericVector)
  8214. return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
  8215. hasSameType(VT->getElementType(),
  8216. getBuiltinVectorTypeInfo(BT).ElementType);
  8217. }
  8218. }
  8219. return false;
  8220. };
  8221. return IsValidCast(FirstType, SecondType) ||
  8222. IsValidCast(SecondType, FirstType);
  8223. }
  8224. bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
  8225. QualType SecondType) {
  8226. assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
  8227. (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
  8228. "Expected SVE builtin type and vector type!");
  8229. auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
  8230. const auto *BT = FirstType->getAs<BuiltinType>();
  8231. if (!BT)
  8232. return false;
  8233. const auto *VecTy = SecondType->getAs<VectorType>();
  8234. if (VecTy &&
  8235. (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  8236. VecTy->getVectorKind() == VectorType::GenericVector)) {
  8237. const LangOptions::LaxVectorConversionKind LVCKind =
  8238. getLangOpts().getLaxVectorConversions();
  8239. // Can not convert between sve predicates and sve vectors because of
  8240. // different size.
  8241. if (BT->getKind() == BuiltinType::SveBool &&
  8242. VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
  8243. return false;
  8244. // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
  8245. // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
  8246. // converts to VLAT and VLAT implicitly converts to GNUT."
  8247. // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
  8248. // predicates.
  8249. if (VecTy->getVectorKind() == VectorType::GenericVector &&
  8250. getTypeSize(SecondType) != getSVETypeSize(*this, BT))
  8251. return false;
  8252. // If -flax-vector-conversions=all is specified, the types are
  8253. // certainly compatible.
  8254. if (LVCKind == LangOptions::LaxVectorConversionKind::All)
  8255. return true;
  8256. // If -flax-vector-conversions=integer is specified, the types are
  8257. // compatible if the elements are integer types.
  8258. if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
  8259. return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
  8260. FirstType->getSveEltType(*this)->isIntegerType();
  8261. }
  8262. return false;
  8263. };
  8264. return IsLaxCompatible(FirstType, SecondType) ||
  8265. IsLaxCompatible(SecondType, FirstType);
  8266. }
  8267. bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
  8268. while (true) {
  8269. // __strong id
  8270. if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
  8271. if (Attr->getAttrKind() == attr::ObjCOwnership)
  8272. return true;
  8273. Ty = Attr->getModifiedType();
  8274. // X *__strong (...)
  8275. } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
  8276. Ty = Paren->getInnerType();
  8277. // We do not want to look through typedefs, typeof(expr),
  8278. // typeof(type), or any other way that the type is somehow
  8279. // abstracted.
  8280. } else {
  8281. return false;
  8282. }
  8283. }
  8284. }
  8285. //===----------------------------------------------------------------------===//
  8286. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  8287. //===----------------------------------------------------------------------===//
  8288. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  8289. /// inheritance hierarchy of 'rProto'.
  8290. bool
  8291. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  8292. ObjCProtocolDecl *rProto) const {
  8293. if (declaresSameEntity(lProto, rProto))
  8294. return true;
  8295. for (auto *PI : rProto->protocols())
  8296. if (ProtocolCompatibleWithProtocol(lProto, PI))
  8297. return true;
  8298. return false;
  8299. }
  8300. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  8301. /// Class<pr1, ...>.
  8302. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
  8303. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
  8304. for (auto *lhsProto : lhs->quals()) {
  8305. bool match = false;
  8306. for (auto *rhsProto : rhs->quals()) {
  8307. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  8308. match = true;
  8309. break;
  8310. }
  8311. }
  8312. if (!match)
  8313. return false;
  8314. }
  8315. return true;
  8316. }
  8317. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  8318. /// ObjCQualifiedIDType.
  8319. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
  8320. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
  8321. bool compare) {
  8322. // Allow id<P..> and an 'id' in all cases.
  8323. if (lhs->isObjCIdType() || rhs->isObjCIdType())
  8324. return true;
  8325. // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
  8326. if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
  8327. rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
  8328. return false;
  8329. if (lhs->isObjCQualifiedIdType()) {
  8330. if (rhs->qual_empty()) {
  8331. // If the RHS is a unqualified interface pointer "NSString*",
  8332. // make sure we check the class hierarchy.
  8333. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  8334. for (auto *I : lhs->quals()) {
  8335. // when comparing an id<P> on lhs with a static type on rhs,
  8336. // see if static class implements all of id's protocols, directly or
  8337. // through its super class and categories.
  8338. if (!rhsID->ClassImplementsProtocol(I, true))
  8339. return false;
  8340. }
  8341. }
  8342. // If there are no qualifiers and no interface, we have an 'id'.
  8343. return true;
  8344. }
  8345. // Both the right and left sides have qualifiers.
  8346. for (auto *lhsProto : lhs->quals()) {
  8347. bool match = false;
  8348. // when comparing an id<P> on lhs with a static type on rhs,
  8349. // see if static class implements all of id's protocols, directly or
  8350. // through its super class and categories.
  8351. for (auto *rhsProto : rhs->quals()) {
  8352. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8353. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8354. match = true;
  8355. break;
  8356. }
  8357. }
  8358. // If the RHS is a qualified interface pointer "NSString<P>*",
  8359. // make sure we check the class hierarchy.
  8360. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  8361. for (auto *I : lhs->quals()) {
  8362. // when comparing an id<P> on lhs with a static type on rhs,
  8363. // see if static class implements all of id's protocols, directly or
  8364. // through its super class and categories.
  8365. if (rhsID->ClassImplementsProtocol(I, true)) {
  8366. match = true;
  8367. break;
  8368. }
  8369. }
  8370. }
  8371. if (!match)
  8372. return false;
  8373. }
  8374. return true;
  8375. }
  8376. assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
  8377. if (lhs->getInterfaceType()) {
  8378. // If both the right and left sides have qualifiers.
  8379. for (auto *lhsProto : lhs->quals()) {
  8380. bool match = false;
  8381. // when comparing an id<P> on rhs with a static type on lhs,
  8382. // see if static class implements all of id's protocols, directly or
  8383. // through its super class and categories.
  8384. // First, lhs protocols in the qualifier list must be found, direct
  8385. // or indirect in rhs's qualifier list or it is a mismatch.
  8386. for (auto *rhsProto : rhs->quals()) {
  8387. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8388. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8389. match = true;
  8390. break;
  8391. }
  8392. }
  8393. if (!match)
  8394. return false;
  8395. }
  8396. // Static class's protocols, or its super class or category protocols
  8397. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  8398. if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
  8399. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  8400. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  8401. // This is rather dubious but matches gcc's behavior. If lhs has
  8402. // no type qualifier and its class has no static protocol(s)
  8403. // assume that it is mismatch.
  8404. if (LHSInheritedProtocols.empty() && lhs->qual_empty())
  8405. return false;
  8406. for (auto *lhsProto : LHSInheritedProtocols) {
  8407. bool match = false;
  8408. for (auto *rhsProto : rhs->quals()) {
  8409. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8410. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8411. match = true;
  8412. break;
  8413. }
  8414. }
  8415. if (!match)
  8416. return false;
  8417. }
  8418. }
  8419. return true;
  8420. }
  8421. return false;
  8422. }
  8423. /// canAssignObjCInterfaces - Return true if the two interface types are
  8424. /// compatible for assignment from RHS to LHS. This handles validation of any
  8425. /// protocol qualifiers on the LHS or RHS.
  8426. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  8427. const ObjCObjectPointerType *RHSOPT) {
  8428. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  8429. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  8430. // If either type represents the built-in 'id' type, return true.
  8431. if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
  8432. return true;
  8433. // Function object that propagates a successful result or handles
  8434. // __kindof types.
  8435. auto finish = [&](bool succeeded) -> bool {
  8436. if (succeeded)
  8437. return true;
  8438. if (!RHS->isKindOfType())
  8439. return false;
  8440. // Strip off __kindof and protocol qualifiers, then check whether
  8441. // we can assign the other way.
  8442. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8443. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  8444. };
  8445. // Casts from or to id<P> are allowed when the other side has compatible
  8446. // protocols.
  8447. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  8448. return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
  8449. }
  8450. // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
  8451. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  8452. return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
  8453. }
  8454. // Casts from Class to Class<Foo>, or vice-versa, are allowed.
  8455. if (LHS->isObjCClass() && RHS->isObjCClass()) {
  8456. return true;
  8457. }
  8458. // If we have 2 user-defined types, fall into that path.
  8459. if (LHS->getInterface() && RHS->getInterface()) {
  8460. return finish(canAssignObjCInterfaces(LHS, RHS));
  8461. }
  8462. return false;
  8463. }
  8464. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  8465. /// for providing type-safety for objective-c pointers used to pass/return
  8466. /// arguments in block literals. When passed as arguments, passing 'A*' where
  8467. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  8468. /// not OK. For the return type, the opposite is not OK.
  8469. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  8470. const ObjCObjectPointerType *LHSOPT,
  8471. const ObjCObjectPointerType *RHSOPT,
  8472. bool BlockReturnType) {
  8473. // Function object that propagates a successful result or handles
  8474. // __kindof types.
  8475. auto finish = [&](bool succeeded) -> bool {
  8476. if (succeeded)
  8477. return true;
  8478. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  8479. if (!Expected->isKindOfType())
  8480. return false;
  8481. // Strip off __kindof and protocol qualifiers, then check whether
  8482. // we can assign the other way.
  8483. return canAssignObjCInterfacesInBlockPointer(
  8484. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8485. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8486. BlockReturnType);
  8487. };
  8488. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  8489. return true;
  8490. if (LHSOPT->isObjCBuiltinType()) {
  8491. return finish(RHSOPT->isObjCBuiltinType() ||
  8492. RHSOPT->isObjCQualifiedIdType());
  8493. }
  8494. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
  8495. if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
  8496. // Use for block parameters previous type checking for compatibility.
  8497. return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
  8498. // Or corrected type checking as in non-compat mode.
  8499. (!BlockReturnType &&
  8500. ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
  8501. else
  8502. return finish(ObjCQualifiedIdTypesAreCompatible(
  8503. (BlockReturnType ? LHSOPT : RHSOPT),
  8504. (BlockReturnType ? RHSOPT : LHSOPT), false));
  8505. }
  8506. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  8507. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  8508. if (LHS && RHS) { // We have 2 user-defined types.
  8509. if (LHS != RHS) {
  8510. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  8511. return finish(BlockReturnType);
  8512. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  8513. return finish(!BlockReturnType);
  8514. }
  8515. else
  8516. return true;
  8517. }
  8518. return false;
  8519. }
  8520. /// Comparison routine for Objective-C protocols to be used with
  8521. /// llvm::array_pod_sort.
  8522. static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
  8523. ObjCProtocolDecl * const *rhs) {
  8524. return (*lhs)->getName().compare((*rhs)->getName());
  8525. }
  8526. /// getIntersectionOfProtocols - This routine finds the intersection of set
  8527. /// of protocols inherited from two distinct objective-c pointer objects with
  8528. /// the given common base.
  8529. /// It is used to build composite qualifier list of the composite type of
  8530. /// the conditional expression involving two objective-c pointer objects.
  8531. static
  8532. void getIntersectionOfProtocols(ASTContext &Context,
  8533. const ObjCInterfaceDecl *CommonBase,
  8534. const ObjCObjectPointerType *LHSOPT,
  8535. const ObjCObjectPointerType *RHSOPT,
  8536. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  8537. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  8538. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  8539. assert(LHS->getInterface() && "LHS must have an interface base");
  8540. assert(RHS->getInterface() && "RHS must have an interface base");
  8541. // Add all of the protocols for the LHS.
  8542. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  8543. // Start with the protocol qualifiers.
  8544. for (auto *proto : LHS->quals()) {
  8545. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  8546. }
  8547. // Also add the protocols associated with the LHS interface.
  8548. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  8549. // Add all of the protocols for the RHS.
  8550. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  8551. // Start with the protocol qualifiers.
  8552. for (auto *proto : RHS->quals()) {
  8553. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  8554. }
  8555. // Also add the protocols associated with the RHS interface.
  8556. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  8557. // Compute the intersection of the collected protocol sets.
  8558. for (auto *proto : LHSProtocolSet) {
  8559. if (RHSProtocolSet.count(proto))
  8560. IntersectionSet.push_back(proto);
  8561. }
  8562. // Compute the set of protocols that is implied by either the common type or
  8563. // the protocols within the intersection.
  8564. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  8565. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  8566. // Remove any implied protocols from the list of inherited protocols.
  8567. if (!ImpliedProtocols.empty()) {
  8568. llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
  8569. return ImpliedProtocols.contains(proto);
  8570. });
  8571. }
  8572. // Sort the remaining protocols by name.
  8573. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  8574. compareObjCProtocolsByName);
  8575. }
  8576. /// Determine whether the first type is a subtype of the second.
  8577. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  8578. QualType rhs) {
  8579. // Common case: two object pointers.
  8580. const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  8581. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  8582. if (lhsOPT && rhsOPT)
  8583. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  8584. // Two block pointers.
  8585. const auto *lhsBlock = lhs->getAs<BlockPointerType>();
  8586. const auto *rhsBlock = rhs->getAs<BlockPointerType>();
  8587. if (lhsBlock && rhsBlock)
  8588. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  8589. // If either is an unqualified 'id' and the other is a block, it's
  8590. // acceptable.
  8591. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  8592. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  8593. return true;
  8594. return false;
  8595. }
  8596. // Check that the given Objective-C type argument lists are equivalent.
  8597. static bool sameObjCTypeArgs(ASTContext &ctx,
  8598. const ObjCInterfaceDecl *iface,
  8599. ArrayRef<QualType> lhsArgs,
  8600. ArrayRef<QualType> rhsArgs,
  8601. bool stripKindOf) {
  8602. if (lhsArgs.size() != rhsArgs.size())
  8603. return false;
  8604. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  8605. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  8606. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  8607. continue;
  8608. switch (typeParams->begin()[i]->getVariance()) {
  8609. case ObjCTypeParamVariance::Invariant:
  8610. if (!stripKindOf ||
  8611. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  8612. rhsArgs[i].stripObjCKindOfType(ctx))) {
  8613. return false;
  8614. }
  8615. break;
  8616. case ObjCTypeParamVariance::Covariant:
  8617. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  8618. return false;
  8619. break;
  8620. case ObjCTypeParamVariance::Contravariant:
  8621. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  8622. return false;
  8623. break;
  8624. }
  8625. }
  8626. return true;
  8627. }
  8628. QualType ASTContext::areCommonBaseCompatible(
  8629. const ObjCObjectPointerType *Lptr,
  8630. const ObjCObjectPointerType *Rptr) {
  8631. const ObjCObjectType *LHS = Lptr->getObjectType();
  8632. const ObjCObjectType *RHS = Rptr->getObjectType();
  8633. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  8634. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  8635. if (!LDecl || !RDecl)
  8636. return {};
  8637. // When either LHS or RHS is a kindof type, we should return a kindof type.
  8638. // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
  8639. // kindof(A).
  8640. bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
  8641. // Follow the left-hand side up the class hierarchy until we either hit a
  8642. // root or find the RHS. Record the ancestors in case we don't find it.
  8643. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  8644. LHSAncestors;
  8645. while (true) {
  8646. // Record this ancestor. We'll need this if the common type isn't in the
  8647. // path from the LHS to the root.
  8648. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  8649. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  8650. // Get the type arguments.
  8651. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  8652. bool anyChanges = false;
  8653. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  8654. // Both have type arguments, compare them.
  8655. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  8656. LHS->getTypeArgs(), RHS->getTypeArgs(),
  8657. /*stripKindOf=*/true))
  8658. return {};
  8659. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  8660. // If only one has type arguments, the result will not have type
  8661. // arguments.
  8662. LHSTypeArgs = {};
  8663. anyChanges = true;
  8664. }
  8665. // Compute the intersection of protocols.
  8666. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  8667. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  8668. Protocols);
  8669. if (!Protocols.empty())
  8670. anyChanges = true;
  8671. // If anything in the LHS will have changed, build a new result type.
  8672. // If we need to return a kindof type but LHS is not a kindof type, we
  8673. // build a new result type.
  8674. if (anyChanges || LHS->isKindOfType() != anyKindOf) {
  8675. QualType Result = getObjCInterfaceType(LHS->getInterface());
  8676. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  8677. anyKindOf || LHS->isKindOfType());
  8678. return getObjCObjectPointerType(Result);
  8679. }
  8680. return getObjCObjectPointerType(QualType(LHS, 0));
  8681. }
  8682. // Find the superclass.
  8683. QualType LHSSuperType = LHS->getSuperClassType();
  8684. if (LHSSuperType.isNull())
  8685. break;
  8686. LHS = LHSSuperType->castAs<ObjCObjectType>();
  8687. }
  8688. // We didn't find anything by following the LHS to its root; now check
  8689. // the RHS against the cached set of ancestors.
  8690. while (true) {
  8691. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  8692. if (KnownLHS != LHSAncestors.end()) {
  8693. LHS = KnownLHS->second;
  8694. // Get the type arguments.
  8695. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  8696. bool anyChanges = false;
  8697. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  8698. // Both have type arguments, compare them.
  8699. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  8700. LHS->getTypeArgs(), RHS->getTypeArgs(),
  8701. /*stripKindOf=*/true))
  8702. return {};
  8703. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  8704. // If only one has type arguments, the result will not have type
  8705. // arguments.
  8706. RHSTypeArgs = {};
  8707. anyChanges = true;
  8708. }
  8709. // Compute the intersection of protocols.
  8710. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  8711. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  8712. Protocols);
  8713. if (!Protocols.empty())
  8714. anyChanges = true;
  8715. // If we need to return a kindof type but RHS is not a kindof type, we
  8716. // build a new result type.
  8717. if (anyChanges || RHS->isKindOfType() != anyKindOf) {
  8718. QualType Result = getObjCInterfaceType(RHS->getInterface());
  8719. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  8720. anyKindOf || RHS->isKindOfType());
  8721. return getObjCObjectPointerType(Result);
  8722. }
  8723. return getObjCObjectPointerType(QualType(RHS, 0));
  8724. }
  8725. // Find the superclass of the RHS.
  8726. QualType RHSSuperType = RHS->getSuperClassType();
  8727. if (RHSSuperType.isNull())
  8728. break;
  8729. RHS = RHSSuperType->castAs<ObjCObjectType>();
  8730. }
  8731. return {};
  8732. }
  8733. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  8734. const ObjCObjectType *RHS) {
  8735. assert(LHS->getInterface() && "LHS is not an interface type");
  8736. assert(RHS->getInterface() && "RHS is not an interface type");
  8737. // Verify that the base decls are compatible: the RHS must be a subclass of
  8738. // the LHS.
  8739. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  8740. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  8741. if (!IsSuperClass)
  8742. return false;
  8743. // If the LHS has protocol qualifiers, determine whether all of them are
  8744. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  8745. // LHS).
  8746. if (LHS->getNumProtocols() > 0) {
  8747. // OK if conversion of LHS to SuperClass results in narrowing of types
  8748. // ; i.e., SuperClass may implement at least one of the protocols
  8749. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  8750. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  8751. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  8752. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  8753. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  8754. // qualifiers.
  8755. for (auto *RHSPI : RHS->quals())
  8756. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  8757. // If there is no protocols associated with RHS, it is not a match.
  8758. if (SuperClassInheritedProtocols.empty())
  8759. return false;
  8760. for (const auto *LHSProto : LHS->quals()) {
  8761. bool SuperImplementsProtocol = false;
  8762. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  8763. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  8764. SuperImplementsProtocol = true;
  8765. break;
  8766. }
  8767. if (!SuperImplementsProtocol)
  8768. return false;
  8769. }
  8770. }
  8771. // If the LHS is specialized, we may need to check type arguments.
  8772. if (LHS->isSpecialized()) {
  8773. // Follow the superclass chain until we've matched the LHS class in the
  8774. // hierarchy. This substitutes type arguments through.
  8775. const ObjCObjectType *RHSSuper = RHS;
  8776. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  8777. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  8778. // If the RHS is specializd, compare type arguments.
  8779. if (RHSSuper->isSpecialized() &&
  8780. !sameObjCTypeArgs(*this, LHS->getInterface(),
  8781. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  8782. /*stripKindOf=*/true)) {
  8783. return false;
  8784. }
  8785. }
  8786. return true;
  8787. }
  8788. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  8789. // get the "pointed to" types
  8790. const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  8791. const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  8792. if (!LHSOPT || !RHSOPT)
  8793. return false;
  8794. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  8795. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  8796. }
  8797. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  8798. return canAssignObjCInterfaces(
  8799. getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
  8800. getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
  8801. }
  8802. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  8803. /// both shall have the identically qualified version of a compatible type.
  8804. /// C99 6.2.7p1: Two types have compatible types if their types are the
  8805. /// same. See 6.7.[2,3,5] for additional rules.
  8806. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  8807. bool CompareUnqualified) {
  8808. if (getLangOpts().CPlusPlus)
  8809. return hasSameType(LHS, RHS);
  8810. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  8811. }
  8812. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  8813. return typesAreCompatible(LHS, RHS);
  8814. }
  8815. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  8816. return !mergeTypes(LHS, RHS, true).isNull();
  8817. }
  8818. /// mergeTransparentUnionType - if T is a transparent union type and a member
  8819. /// of T is compatible with SubType, return the merged type, else return
  8820. /// QualType()
  8821. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  8822. bool OfBlockPointer,
  8823. bool Unqualified) {
  8824. if (const RecordType *UT = T->getAsUnionType()) {
  8825. RecordDecl *UD = UT->getDecl();
  8826. if (UD->hasAttr<TransparentUnionAttr>()) {
  8827. for (const auto *I : UD->fields()) {
  8828. QualType ET = I->getType().getUnqualifiedType();
  8829. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  8830. if (!MT.isNull())
  8831. return MT;
  8832. }
  8833. }
  8834. }
  8835. return {};
  8836. }
  8837. /// mergeFunctionParameterTypes - merge two types which appear as function
  8838. /// parameter types
  8839. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  8840. bool OfBlockPointer,
  8841. bool Unqualified) {
  8842. // GNU extension: two types are compatible if they appear as a function
  8843. // argument, one of the types is a transparent union type and the other
  8844. // type is compatible with a union member
  8845. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  8846. Unqualified);
  8847. if (!lmerge.isNull())
  8848. return lmerge;
  8849. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  8850. Unqualified);
  8851. if (!rmerge.isNull())
  8852. return rmerge;
  8853. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  8854. }
  8855. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  8856. bool OfBlockPointer, bool Unqualified,
  8857. bool AllowCXX,
  8858. bool IsConditionalOperator) {
  8859. const auto *lbase = lhs->castAs<FunctionType>();
  8860. const auto *rbase = rhs->castAs<FunctionType>();
  8861. const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
  8862. const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
  8863. bool allLTypes = true;
  8864. bool allRTypes = true;
  8865. // Check return type
  8866. QualType retType;
  8867. if (OfBlockPointer) {
  8868. QualType RHS = rbase->getReturnType();
  8869. QualType LHS = lbase->getReturnType();
  8870. bool UnqualifiedResult = Unqualified;
  8871. if (!UnqualifiedResult)
  8872. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  8873. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  8874. }
  8875. else
  8876. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  8877. Unqualified);
  8878. if (retType.isNull())
  8879. return {};
  8880. if (Unqualified)
  8881. retType = retType.getUnqualifiedType();
  8882. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  8883. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  8884. if (Unqualified) {
  8885. LRetType = LRetType.getUnqualifiedType();
  8886. RRetType = RRetType.getUnqualifiedType();
  8887. }
  8888. if (getCanonicalType(retType) != LRetType)
  8889. allLTypes = false;
  8890. if (getCanonicalType(retType) != RRetType)
  8891. allRTypes = false;
  8892. // FIXME: double check this
  8893. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  8894. // rbase->getRegParmAttr() != 0 &&
  8895. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  8896. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  8897. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  8898. // Compatible functions must have compatible calling conventions
  8899. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  8900. return {};
  8901. // Regparm is part of the calling convention.
  8902. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  8903. return {};
  8904. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  8905. return {};
  8906. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  8907. return {};
  8908. if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
  8909. return {};
  8910. if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
  8911. return {};
  8912. // When merging declarations, it's common for supplemental information like
  8913. // attributes to only be present in one of the declarations, and we generally
  8914. // want type merging to preserve the union of information. So a merged
  8915. // function type should be noreturn if it was noreturn in *either* operand
  8916. // type.
  8917. //
  8918. // But for the conditional operator, this is backwards. The result of the
  8919. // operator could be either operand, and its type should conservatively
  8920. // reflect that. So a function type in a composite type is noreturn only
  8921. // if it's noreturn in *both* operand types.
  8922. //
  8923. // Arguably, noreturn is a kind of subtype, and the conditional operator
  8924. // ought to produce the most specific common supertype of its operand types.
  8925. // That would differ from this rule in contravariant positions. However,
  8926. // neither C nor C++ generally uses this kind of subtype reasoning. Also,
  8927. // as a practical matter, it would only affect C code that does abstraction of
  8928. // higher-order functions (taking noreturn callbacks!), which is uncommon to
  8929. // say the least. So we use the simpler rule.
  8930. bool NoReturn = IsConditionalOperator
  8931. ? lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()
  8932. : lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  8933. if (lbaseInfo.getNoReturn() != NoReturn)
  8934. allLTypes = false;
  8935. if (rbaseInfo.getNoReturn() != NoReturn)
  8936. allRTypes = false;
  8937. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  8938. if (lproto && rproto) { // two C99 style function prototypes
  8939. assert((AllowCXX ||
  8940. (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
  8941. "C++ shouldn't be here");
  8942. // Compatible functions must have the same number of parameters
  8943. if (lproto->getNumParams() != rproto->getNumParams())
  8944. return {};
  8945. // Variadic and non-variadic functions aren't compatible
  8946. if (lproto->isVariadic() != rproto->isVariadic())
  8947. return {};
  8948. if (lproto->getMethodQuals() != rproto->getMethodQuals())
  8949. return {};
  8950. SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
  8951. bool canUseLeft, canUseRight;
  8952. if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
  8953. newParamInfos))
  8954. return {};
  8955. if (!canUseLeft)
  8956. allLTypes = false;
  8957. if (!canUseRight)
  8958. allRTypes = false;
  8959. // Check parameter type compatibility
  8960. SmallVector<QualType, 10> types;
  8961. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  8962. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  8963. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  8964. QualType paramType = mergeFunctionParameterTypes(
  8965. lParamType, rParamType, OfBlockPointer, Unqualified);
  8966. if (paramType.isNull())
  8967. return {};
  8968. if (Unqualified)
  8969. paramType = paramType.getUnqualifiedType();
  8970. types.push_back(paramType);
  8971. if (Unqualified) {
  8972. lParamType = lParamType.getUnqualifiedType();
  8973. rParamType = rParamType.getUnqualifiedType();
  8974. }
  8975. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  8976. allLTypes = false;
  8977. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  8978. allRTypes = false;
  8979. }
  8980. if (allLTypes) return lhs;
  8981. if (allRTypes) return rhs;
  8982. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  8983. EPI.ExtInfo = einfo;
  8984. EPI.ExtParameterInfos =
  8985. newParamInfos.empty() ? nullptr : newParamInfos.data();
  8986. return getFunctionType(retType, types, EPI);
  8987. }
  8988. if (lproto) allRTypes = false;
  8989. if (rproto) allLTypes = false;
  8990. const FunctionProtoType *proto = lproto ? lproto : rproto;
  8991. if (proto) {
  8992. assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
  8993. if (proto->isVariadic())
  8994. return {};
  8995. // Check that the types are compatible with the types that
  8996. // would result from default argument promotions (C99 6.7.5.3p15).
  8997. // The only types actually affected are promotable integer
  8998. // types and floats, which would be passed as a different
  8999. // type depending on whether the prototype is visible.
  9000. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  9001. QualType paramTy = proto->getParamType(i);
  9002. // Look at the converted type of enum types, since that is the type used
  9003. // to pass enum values.
  9004. if (const auto *Enum = paramTy->getAs<EnumType>()) {
  9005. paramTy = Enum->getDecl()->getIntegerType();
  9006. if (paramTy.isNull())
  9007. return {};
  9008. }
  9009. if (isPromotableIntegerType(paramTy) ||
  9010. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  9011. return {};
  9012. }
  9013. if (allLTypes) return lhs;
  9014. if (allRTypes) return rhs;
  9015. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  9016. EPI.ExtInfo = einfo;
  9017. return getFunctionType(retType, proto->getParamTypes(), EPI);
  9018. }
  9019. if (allLTypes) return lhs;
  9020. if (allRTypes) return rhs;
  9021. return getFunctionNoProtoType(retType, einfo);
  9022. }
  9023. /// Given that we have an enum type and a non-enum type, try to merge them.
  9024. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  9025. QualType other, bool isBlockReturnType) {
  9026. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  9027. // a signed integer type, or an unsigned integer type.
  9028. // Compatibility is based on the underlying type, not the promotion
  9029. // type.
  9030. QualType underlyingType = ET->getDecl()->getIntegerType();
  9031. if (underlyingType.isNull())
  9032. return {};
  9033. if (Context.hasSameType(underlyingType, other))
  9034. return other;
  9035. // In block return types, we're more permissive and accept any
  9036. // integral type of the same size.
  9037. if (isBlockReturnType && other->isIntegerType() &&
  9038. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  9039. return other;
  9040. return {};
  9041. }
  9042. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, bool OfBlockPointer,
  9043. bool Unqualified, bool BlockReturnType,
  9044. bool IsConditionalOperator) {
  9045. // For C++ we will not reach this code with reference types (see below),
  9046. // for OpenMP variant call overloading we might.
  9047. //
  9048. // C++ [expr]: If an expression initially has the type "reference to T", the
  9049. // type is adjusted to "T" prior to any further analysis, the expression
  9050. // designates the object or function denoted by the reference, and the
  9051. // expression is an lvalue unless the reference is an rvalue reference and
  9052. // the expression is a function call (possibly inside parentheses).
  9053. auto *LHSRefTy = LHS->getAs<ReferenceType>();
  9054. auto *RHSRefTy = RHS->getAs<ReferenceType>();
  9055. if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
  9056. LHS->getTypeClass() == RHS->getTypeClass())
  9057. return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
  9058. OfBlockPointer, Unqualified, BlockReturnType);
  9059. if (LHSRefTy || RHSRefTy)
  9060. return {};
  9061. if (Unqualified) {
  9062. LHS = LHS.getUnqualifiedType();
  9063. RHS = RHS.getUnqualifiedType();
  9064. }
  9065. QualType LHSCan = getCanonicalType(LHS),
  9066. RHSCan = getCanonicalType(RHS);
  9067. // If two types are identical, they are compatible.
  9068. if (LHSCan == RHSCan)
  9069. return LHS;
  9070. // If the qualifiers are different, the types aren't compatible... mostly.
  9071. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  9072. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  9073. if (LQuals != RQuals) {
  9074. // If any of these qualifiers are different, we have a type
  9075. // mismatch.
  9076. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  9077. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  9078. LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
  9079. LQuals.hasUnaligned() != RQuals.hasUnaligned())
  9080. return {};
  9081. // Exactly one GC qualifier difference is allowed: __strong is
  9082. // okay if the other type has no GC qualifier but is an Objective
  9083. // C object pointer (i.e. implicitly strong by default). We fix
  9084. // this by pretending that the unqualified type was actually
  9085. // qualified __strong.
  9086. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  9087. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  9088. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  9089. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  9090. return {};
  9091. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  9092. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  9093. }
  9094. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  9095. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  9096. }
  9097. return {};
  9098. }
  9099. // Okay, qualifiers are equal.
  9100. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  9101. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  9102. // We want to consider the two function types to be the same for these
  9103. // comparisons, just force one to the other.
  9104. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  9105. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  9106. // Same as above for arrays
  9107. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  9108. LHSClass = Type::ConstantArray;
  9109. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  9110. RHSClass = Type::ConstantArray;
  9111. // ObjCInterfaces are just specialized ObjCObjects.
  9112. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  9113. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  9114. // Canonicalize ExtVector -> Vector.
  9115. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  9116. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  9117. // If the canonical type classes don't match.
  9118. if (LHSClass != RHSClass) {
  9119. // Note that we only have special rules for turning block enum
  9120. // returns into block int returns, not vice-versa.
  9121. if (const auto *ETy = LHS->getAs<EnumType>()) {
  9122. return mergeEnumWithInteger(*this, ETy, RHS, false);
  9123. }
  9124. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  9125. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  9126. }
  9127. // allow block pointer type to match an 'id' type.
  9128. if (OfBlockPointer && !BlockReturnType) {
  9129. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  9130. return LHS;
  9131. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  9132. return RHS;
  9133. }
  9134. // Allow __auto_type to match anything; it merges to the type with more
  9135. // information.
  9136. if (const auto *AT = LHS->getAs<AutoType>()) {
  9137. if (!AT->isDeduced() && AT->isGNUAutoType())
  9138. return RHS;
  9139. }
  9140. if (const auto *AT = RHS->getAs<AutoType>()) {
  9141. if (!AT->isDeduced() && AT->isGNUAutoType())
  9142. return LHS;
  9143. }
  9144. return {};
  9145. }
  9146. // The canonical type classes match.
  9147. switch (LHSClass) {
  9148. #define TYPE(Class, Base)
  9149. #define ABSTRACT_TYPE(Class, Base)
  9150. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  9151. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  9152. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  9153. #include "clang/AST/TypeNodes.inc"
  9154. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  9155. case Type::Auto:
  9156. case Type::DeducedTemplateSpecialization:
  9157. case Type::LValueReference:
  9158. case Type::RValueReference:
  9159. case Type::MemberPointer:
  9160. llvm_unreachable("C++ should never be in mergeTypes");
  9161. case Type::ObjCInterface:
  9162. case Type::IncompleteArray:
  9163. case Type::VariableArray:
  9164. case Type::FunctionProto:
  9165. case Type::ExtVector:
  9166. llvm_unreachable("Types are eliminated above");
  9167. case Type::Pointer:
  9168. {
  9169. // Merge two pointer types, while trying to preserve typedef info
  9170. QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
  9171. QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
  9172. if (Unqualified) {
  9173. LHSPointee = LHSPointee.getUnqualifiedType();
  9174. RHSPointee = RHSPointee.getUnqualifiedType();
  9175. }
  9176. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  9177. Unqualified);
  9178. if (ResultType.isNull())
  9179. return {};
  9180. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  9181. return LHS;
  9182. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  9183. return RHS;
  9184. return getPointerType(ResultType);
  9185. }
  9186. case Type::BlockPointer:
  9187. {
  9188. // Merge two block pointer types, while trying to preserve typedef info
  9189. QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
  9190. QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
  9191. if (Unqualified) {
  9192. LHSPointee = LHSPointee.getUnqualifiedType();
  9193. RHSPointee = RHSPointee.getUnqualifiedType();
  9194. }
  9195. if (getLangOpts().OpenCL) {
  9196. Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
  9197. Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
  9198. // Blocks can't be an expression in a ternary operator (OpenCL v2.0
  9199. // 6.12.5) thus the following check is asymmetric.
  9200. if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
  9201. return {};
  9202. LHSPteeQual.removeAddressSpace();
  9203. RHSPteeQual.removeAddressSpace();
  9204. LHSPointee =
  9205. QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
  9206. RHSPointee =
  9207. QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
  9208. }
  9209. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  9210. Unqualified);
  9211. if (ResultType.isNull())
  9212. return {};
  9213. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  9214. return LHS;
  9215. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  9216. return RHS;
  9217. return getBlockPointerType(ResultType);
  9218. }
  9219. case Type::Atomic:
  9220. {
  9221. // Merge two pointer types, while trying to preserve typedef info
  9222. QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
  9223. QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
  9224. if (Unqualified) {
  9225. LHSValue = LHSValue.getUnqualifiedType();
  9226. RHSValue = RHSValue.getUnqualifiedType();
  9227. }
  9228. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  9229. Unqualified);
  9230. if (ResultType.isNull())
  9231. return {};
  9232. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  9233. return LHS;
  9234. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  9235. return RHS;
  9236. return getAtomicType(ResultType);
  9237. }
  9238. case Type::ConstantArray:
  9239. {
  9240. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  9241. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  9242. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  9243. return {};
  9244. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  9245. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  9246. if (Unqualified) {
  9247. LHSElem = LHSElem.getUnqualifiedType();
  9248. RHSElem = RHSElem.getUnqualifiedType();
  9249. }
  9250. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  9251. if (ResultType.isNull())
  9252. return {};
  9253. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  9254. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  9255. // If either side is a variable array, and both are complete, check whether
  9256. // the current dimension is definite.
  9257. if (LVAT || RVAT) {
  9258. auto SizeFetch = [this](const VariableArrayType* VAT,
  9259. const ConstantArrayType* CAT)
  9260. -> std::pair<bool,llvm::APInt> {
  9261. if (VAT) {
  9262. std::optional<llvm::APSInt> TheInt;
  9263. Expr *E = VAT->getSizeExpr();
  9264. if (E && (TheInt = E->getIntegerConstantExpr(*this)))
  9265. return std::make_pair(true, *TheInt);
  9266. return std::make_pair(false, llvm::APSInt());
  9267. }
  9268. if (CAT)
  9269. return std::make_pair(true, CAT->getSize());
  9270. return std::make_pair(false, llvm::APInt());
  9271. };
  9272. bool HaveLSize, HaveRSize;
  9273. llvm::APInt LSize, RSize;
  9274. std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
  9275. std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
  9276. if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
  9277. return {}; // Definite, but unequal, array dimension
  9278. }
  9279. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  9280. return LHS;
  9281. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  9282. return RHS;
  9283. if (LCAT)
  9284. return getConstantArrayType(ResultType, LCAT->getSize(),
  9285. LCAT->getSizeExpr(),
  9286. ArrayType::ArraySizeModifier(), 0);
  9287. if (RCAT)
  9288. return getConstantArrayType(ResultType, RCAT->getSize(),
  9289. RCAT->getSizeExpr(),
  9290. ArrayType::ArraySizeModifier(), 0);
  9291. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  9292. return LHS;
  9293. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  9294. return RHS;
  9295. if (LVAT) {
  9296. // FIXME: This isn't correct! But tricky to implement because
  9297. // the array's size has to be the size of LHS, but the type
  9298. // has to be different.
  9299. return LHS;
  9300. }
  9301. if (RVAT) {
  9302. // FIXME: This isn't correct! But tricky to implement because
  9303. // the array's size has to be the size of RHS, but the type
  9304. // has to be different.
  9305. return RHS;
  9306. }
  9307. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  9308. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  9309. return getIncompleteArrayType(ResultType,
  9310. ArrayType::ArraySizeModifier(), 0);
  9311. }
  9312. case Type::FunctionNoProto:
  9313. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified,
  9314. /*AllowCXX=*/false, IsConditionalOperator);
  9315. case Type::Record:
  9316. case Type::Enum:
  9317. return {};
  9318. case Type::Builtin:
  9319. // Only exactly equal builtin types are compatible, which is tested above.
  9320. return {};
  9321. case Type::Complex:
  9322. // Distinct complex types are incompatible.
  9323. return {};
  9324. case Type::Vector:
  9325. // FIXME: The merged type should be an ExtVector!
  9326. if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
  9327. RHSCan->castAs<VectorType>()))
  9328. return LHS;
  9329. return {};
  9330. case Type::ConstantMatrix:
  9331. if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
  9332. RHSCan->castAs<ConstantMatrixType>()))
  9333. return LHS;
  9334. return {};
  9335. case Type::ObjCObject: {
  9336. // Check if the types are assignment compatible.
  9337. // FIXME: This should be type compatibility, e.g. whether
  9338. // "LHS x; RHS x;" at global scope is legal.
  9339. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
  9340. RHS->castAs<ObjCObjectType>()))
  9341. return LHS;
  9342. return {};
  9343. }
  9344. case Type::ObjCObjectPointer:
  9345. if (OfBlockPointer) {
  9346. if (canAssignObjCInterfacesInBlockPointer(
  9347. LHS->castAs<ObjCObjectPointerType>(),
  9348. RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
  9349. return LHS;
  9350. return {};
  9351. }
  9352. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
  9353. RHS->castAs<ObjCObjectPointerType>()))
  9354. return LHS;
  9355. return {};
  9356. case Type::Pipe:
  9357. assert(LHS != RHS &&
  9358. "Equivalent pipe types should have already been handled!");
  9359. return {};
  9360. case Type::BitInt: {
  9361. // Merge two bit-precise int types, while trying to preserve typedef info.
  9362. bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
  9363. bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
  9364. unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
  9365. unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
  9366. // Like unsigned/int, shouldn't have a type if they don't match.
  9367. if (LHSUnsigned != RHSUnsigned)
  9368. return {};
  9369. if (LHSBits != RHSBits)
  9370. return {};
  9371. return LHS;
  9372. }
  9373. }
  9374. llvm_unreachable("Invalid Type::Class!");
  9375. }
  9376. bool ASTContext::mergeExtParameterInfo(
  9377. const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
  9378. bool &CanUseFirst, bool &CanUseSecond,
  9379. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
  9380. assert(NewParamInfos.empty() && "param info list not empty");
  9381. CanUseFirst = CanUseSecond = true;
  9382. bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
  9383. bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
  9384. // Fast path: if the first type doesn't have ext parameter infos,
  9385. // we match if and only if the second type also doesn't have them.
  9386. if (!FirstHasInfo && !SecondHasInfo)
  9387. return true;
  9388. bool NeedParamInfo = false;
  9389. size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
  9390. : SecondFnType->getExtParameterInfos().size();
  9391. for (size_t I = 0; I < E; ++I) {
  9392. FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
  9393. if (FirstHasInfo)
  9394. FirstParam = FirstFnType->getExtParameterInfo(I);
  9395. if (SecondHasInfo)
  9396. SecondParam = SecondFnType->getExtParameterInfo(I);
  9397. // Cannot merge unless everything except the noescape flag matches.
  9398. if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
  9399. return false;
  9400. bool FirstNoEscape = FirstParam.isNoEscape();
  9401. bool SecondNoEscape = SecondParam.isNoEscape();
  9402. bool IsNoEscape = FirstNoEscape && SecondNoEscape;
  9403. NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
  9404. if (NewParamInfos.back().getOpaqueValue())
  9405. NeedParamInfo = true;
  9406. if (FirstNoEscape != IsNoEscape)
  9407. CanUseFirst = false;
  9408. if (SecondNoEscape != IsNoEscape)
  9409. CanUseSecond = false;
  9410. }
  9411. if (!NeedParamInfo)
  9412. NewParamInfos.clear();
  9413. return true;
  9414. }
  9415. void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
  9416. ObjCLayouts[CD] = nullptr;
  9417. }
  9418. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  9419. /// 'RHS' attributes and returns the merged version; including for function
  9420. /// return types.
  9421. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  9422. QualType LHSCan = getCanonicalType(LHS),
  9423. RHSCan = getCanonicalType(RHS);
  9424. // If two types are identical, they are compatible.
  9425. if (LHSCan == RHSCan)
  9426. return LHS;
  9427. if (RHSCan->isFunctionType()) {
  9428. if (!LHSCan->isFunctionType())
  9429. return {};
  9430. QualType OldReturnType =
  9431. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  9432. QualType NewReturnType =
  9433. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  9434. QualType ResReturnType =
  9435. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  9436. if (ResReturnType.isNull())
  9437. return {};
  9438. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  9439. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  9440. // In either case, use OldReturnType to build the new function type.
  9441. const auto *F = LHS->castAs<FunctionType>();
  9442. if (const auto *FPT = cast<FunctionProtoType>(F)) {
  9443. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9444. EPI.ExtInfo = getFunctionExtInfo(LHS);
  9445. QualType ResultType =
  9446. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
  9447. return ResultType;
  9448. }
  9449. }
  9450. return {};
  9451. }
  9452. // If the qualifiers are different, the types can still be merged.
  9453. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  9454. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  9455. if (LQuals != RQuals) {
  9456. // If any of these qualifiers are different, we have a type mismatch.
  9457. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  9458. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  9459. return {};
  9460. // Exactly one GC qualifier difference is allowed: __strong is
  9461. // okay if the other type has no GC qualifier but is an Objective
  9462. // C object pointer (i.e. implicitly strong by default). We fix
  9463. // this by pretending that the unqualified type was actually
  9464. // qualified __strong.
  9465. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  9466. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  9467. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  9468. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  9469. return {};
  9470. if (GC_L == Qualifiers::Strong)
  9471. return LHS;
  9472. if (GC_R == Qualifiers::Strong)
  9473. return RHS;
  9474. return {};
  9475. }
  9476. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  9477. QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  9478. QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  9479. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  9480. if (ResQT == LHSBaseQT)
  9481. return LHS;
  9482. if (ResQT == RHSBaseQT)
  9483. return RHS;
  9484. }
  9485. return {};
  9486. }
  9487. //===----------------------------------------------------------------------===//
  9488. // Integer Predicates
  9489. //===----------------------------------------------------------------------===//
  9490. unsigned ASTContext::getIntWidth(QualType T) const {
  9491. if (const auto *ET = T->getAs<EnumType>())
  9492. T = ET->getDecl()->getIntegerType();
  9493. if (T->isBooleanType())
  9494. return 1;
  9495. if (const auto *EIT = T->getAs<BitIntType>())
  9496. return EIT->getNumBits();
  9497. // For builtin types, just use the standard type sizing method
  9498. return (unsigned)getTypeSize(T);
  9499. }
  9500. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  9501. assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
  9502. T->isFixedPointType()) &&
  9503. "Unexpected type");
  9504. // Turn <4 x signed int> -> <4 x unsigned int>
  9505. if (const auto *VTy = T->getAs<VectorType>())
  9506. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  9507. VTy->getNumElements(), VTy->getVectorKind());
  9508. // For _BitInt, return an unsigned _BitInt with same width.
  9509. if (const auto *EITy = T->getAs<BitIntType>())
  9510. return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
  9511. // For enums, get the underlying integer type of the enum, and let the general
  9512. // integer type signchanging code handle it.
  9513. if (const auto *ETy = T->getAs<EnumType>())
  9514. T = ETy->getDecl()->getIntegerType();
  9515. switch (T->castAs<BuiltinType>()->getKind()) {
  9516. case BuiltinType::Char_U:
  9517. // Plain `char` is mapped to `unsigned char` even if it's already unsigned
  9518. case BuiltinType::Char_S:
  9519. case BuiltinType::SChar:
  9520. case BuiltinType::Char8:
  9521. return UnsignedCharTy;
  9522. case BuiltinType::Short:
  9523. return UnsignedShortTy;
  9524. case BuiltinType::Int:
  9525. return UnsignedIntTy;
  9526. case BuiltinType::Long:
  9527. return UnsignedLongTy;
  9528. case BuiltinType::LongLong:
  9529. return UnsignedLongLongTy;
  9530. case BuiltinType::Int128:
  9531. return UnsignedInt128Ty;
  9532. // wchar_t is special. It is either signed or not, but when it's signed,
  9533. // there's no matching "unsigned wchar_t". Therefore we return the unsigned
  9534. // version of its underlying type instead.
  9535. case BuiltinType::WChar_S:
  9536. return getUnsignedWCharType();
  9537. case BuiltinType::ShortAccum:
  9538. return UnsignedShortAccumTy;
  9539. case BuiltinType::Accum:
  9540. return UnsignedAccumTy;
  9541. case BuiltinType::LongAccum:
  9542. return UnsignedLongAccumTy;
  9543. case BuiltinType::SatShortAccum:
  9544. return SatUnsignedShortAccumTy;
  9545. case BuiltinType::SatAccum:
  9546. return SatUnsignedAccumTy;
  9547. case BuiltinType::SatLongAccum:
  9548. return SatUnsignedLongAccumTy;
  9549. case BuiltinType::ShortFract:
  9550. return UnsignedShortFractTy;
  9551. case BuiltinType::Fract:
  9552. return UnsignedFractTy;
  9553. case BuiltinType::LongFract:
  9554. return UnsignedLongFractTy;
  9555. case BuiltinType::SatShortFract:
  9556. return SatUnsignedShortFractTy;
  9557. case BuiltinType::SatFract:
  9558. return SatUnsignedFractTy;
  9559. case BuiltinType::SatLongFract:
  9560. return SatUnsignedLongFractTy;
  9561. default:
  9562. assert((T->hasUnsignedIntegerRepresentation() ||
  9563. T->isUnsignedFixedPointType()) &&
  9564. "Unexpected signed integer or fixed point type");
  9565. return T;
  9566. }
  9567. }
  9568. QualType ASTContext::getCorrespondingSignedType(QualType T) const {
  9569. assert((T->hasIntegerRepresentation() || T->isEnumeralType() ||
  9570. T->isFixedPointType()) &&
  9571. "Unexpected type");
  9572. // Turn <4 x unsigned int> -> <4 x signed int>
  9573. if (const auto *VTy = T->getAs<VectorType>())
  9574. return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
  9575. VTy->getNumElements(), VTy->getVectorKind());
  9576. // For _BitInt, return a signed _BitInt with same width.
  9577. if (const auto *EITy = T->getAs<BitIntType>())
  9578. return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
  9579. // For enums, get the underlying integer type of the enum, and let the general
  9580. // integer type signchanging code handle it.
  9581. if (const auto *ETy = T->getAs<EnumType>())
  9582. T = ETy->getDecl()->getIntegerType();
  9583. switch (T->castAs<BuiltinType>()->getKind()) {
  9584. case BuiltinType::Char_S:
  9585. // Plain `char` is mapped to `signed char` even if it's already signed
  9586. case BuiltinType::Char_U:
  9587. case BuiltinType::UChar:
  9588. case BuiltinType::Char8:
  9589. return SignedCharTy;
  9590. case BuiltinType::UShort:
  9591. return ShortTy;
  9592. case BuiltinType::UInt:
  9593. return IntTy;
  9594. case BuiltinType::ULong:
  9595. return LongTy;
  9596. case BuiltinType::ULongLong:
  9597. return LongLongTy;
  9598. case BuiltinType::UInt128:
  9599. return Int128Ty;
  9600. // wchar_t is special. It is either unsigned or not, but when it's unsigned,
  9601. // there's no matching "signed wchar_t". Therefore we return the signed
  9602. // version of its underlying type instead.
  9603. case BuiltinType::WChar_U:
  9604. return getSignedWCharType();
  9605. case BuiltinType::UShortAccum:
  9606. return ShortAccumTy;
  9607. case BuiltinType::UAccum:
  9608. return AccumTy;
  9609. case BuiltinType::ULongAccum:
  9610. return LongAccumTy;
  9611. case BuiltinType::SatUShortAccum:
  9612. return SatShortAccumTy;
  9613. case BuiltinType::SatUAccum:
  9614. return SatAccumTy;
  9615. case BuiltinType::SatULongAccum:
  9616. return SatLongAccumTy;
  9617. case BuiltinType::UShortFract:
  9618. return ShortFractTy;
  9619. case BuiltinType::UFract:
  9620. return FractTy;
  9621. case BuiltinType::ULongFract:
  9622. return LongFractTy;
  9623. case BuiltinType::SatUShortFract:
  9624. return SatShortFractTy;
  9625. case BuiltinType::SatUFract:
  9626. return SatFractTy;
  9627. case BuiltinType::SatULongFract:
  9628. return SatLongFractTy;
  9629. default:
  9630. assert(
  9631. (T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
  9632. "Unexpected signed integer or fixed point type");
  9633. return T;
  9634. }
  9635. }
  9636. ASTMutationListener::~ASTMutationListener() = default;
  9637. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  9638. QualType ReturnType) {}
  9639. //===----------------------------------------------------------------------===//
  9640. // Builtin Type Computation
  9641. //===----------------------------------------------------------------------===//
  9642. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  9643. /// pointer over the consumed characters. This returns the resultant type. If
  9644. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  9645. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  9646. /// a vector of "i*".
  9647. ///
  9648. /// RequiresICE is filled in on return to indicate whether the value is required
  9649. /// to be an Integer Constant Expression.
  9650. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  9651. ASTContext::GetBuiltinTypeError &Error,
  9652. bool &RequiresICE,
  9653. bool AllowTypeModifiers) {
  9654. // Modifiers.
  9655. int HowLong = 0;
  9656. bool Signed = false, Unsigned = false;
  9657. RequiresICE = false;
  9658. // Read the prefixed modifiers first.
  9659. bool Done = false;
  9660. #ifndef NDEBUG
  9661. bool IsSpecial = false;
  9662. #endif
  9663. while (!Done) {
  9664. switch (*Str++) {
  9665. default: Done = true; --Str; break;
  9666. case 'I':
  9667. RequiresICE = true;
  9668. break;
  9669. case 'S':
  9670. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  9671. assert(!Signed && "Can't use 'S' modifier multiple times!");
  9672. Signed = true;
  9673. break;
  9674. case 'U':
  9675. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  9676. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  9677. Unsigned = true;
  9678. break;
  9679. case 'L':
  9680. assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
  9681. assert(HowLong <= 2 && "Can't have LLLL modifier");
  9682. ++HowLong;
  9683. break;
  9684. case 'N':
  9685. // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
  9686. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9687. assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
  9688. #ifndef NDEBUG
  9689. IsSpecial = true;
  9690. #endif
  9691. if (Context.getTargetInfo().getLongWidth() == 32)
  9692. ++HowLong;
  9693. break;
  9694. case 'W':
  9695. // This modifier represents int64 type.
  9696. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9697. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  9698. #ifndef NDEBUG
  9699. IsSpecial = true;
  9700. #endif
  9701. switch (Context.getTargetInfo().getInt64Type()) {
  9702. default:
  9703. llvm_unreachable("Unexpected integer type");
  9704. case TargetInfo::SignedLong:
  9705. HowLong = 1;
  9706. break;
  9707. case TargetInfo::SignedLongLong:
  9708. HowLong = 2;
  9709. break;
  9710. }
  9711. break;
  9712. case 'Z':
  9713. // This modifier represents int32 type.
  9714. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9715. assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
  9716. #ifndef NDEBUG
  9717. IsSpecial = true;
  9718. #endif
  9719. switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
  9720. default:
  9721. llvm_unreachable("Unexpected integer type");
  9722. case TargetInfo::SignedInt:
  9723. HowLong = 0;
  9724. break;
  9725. case TargetInfo::SignedLong:
  9726. HowLong = 1;
  9727. break;
  9728. case TargetInfo::SignedLongLong:
  9729. HowLong = 2;
  9730. break;
  9731. }
  9732. break;
  9733. case 'O':
  9734. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9735. assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
  9736. #ifndef NDEBUG
  9737. IsSpecial = true;
  9738. #endif
  9739. if (Context.getLangOpts().OpenCL)
  9740. HowLong = 1;
  9741. else
  9742. HowLong = 2;
  9743. break;
  9744. }
  9745. }
  9746. QualType Type;
  9747. // Read the base type.
  9748. switch (*Str++) {
  9749. default: llvm_unreachable("Unknown builtin type letter!");
  9750. case 'x':
  9751. assert(HowLong == 0 && !Signed && !Unsigned &&
  9752. "Bad modifiers used with 'x'!");
  9753. Type = Context.Float16Ty;
  9754. break;
  9755. case 'y':
  9756. assert(HowLong == 0 && !Signed && !Unsigned &&
  9757. "Bad modifiers used with 'y'!");
  9758. Type = Context.BFloat16Ty;
  9759. break;
  9760. case 'v':
  9761. assert(HowLong == 0 && !Signed && !Unsigned &&
  9762. "Bad modifiers used with 'v'!");
  9763. Type = Context.VoidTy;
  9764. break;
  9765. case 'h':
  9766. assert(HowLong == 0 && !Signed && !Unsigned &&
  9767. "Bad modifiers used with 'h'!");
  9768. Type = Context.HalfTy;
  9769. break;
  9770. case 'f':
  9771. assert(HowLong == 0 && !Signed && !Unsigned &&
  9772. "Bad modifiers used with 'f'!");
  9773. Type = Context.FloatTy;
  9774. break;
  9775. case 'd':
  9776. assert(HowLong < 3 && !Signed && !Unsigned &&
  9777. "Bad modifiers used with 'd'!");
  9778. if (HowLong == 1)
  9779. Type = Context.LongDoubleTy;
  9780. else if (HowLong == 2)
  9781. Type = Context.Float128Ty;
  9782. else
  9783. Type = Context.DoubleTy;
  9784. break;
  9785. case 's':
  9786. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  9787. if (Unsigned)
  9788. Type = Context.UnsignedShortTy;
  9789. else
  9790. Type = Context.ShortTy;
  9791. break;
  9792. case 'i':
  9793. if (HowLong == 3)
  9794. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  9795. else if (HowLong == 2)
  9796. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  9797. else if (HowLong == 1)
  9798. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  9799. else
  9800. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  9801. break;
  9802. case 'c':
  9803. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  9804. if (Signed)
  9805. Type = Context.SignedCharTy;
  9806. else if (Unsigned)
  9807. Type = Context.UnsignedCharTy;
  9808. else
  9809. Type = Context.CharTy;
  9810. break;
  9811. case 'b': // boolean
  9812. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  9813. Type = Context.BoolTy;
  9814. break;
  9815. case 'z': // size_t.
  9816. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  9817. Type = Context.getSizeType();
  9818. break;
  9819. case 'w': // wchar_t.
  9820. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
  9821. Type = Context.getWideCharType();
  9822. break;
  9823. case 'F':
  9824. Type = Context.getCFConstantStringType();
  9825. break;
  9826. case 'G':
  9827. Type = Context.getObjCIdType();
  9828. break;
  9829. case 'H':
  9830. Type = Context.getObjCSelType();
  9831. break;
  9832. case 'M':
  9833. Type = Context.getObjCSuperType();
  9834. break;
  9835. case 'a':
  9836. Type = Context.getBuiltinVaListType();
  9837. assert(!Type.isNull() && "builtin va list type not initialized!");
  9838. break;
  9839. case 'A':
  9840. // This is a "reference" to a va_list; however, what exactly
  9841. // this means depends on how va_list is defined. There are two
  9842. // different kinds of va_list: ones passed by value, and ones
  9843. // passed by reference. An example of a by-value va_list is
  9844. // x86, where va_list is a char*. An example of by-ref va_list
  9845. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  9846. // we want this argument to be a char*&; for x86-64, we want
  9847. // it to be a __va_list_tag*.
  9848. Type = Context.getBuiltinVaListType();
  9849. assert(!Type.isNull() && "builtin va list type not initialized!");
  9850. if (Type->isArrayType())
  9851. Type = Context.getArrayDecayedType(Type);
  9852. else
  9853. Type = Context.getLValueReferenceType(Type);
  9854. break;
  9855. case 'q': {
  9856. char *End;
  9857. unsigned NumElements = strtoul(Str, &End, 10);
  9858. assert(End != Str && "Missing vector size");
  9859. Str = End;
  9860. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  9861. RequiresICE, false);
  9862. assert(!RequiresICE && "Can't require vector ICE");
  9863. Type = Context.getScalableVectorType(ElementType, NumElements);
  9864. break;
  9865. }
  9866. case 'V': {
  9867. char *End;
  9868. unsigned NumElements = strtoul(Str, &End, 10);
  9869. assert(End != Str && "Missing vector size");
  9870. Str = End;
  9871. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  9872. RequiresICE, false);
  9873. assert(!RequiresICE && "Can't require vector ICE");
  9874. // TODO: No way to make AltiVec vectors in builtins yet.
  9875. Type = Context.getVectorType(ElementType, NumElements,
  9876. VectorType::GenericVector);
  9877. break;
  9878. }
  9879. case 'E': {
  9880. char *End;
  9881. unsigned NumElements = strtoul(Str, &End, 10);
  9882. assert(End != Str && "Missing vector size");
  9883. Str = End;
  9884. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  9885. false);
  9886. Type = Context.getExtVectorType(ElementType, NumElements);
  9887. break;
  9888. }
  9889. case 'X': {
  9890. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  9891. false);
  9892. assert(!RequiresICE && "Can't require complex ICE");
  9893. Type = Context.getComplexType(ElementType);
  9894. break;
  9895. }
  9896. case 'Y':
  9897. Type = Context.getPointerDiffType();
  9898. break;
  9899. case 'P':
  9900. Type = Context.getFILEType();
  9901. if (Type.isNull()) {
  9902. Error = ASTContext::GE_Missing_stdio;
  9903. return {};
  9904. }
  9905. break;
  9906. case 'J':
  9907. if (Signed)
  9908. Type = Context.getsigjmp_bufType();
  9909. else
  9910. Type = Context.getjmp_bufType();
  9911. if (Type.isNull()) {
  9912. Error = ASTContext::GE_Missing_setjmp;
  9913. return {};
  9914. }
  9915. break;
  9916. case 'K':
  9917. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  9918. Type = Context.getucontext_tType();
  9919. if (Type.isNull()) {
  9920. Error = ASTContext::GE_Missing_ucontext;
  9921. return {};
  9922. }
  9923. break;
  9924. case 'p':
  9925. Type = Context.getProcessIDType();
  9926. break;
  9927. }
  9928. // If there are modifiers and if we're allowed to parse them, go for it.
  9929. Done = !AllowTypeModifiers;
  9930. while (!Done) {
  9931. switch (char c = *Str++) {
  9932. default: Done = true; --Str; break;
  9933. case '*':
  9934. case '&': {
  9935. // Both pointers and references can have their pointee types
  9936. // qualified with an address space.
  9937. char *End;
  9938. unsigned AddrSpace = strtoul(Str, &End, 10);
  9939. if (End != Str) {
  9940. // Note AddrSpace == 0 is not the same as an unspecified address space.
  9941. Type = Context.getAddrSpaceQualType(
  9942. Type,
  9943. Context.getLangASForBuiltinAddressSpace(AddrSpace));
  9944. Str = End;
  9945. }
  9946. if (c == '*')
  9947. Type = Context.getPointerType(Type);
  9948. else
  9949. Type = Context.getLValueReferenceType(Type);
  9950. break;
  9951. }
  9952. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  9953. case 'C':
  9954. Type = Type.withConst();
  9955. break;
  9956. case 'D':
  9957. Type = Context.getVolatileType(Type);
  9958. break;
  9959. case 'R':
  9960. Type = Type.withRestrict();
  9961. break;
  9962. }
  9963. }
  9964. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  9965. "Integer constant 'I' type must be an integer");
  9966. return Type;
  9967. }
  9968. // On some targets such as PowerPC, some of the builtins are defined with custom
  9969. // type descriptors for target-dependent types. These descriptors are decoded in
  9970. // other functions, but it may be useful to be able to fall back to default
  9971. // descriptor decoding to define builtins mixing target-dependent and target-
  9972. // independent types. This function allows decoding one type descriptor with
  9973. // default decoding.
  9974. QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
  9975. GetBuiltinTypeError &Error, bool &RequireICE,
  9976. bool AllowTypeModifiers) const {
  9977. return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
  9978. }
  9979. /// GetBuiltinType - Return the type for the specified builtin.
  9980. QualType ASTContext::GetBuiltinType(unsigned Id,
  9981. GetBuiltinTypeError &Error,
  9982. unsigned *IntegerConstantArgs) const {
  9983. const char *TypeStr = BuiltinInfo.getTypeString(Id);
  9984. if (TypeStr[0] == '\0') {
  9985. Error = GE_Missing_type;
  9986. return {};
  9987. }
  9988. SmallVector<QualType, 8> ArgTypes;
  9989. bool RequiresICE = false;
  9990. Error = GE_None;
  9991. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  9992. RequiresICE, true);
  9993. if (Error != GE_None)
  9994. return {};
  9995. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  9996. while (TypeStr[0] && TypeStr[0] != '.') {
  9997. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  9998. if (Error != GE_None)
  9999. return {};
  10000. // If this argument is required to be an IntegerConstantExpression and the
  10001. // caller cares, fill in the bitmask we return.
  10002. if (RequiresICE && IntegerConstantArgs)
  10003. *IntegerConstantArgs |= 1 << ArgTypes.size();
  10004. // Do array -> pointer decay. The builtin should use the decayed type.
  10005. if (Ty->isArrayType())
  10006. Ty = getArrayDecayedType(Ty);
  10007. ArgTypes.push_back(Ty);
  10008. }
  10009. if (Id == Builtin::BI__GetExceptionInfo)
  10010. return {};
  10011. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  10012. "'.' should only occur at end of builtin type list!");
  10013. bool Variadic = (TypeStr[0] == '.');
  10014. FunctionType::ExtInfo EI(getDefaultCallingConvention(
  10015. Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
  10016. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  10017. // We really shouldn't be making a no-proto type here.
  10018. if (ArgTypes.empty() && Variadic && !getLangOpts().requiresStrictPrototypes())
  10019. return getFunctionNoProtoType(ResType, EI);
  10020. FunctionProtoType::ExtProtoInfo EPI;
  10021. EPI.ExtInfo = EI;
  10022. EPI.Variadic = Variadic;
  10023. if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
  10024. EPI.ExceptionSpec.Type =
  10025. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  10026. return getFunctionType(ResType, ArgTypes, EPI);
  10027. }
  10028. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  10029. const FunctionDecl *FD) {
  10030. if (!FD->isExternallyVisible())
  10031. return GVA_Internal;
  10032. // Non-user-provided functions get emitted as weak definitions with every
  10033. // use, no matter whether they've been explicitly instantiated etc.
  10034. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  10035. if (!MD->isUserProvided())
  10036. return GVA_DiscardableODR;
  10037. GVALinkage External;
  10038. switch (FD->getTemplateSpecializationKind()) {
  10039. case TSK_Undeclared:
  10040. case TSK_ExplicitSpecialization:
  10041. External = GVA_StrongExternal;
  10042. break;
  10043. case TSK_ExplicitInstantiationDefinition:
  10044. return GVA_StrongODR;
  10045. // C++11 [temp.explicit]p10:
  10046. // [ Note: The intent is that an inline function that is the subject of
  10047. // an explicit instantiation declaration will still be implicitly
  10048. // instantiated when used so that the body can be considered for
  10049. // inlining, but that no out-of-line copy of the inline function would be
  10050. // generated in the translation unit. -- end note ]
  10051. case TSK_ExplicitInstantiationDeclaration:
  10052. return GVA_AvailableExternally;
  10053. case TSK_ImplicitInstantiation:
  10054. External = GVA_DiscardableODR;
  10055. break;
  10056. }
  10057. if (!FD->isInlined())
  10058. return External;
  10059. if ((!Context.getLangOpts().CPlusPlus &&
  10060. !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10061. !FD->hasAttr<DLLExportAttr>()) ||
  10062. FD->hasAttr<GNUInlineAttr>()) {
  10063. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  10064. // GNU or C99 inline semantics. Determine whether this symbol should be
  10065. // externally visible.
  10066. if (FD->isInlineDefinitionExternallyVisible())
  10067. return External;
  10068. // C99 inline semantics, where the symbol is not externally visible.
  10069. return GVA_AvailableExternally;
  10070. }
  10071. // Functions specified with extern and inline in -fms-compatibility mode
  10072. // forcibly get emitted. While the body of the function cannot be later
  10073. // replaced, the function definition cannot be discarded.
  10074. if (FD->isMSExternInline())
  10075. return GVA_StrongODR;
  10076. return GVA_DiscardableODR;
  10077. }
  10078. static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
  10079. const Decl *D, GVALinkage L) {
  10080. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  10081. // dllexport/dllimport on inline functions.
  10082. if (D->hasAttr<DLLImportAttr>()) {
  10083. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  10084. return GVA_AvailableExternally;
  10085. } else if (D->hasAttr<DLLExportAttr>()) {
  10086. if (L == GVA_DiscardableODR)
  10087. return GVA_StrongODR;
  10088. } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
  10089. // Device-side functions with __global__ attribute must always be
  10090. // visible externally so they can be launched from host.
  10091. if (D->hasAttr<CUDAGlobalAttr>() &&
  10092. (L == GVA_DiscardableODR || L == GVA_Internal))
  10093. return GVA_StrongODR;
  10094. // Single source offloading languages like CUDA/HIP need to be able to
  10095. // access static device variables from host code of the same compilation
  10096. // unit. This is done by externalizing the static variable with a shared
  10097. // name between the host and device compilation which is the same for the
  10098. // same compilation unit whereas different among different compilation
  10099. // units.
  10100. if (Context.shouldExternalize(D))
  10101. return GVA_StrongExternal;
  10102. }
  10103. return L;
  10104. }
  10105. /// Adjust the GVALinkage for a declaration based on what an external AST source
  10106. /// knows about whether there can be other definitions of this declaration.
  10107. static GVALinkage
  10108. adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
  10109. GVALinkage L) {
  10110. ExternalASTSource *Source = Ctx.getExternalSource();
  10111. if (!Source)
  10112. return L;
  10113. switch (Source->hasExternalDefinitions(D)) {
  10114. case ExternalASTSource::EK_Never:
  10115. // Other translation units rely on us to provide the definition.
  10116. if (L == GVA_DiscardableODR)
  10117. return GVA_StrongODR;
  10118. break;
  10119. case ExternalASTSource::EK_Always:
  10120. return GVA_AvailableExternally;
  10121. case ExternalASTSource::EK_ReplyHazy:
  10122. break;
  10123. }
  10124. return L;
  10125. }
  10126. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  10127. return adjustGVALinkageForExternalDefinitionKind(*this, FD,
  10128. adjustGVALinkageForAttributes(*this, FD,
  10129. basicGVALinkageForFunction(*this, FD)));
  10130. }
  10131. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  10132. const VarDecl *VD) {
  10133. if (!VD->isExternallyVisible())
  10134. return GVA_Internal;
  10135. if (VD->isStaticLocal()) {
  10136. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  10137. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  10138. LexicalContext = LexicalContext->getLexicalParent();
  10139. // ObjC Blocks can create local variables that don't have a FunctionDecl
  10140. // LexicalContext.
  10141. if (!LexicalContext)
  10142. return GVA_DiscardableODR;
  10143. // Otherwise, let the static local variable inherit its linkage from the
  10144. // nearest enclosing function.
  10145. auto StaticLocalLinkage =
  10146. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  10147. // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
  10148. // be emitted in any object with references to the symbol for the object it
  10149. // contains, whether inline or out-of-line."
  10150. // Similar behavior is observed with MSVC. An alternative ABI could use
  10151. // StrongODR/AvailableExternally to match the function, but none are
  10152. // known/supported currently.
  10153. if (StaticLocalLinkage == GVA_StrongODR ||
  10154. StaticLocalLinkage == GVA_AvailableExternally)
  10155. return GVA_DiscardableODR;
  10156. return StaticLocalLinkage;
  10157. }
  10158. // MSVC treats in-class initialized static data members as definitions.
  10159. // By giving them non-strong linkage, out-of-line definitions won't
  10160. // cause link errors.
  10161. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  10162. return GVA_DiscardableODR;
  10163. // Most non-template variables have strong linkage; inline variables are
  10164. // linkonce_odr or (occasionally, for compatibility) weak_odr.
  10165. GVALinkage StrongLinkage;
  10166. switch (Context.getInlineVariableDefinitionKind(VD)) {
  10167. case ASTContext::InlineVariableDefinitionKind::None:
  10168. StrongLinkage = GVA_StrongExternal;
  10169. break;
  10170. case ASTContext::InlineVariableDefinitionKind::Weak:
  10171. case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
  10172. StrongLinkage = GVA_DiscardableODR;
  10173. break;
  10174. case ASTContext::InlineVariableDefinitionKind::Strong:
  10175. StrongLinkage = GVA_StrongODR;
  10176. break;
  10177. }
  10178. switch (VD->getTemplateSpecializationKind()) {
  10179. case TSK_Undeclared:
  10180. return StrongLinkage;
  10181. case TSK_ExplicitSpecialization:
  10182. return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  10183. VD->isStaticDataMember()
  10184. ? GVA_StrongODR
  10185. : StrongLinkage;
  10186. case TSK_ExplicitInstantiationDefinition:
  10187. return GVA_StrongODR;
  10188. case TSK_ExplicitInstantiationDeclaration:
  10189. return GVA_AvailableExternally;
  10190. case TSK_ImplicitInstantiation:
  10191. return GVA_DiscardableODR;
  10192. }
  10193. llvm_unreachable("Invalid Linkage!");
  10194. }
  10195. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  10196. return adjustGVALinkageForExternalDefinitionKind(*this, VD,
  10197. adjustGVALinkageForAttributes(*this, VD,
  10198. basicGVALinkageForVariable(*this, VD)));
  10199. }
  10200. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  10201. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  10202. if (!VD->isFileVarDecl())
  10203. return false;
  10204. // Global named register variables (GNU extension) are never emitted.
  10205. if (VD->getStorageClass() == SC_Register)
  10206. return false;
  10207. if (VD->getDescribedVarTemplate() ||
  10208. isa<VarTemplatePartialSpecializationDecl>(VD))
  10209. return false;
  10210. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  10211. // We never need to emit an uninstantiated function template.
  10212. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10213. return false;
  10214. } else if (isa<PragmaCommentDecl>(D))
  10215. return true;
  10216. else if (isa<PragmaDetectMismatchDecl>(D))
  10217. return true;
  10218. else if (isa<OMPRequiresDecl>(D))
  10219. return true;
  10220. else if (isa<OMPThreadPrivateDecl>(D))
  10221. return !D->getDeclContext()->isDependentContext();
  10222. else if (isa<OMPAllocateDecl>(D))
  10223. return !D->getDeclContext()->isDependentContext();
  10224. else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
  10225. return !D->getDeclContext()->isDependentContext();
  10226. else if (isa<ImportDecl>(D))
  10227. return true;
  10228. else
  10229. return false;
  10230. // If this is a member of a class template, we do not need to emit it.
  10231. if (D->getDeclContext()->isDependentContext())
  10232. return false;
  10233. // Weak references don't produce any output by themselves.
  10234. if (D->hasAttr<WeakRefAttr>())
  10235. return false;
  10236. // Aliases and used decls are required.
  10237. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  10238. return true;
  10239. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  10240. // Forward declarations aren't required.
  10241. if (!FD->doesThisDeclarationHaveABody())
  10242. return FD->doesDeclarationForceExternallyVisibleDefinition();
  10243. // Constructors and destructors are required.
  10244. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  10245. return true;
  10246. // The key function for a class is required. This rule only comes
  10247. // into play when inline functions can be key functions, though.
  10248. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  10249. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  10250. const CXXRecordDecl *RD = MD->getParent();
  10251. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  10252. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  10253. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  10254. return true;
  10255. }
  10256. }
  10257. }
  10258. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  10259. // static, static inline, always_inline, and extern inline functions can
  10260. // always be deferred. Normal inline functions can be deferred in C99/C++.
  10261. // Implicit template instantiations can also be deferred in C++.
  10262. return !isDiscardableGVALinkage(Linkage);
  10263. }
  10264. const auto *VD = cast<VarDecl>(D);
  10265. assert(VD->isFileVarDecl() && "Expected file scoped var");
  10266. // If the decl is marked as `declare target to`, it should be emitted for the
  10267. // host and for the device.
  10268. if (LangOpts.OpenMP &&
  10269. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  10270. return true;
  10271. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  10272. !isMSStaticDataMemberInlineDefinition(VD))
  10273. return false;
  10274. // Variables that can be needed in other TUs are required.
  10275. auto Linkage = GetGVALinkageForVariable(VD);
  10276. if (!isDiscardableGVALinkage(Linkage))
  10277. return true;
  10278. // We never need to emit a variable that is available in another TU.
  10279. if (Linkage == GVA_AvailableExternally)
  10280. return false;
  10281. // Variables that have destruction with side-effects are required.
  10282. if (VD->needsDestruction(*this))
  10283. return true;
  10284. // Variables that have initialization with side-effects are required.
  10285. if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
  10286. // We can get a value-dependent initializer during error recovery.
  10287. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  10288. return true;
  10289. // Likewise, variables with tuple-like bindings are required if their
  10290. // bindings have side-effects.
  10291. if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
  10292. for (const auto *BD : DD->bindings())
  10293. if (const auto *BindingVD = BD->getHoldingVar())
  10294. if (DeclMustBeEmitted(BindingVD))
  10295. return true;
  10296. return false;
  10297. }
  10298. void ASTContext::forEachMultiversionedFunctionVersion(
  10299. const FunctionDecl *FD,
  10300. llvm::function_ref<void(FunctionDecl *)> Pred) const {
  10301. assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
  10302. llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
  10303. FD = FD->getMostRecentDecl();
  10304. // FIXME: The order of traversal here matters and depends on the order of
  10305. // lookup results, which happens to be (mostly) oldest-to-newest, but we
  10306. // shouldn't rely on that.
  10307. for (auto *CurDecl :
  10308. FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
  10309. FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
  10310. if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
  10311. !llvm::is_contained(SeenDecls, CurFD)) {
  10312. SeenDecls.insert(CurFD);
  10313. Pred(CurFD);
  10314. }
  10315. }
  10316. }
  10317. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  10318. bool IsCXXMethod,
  10319. bool IsBuiltin) const {
  10320. // Pass through to the C++ ABI object
  10321. if (IsCXXMethod)
  10322. return ABI->getDefaultMethodCallConv(IsVariadic);
  10323. // Builtins ignore user-specified default calling convention and remain the
  10324. // Target's default calling convention.
  10325. if (!IsBuiltin) {
  10326. switch (LangOpts.getDefaultCallingConv()) {
  10327. case LangOptions::DCC_None:
  10328. break;
  10329. case LangOptions::DCC_CDecl:
  10330. return CC_C;
  10331. case LangOptions::DCC_FastCall:
  10332. if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
  10333. return CC_X86FastCall;
  10334. break;
  10335. case LangOptions::DCC_StdCall:
  10336. if (!IsVariadic)
  10337. return CC_X86StdCall;
  10338. break;
  10339. case LangOptions::DCC_VectorCall:
  10340. // __vectorcall cannot be applied to variadic functions.
  10341. if (!IsVariadic)
  10342. return CC_X86VectorCall;
  10343. break;
  10344. case LangOptions::DCC_RegCall:
  10345. // __regcall cannot be applied to variadic functions.
  10346. if (!IsVariadic)
  10347. return CC_X86RegCall;
  10348. break;
  10349. }
  10350. }
  10351. return Target->getDefaultCallingConv();
  10352. }
  10353. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  10354. // Pass through to the C++ ABI object
  10355. return ABI->isNearlyEmpty(RD);
  10356. }
  10357. VTableContextBase *ASTContext::getVTableContext() {
  10358. if (!VTContext.get()) {
  10359. auto ABI = Target->getCXXABI();
  10360. if (ABI.isMicrosoft())
  10361. VTContext.reset(new MicrosoftVTableContext(*this));
  10362. else {
  10363. auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
  10364. ? ItaniumVTableContext::Relative
  10365. : ItaniumVTableContext::Pointer;
  10366. VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
  10367. }
  10368. }
  10369. return VTContext.get();
  10370. }
  10371. MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
  10372. if (!T)
  10373. T = Target;
  10374. switch (T->getCXXABI().getKind()) {
  10375. case TargetCXXABI::AppleARM64:
  10376. case TargetCXXABI::Fuchsia:
  10377. case TargetCXXABI::GenericAArch64:
  10378. case TargetCXXABI::GenericItanium:
  10379. case TargetCXXABI::GenericARM:
  10380. case TargetCXXABI::GenericMIPS:
  10381. case TargetCXXABI::iOS:
  10382. case TargetCXXABI::WebAssembly:
  10383. case TargetCXXABI::WatchOS:
  10384. case TargetCXXABI::XL:
  10385. return ItaniumMangleContext::create(*this, getDiagnostics());
  10386. case TargetCXXABI::Microsoft:
  10387. return MicrosoftMangleContext::create(*this, getDiagnostics());
  10388. }
  10389. llvm_unreachable("Unsupported ABI");
  10390. }
  10391. MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
  10392. assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
  10393. "Device mangle context does not support Microsoft mangling.");
  10394. switch (T.getCXXABI().getKind()) {
  10395. case TargetCXXABI::AppleARM64:
  10396. case TargetCXXABI::Fuchsia:
  10397. case TargetCXXABI::GenericAArch64:
  10398. case TargetCXXABI::GenericItanium:
  10399. case TargetCXXABI::GenericARM:
  10400. case TargetCXXABI::GenericMIPS:
  10401. case TargetCXXABI::iOS:
  10402. case TargetCXXABI::WebAssembly:
  10403. case TargetCXXABI::WatchOS:
  10404. case TargetCXXABI::XL:
  10405. return ItaniumMangleContext::create(
  10406. *this, getDiagnostics(),
  10407. [](ASTContext &, const NamedDecl *ND) -> std::optional<unsigned> {
  10408. if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
  10409. return RD->getDeviceLambdaManglingNumber();
  10410. return std::nullopt;
  10411. },
  10412. /*IsAux=*/true);
  10413. case TargetCXXABI::Microsoft:
  10414. return MicrosoftMangleContext::create(*this, getDiagnostics(),
  10415. /*IsAux=*/true);
  10416. }
  10417. llvm_unreachable("Unsupported ABI");
  10418. }
  10419. CXXABI::~CXXABI() = default;
  10420. size_t ASTContext::getSideTableAllocatedMemory() const {
  10421. return ASTRecordLayouts.getMemorySize() +
  10422. llvm::capacity_in_bytes(ObjCLayouts) +
  10423. llvm::capacity_in_bytes(KeyFunctions) +
  10424. llvm::capacity_in_bytes(ObjCImpls) +
  10425. llvm::capacity_in_bytes(BlockVarCopyInits) +
  10426. llvm::capacity_in_bytes(DeclAttrs) +
  10427. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  10428. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  10429. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  10430. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  10431. llvm::capacity_in_bytes(OverriddenMethods) +
  10432. llvm::capacity_in_bytes(Types) +
  10433. llvm::capacity_in_bytes(VariableArrayTypes);
  10434. }
  10435. /// getIntTypeForBitwidth -
  10436. /// sets integer QualTy according to specified details:
  10437. /// bitwidth, signed/unsigned.
  10438. /// Returns empty type if there is no appropriate target types.
  10439. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  10440. unsigned Signed) const {
  10441. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  10442. CanQualType QualTy = getFromTargetType(Ty);
  10443. if (!QualTy && DestWidth == 128)
  10444. return Signed ? Int128Ty : UnsignedInt128Ty;
  10445. return QualTy;
  10446. }
  10447. /// getRealTypeForBitwidth -
  10448. /// sets floating point QualTy according to specified bitwidth.
  10449. /// Returns empty type if there is no appropriate target types.
  10450. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
  10451. FloatModeKind ExplicitType) const {
  10452. FloatModeKind Ty =
  10453. getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
  10454. switch (Ty) {
  10455. case FloatModeKind::Half:
  10456. return HalfTy;
  10457. case FloatModeKind::Float:
  10458. return FloatTy;
  10459. case FloatModeKind::Double:
  10460. return DoubleTy;
  10461. case FloatModeKind::LongDouble:
  10462. return LongDoubleTy;
  10463. case FloatModeKind::Float128:
  10464. return Float128Ty;
  10465. case FloatModeKind::Ibm128:
  10466. return Ibm128Ty;
  10467. case FloatModeKind::NoFloat:
  10468. return {};
  10469. }
  10470. llvm_unreachable("Unhandled TargetInfo::RealType value");
  10471. }
  10472. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  10473. if (Number > 1)
  10474. MangleNumbers[ND] = Number;
  10475. }
  10476. unsigned ASTContext::getManglingNumber(const NamedDecl *ND,
  10477. bool ForAuxTarget) const {
  10478. auto I = MangleNumbers.find(ND);
  10479. unsigned Res = I != MangleNumbers.end() ? I->second : 1;
  10480. // CUDA/HIP host compilation encodes host and device mangling numbers
  10481. // as lower and upper half of 32 bit integer.
  10482. if (LangOpts.CUDA && !LangOpts.CUDAIsDevice) {
  10483. Res = ForAuxTarget ? Res >> 16 : Res & 0xFFFF;
  10484. } else {
  10485. assert(!ForAuxTarget && "Only CUDA/HIP host compilation supports mangling "
  10486. "number for aux target");
  10487. }
  10488. return Res > 1 ? Res : 1;
  10489. }
  10490. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  10491. if (Number > 1)
  10492. StaticLocalNumbers[VD] = Number;
  10493. }
  10494. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  10495. auto I = StaticLocalNumbers.find(VD);
  10496. return I != StaticLocalNumbers.end() ? I->second : 1;
  10497. }
  10498. MangleNumberingContext &
  10499. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  10500. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  10501. std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
  10502. if (!MCtx)
  10503. MCtx = createMangleNumberingContext();
  10504. return *MCtx;
  10505. }
  10506. MangleNumberingContext &
  10507. ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
  10508. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  10509. std::unique_ptr<MangleNumberingContext> &MCtx =
  10510. ExtraMangleNumberingContexts[D];
  10511. if (!MCtx)
  10512. MCtx = createMangleNumberingContext();
  10513. return *MCtx;
  10514. }
  10515. std::unique_ptr<MangleNumberingContext>
  10516. ASTContext::createMangleNumberingContext() const {
  10517. return ABI->createMangleNumberingContext();
  10518. }
  10519. const CXXConstructorDecl *
  10520. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  10521. return ABI->getCopyConstructorForExceptionObject(
  10522. cast<CXXRecordDecl>(RD->getFirstDecl()));
  10523. }
  10524. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  10525. CXXConstructorDecl *CD) {
  10526. return ABI->addCopyConstructorForExceptionObject(
  10527. cast<CXXRecordDecl>(RD->getFirstDecl()),
  10528. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  10529. }
  10530. void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
  10531. TypedefNameDecl *DD) {
  10532. return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
  10533. }
  10534. TypedefNameDecl *
  10535. ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
  10536. return ABI->getTypedefNameForUnnamedTagDecl(TD);
  10537. }
  10538. void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
  10539. DeclaratorDecl *DD) {
  10540. return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
  10541. }
  10542. DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
  10543. return ABI->getDeclaratorForUnnamedTagDecl(TD);
  10544. }
  10545. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  10546. ParamIndices[D] = index;
  10547. }
  10548. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  10549. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  10550. assert(I != ParamIndices.end() &&
  10551. "ParmIndices lacks entry set by ParmVarDecl");
  10552. return I->second;
  10553. }
  10554. QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
  10555. unsigned Length) const {
  10556. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  10557. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  10558. EltTy = EltTy.withConst();
  10559. EltTy = adjustStringLiteralBaseType(EltTy);
  10560. // Get an array type for the string, according to C99 6.4.5. This includes
  10561. // the null terminator character.
  10562. return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
  10563. ArrayType::Normal, /*IndexTypeQuals*/ 0);
  10564. }
  10565. StringLiteral *
  10566. ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
  10567. StringLiteral *&Result = StringLiteralCache[Key];
  10568. if (!Result)
  10569. Result = StringLiteral::Create(
  10570. *this, Key, StringLiteral::Ordinary,
  10571. /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
  10572. SourceLocation());
  10573. return Result;
  10574. }
  10575. MSGuidDecl *
  10576. ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
  10577. assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
  10578. llvm::FoldingSetNodeID ID;
  10579. MSGuidDecl::Profile(ID, Parts);
  10580. void *InsertPos;
  10581. if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
  10582. return Existing;
  10583. QualType GUIDType = getMSGuidType().withConst();
  10584. MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
  10585. MSGuidDecls.InsertNode(New, InsertPos);
  10586. return New;
  10587. }
  10588. UnnamedGlobalConstantDecl *
  10589. ASTContext::getUnnamedGlobalConstantDecl(QualType Ty,
  10590. const APValue &APVal) const {
  10591. llvm::FoldingSetNodeID ID;
  10592. UnnamedGlobalConstantDecl::Profile(ID, Ty, APVal);
  10593. void *InsertPos;
  10594. if (UnnamedGlobalConstantDecl *Existing =
  10595. UnnamedGlobalConstantDecls.FindNodeOrInsertPos(ID, InsertPos))
  10596. return Existing;
  10597. UnnamedGlobalConstantDecl *New =
  10598. UnnamedGlobalConstantDecl::Create(*this, Ty, APVal);
  10599. UnnamedGlobalConstantDecls.InsertNode(New, InsertPos);
  10600. return New;
  10601. }
  10602. TemplateParamObjectDecl *
  10603. ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
  10604. assert(T->isRecordType() && "template param object of unexpected type");
  10605. // C++ [temp.param]p8:
  10606. // [...] a static storage duration object of type 'const T' [...]
  10607. T.addConst();
  10608. llvm::FoldingSetNodeID ID;
  10609. TemplateParamObjectDecl::Profile(ID, T, V);
  10610. void *InsertPos;
  10611. if (TemplateParamObjectDecl *Existing =
  10612. TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
  10613. return Existing;
  10614. TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
  10615. TemplateParamObjectDecls.InsertNode(New, InsertPos);
  10616. return New;
  10617. }
  10618. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  10619. const llvm::Triple &T = getTargetInfo().getTriple();
  10620. if (!T.isOSDarwin())
  10621. return false;
  10622. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  10623. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  10624. return false;
  10625. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  10626. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  10627. uint64_t Size = sizeChars.getQuantity();
  10628. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  10629. unsigned Align = alignChars.getQuantity();
  10630. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  10631. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  10632. }
  10633. bool
  10634. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  10635. const ObjCMethodDecl *MethodImpl) {
  10636. // No point trying to match an unavailable/deprecated mothod.
  10637. if (MethodDecl->hasAttr<UnavailableAttr>()
  10638. || MethodDecl->hasAttr<DeprecatedAttr>())
  10639. return false;
  10640. if (MethodDecl->getObjCDeclQualifier() !=
  10641. MethodImpl->getObjCDeclQualifier())
  10642. return false;
  10643. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  10644. return false;
  10645. if (MethodDecl->param_size() != MethodImpl->param_size())
  10646. return false;
  10647. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  10648. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  10649. EF = MethodDecl->param_end();
  10650. IM != EM && IF != EF; ++IM, ++IF) {
  10651. const ParmVarDecl *DeclVar = (*IF);
  10652. const ParmVarDecl *ImplVar = (*IM);
  10653. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  10654. return false;
  10655. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  10656. return false;
  10657. }
  10658. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  10659. }
  10660. uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
  10661. LangAS AS;
  10662. if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
  10663. AS = LangAS::Default;
  10664. else
  10665. AS = QT->getPointeeType().getAddressSpace();
  10666. return getTargetInfo().getNullPointerValue(AS);
  10667. }
  10668. unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
  10669. return getTargetInfo().getTargetAddressSpace(AS);
  10670. }
  10671. bool ASTContext::hasSameExpr(const Expr *X, const Expr *Y) const {
  10672. if (X == Y)
  10673. return true;
  10674. if (!X || !Y)
  10675. return false;
  10676. llvm::FoldingSetNodeID IDX, IDY;
  10677. X->Profile(IDX, *this, /*Canonical=*/true);
  10678. Y->Profile(IDY, *this, /*Canonical=*/true);
  10679. return IDX == IDY;
  10680. }
  10681. // The getCommon* helpers return, for given 'same' X and Y entities given as
  10682. // inputs, another entity which is also the 'same' as the inputs, but which
  10683. // is closer to the canonical form of the inputs, each according to a given
  10684. // criteria.
  10685. // The getCommon*Checked variants are 'null inputs not-allowed' equivalents of
  10686. // the regular ones.
  10687. static Decl *getCommonDecl(Decl *X, Decl *Y) {
  10688. if (!declaresSameEntity(X, Y))
  10689. return nullptr;
  10690. for (const Decl *DX : X->redecls()) {
  10691. // If we reach Y before reaching the first decl, that means X is older.
  10692. if (DX == Y)
  10693. return X;
  10694. // If we reach the first decl, then Y is older.
  10695. if (DX->isFirstDecl())
  10696. return Y;
  10697. }
  10698. llvm_unreachable("Corrupt redecls chain");
  10699. }
  10700. template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
  10701. static T *getCommonDecl(T *X, T *Y) {
  10702. return cast_or_null<T>(
  10703. getCommonDecl(const_cast<Decl *>(cast_or_null<Decl>(X)),
  10704. const_cast<Decl *>(cast_or_null<Decl>(Y))));
  10705. }
  10706. template <class T, std::enable_if_t<std::is_base_of_v<Decl, T>, bool> = true>
  10707. static T *getCommonDeclChecked(T *X, T *Y) {
  10708. return cast<T>(getCommonDecl(const_cast<Decl *>(cast<Decl>(X)),
  10709. const_cast<Decl *>(cast<Decl>(Y))));
  10710. }
  10711. static TemplateName getCommonTemplateName(ASTContext &Ctx, TemplateName X,
  10712. TemplateName Y) {
  10713. if (X.getAsVoidPointer() == Y.getAsVoidPointer())
  10714. return X;
  10715. // FIXME: There are cases here where we could find a common template name
  10716. // with more sugar. For example one could be a SubstTemplateTemplate*
  10717. // replacing the other.
  10718. TemplateName CX = Ctx.getCanonicalTemplateName(X);
  10719. if (CX.getAsVoidPointer() !=
  10720. Ctx.getCanonicalTemplateName(Y).getAsVoidPointer())
  10721. return TemplateName();
  10722. return CX;
  10723. }
  10724. static TemplateName
  10725. getCommonTemplateNameChecked(ASTContext &Ctx, TemplateName X, TemplateName Y) {
  10726. TemplateName R = getCommonTemplateName(Ctx, X, Y);
  10727. assert(R.getAsVoidPointer() != nullptr);
  10728. return R;
  10729. }
  10730. static auto getCommonTypes(ASTContext &Ctx, ArrayRef<QualType> Xs,
  10731. ArrayRef<QualType> Ys, bool Unqualified = false) {
  10732. assert(Xs.size() == Ys.size());
  10733. SmallVector<QualType, 8> Rs(Xs.size());
  10734. for (size_t I = 0; I < Rs.size(); ++I)
  10735. Rs[I] = Ctx.getCommonSugaredType(Xs[I], Ys[I], Unqualified);
  10736. return Rs;
  10737. }
  10738. template <class T>
  10739. static SourceLocation getCommonAttrLoc(const T *X, const T *Y) {
  10740. return X->getAttributeLoc() == Y->getAttributeLoc() ? X->getAttributeLoc()
  10741. : SourceLocation();
  10742. }
  10743. static TemplateArgument getCommonTemplateArgument(ASTContext &Ctx,
  10744. const TemplateArgument &X,
  10745. const TemplateArgument &Y) {
  10746. if (X.getKind() != Y.getKind())
  10747. return TemplateArgument();
  10748. switch (X.getKind()) {
  10749. case TemplateArgument::ArgKind::Type:
  10750. if (!Ctx.hasSameType(X.getAsType(), Y.getAsType()))
  10751. return TemplateArgument();
  10752. return TemplateArgument(
  10753. Ctx.getCommonSugaredType(X.getAsType(), Y.getAsType()));
  10754. case TemplateArgument::ArgKind::NullPtr:
  10755. if (!Ctx.hasSameType(X.getNullPtrType(), Y.getNullPtrType()))
  10756. return TemplateArgument();
  10757. return TemplateArgument(
  10758. Ctx.getCommonSugaredType(X.getNullPtrType(), Y.getNullPtrType()),
  10759. /*Unqualified=*/true);
  10760. case TemplateArgument::ArgKind::Expression:
  10761. if (!Ctx.hasSameType(X.getAsExpr()->getType(), Y.getAsExpr()->getType()))
  10762. return TemplateArgument();
  10763. // FIXME: Try to keep the common sugar.
  10764. return X;
  10765. case TemplateArgument::ArgKind::Template: {
  10766. TemplateName TX = X.getAsTemplate(), TY = Y.getAsTemplate();
  10767. TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
  10768. if (!CTN.getAsVoidPointer())
  10769. return TemplateArgument();
  10770. return TemplateArgument(CTN);
  10771. }
  10772. case TemplateArgument::ArgKind::TemplateExpansion: {
  10773. TemplateName TX = X.getAsTemplateOrTemplatePattern(),
  10774. TY = Y.getAsTemplateOrTemplatePattern();
  10775. TemplateName CTN = ::getCommonTemplateName(Ctx, TX, TY);
  10776. if (!CTN.getAsVoidPointer())
  10777. return TemplateName();
  10778. auto NExpX = X.getNumTemplateExpansions();
  10779. assert(NExpX == Y.getNumTemplateExpansions());
  10780. return TemplateArgument(CTN, NExpX);
  10781. }
  10782. default:
  10783. // FIXME: Handle the other argument kinds.
  10784. return X;
  10785. }
  10786. }
  10787. static bool getCommonTemplateArguments(ASTContext &Ctx,
  10788. SmallVectorImpl<TemplateArgument> &R,
  10789. ArrayRef<TemplateArgument> Xs,
  10790. ArrayRef<TemplateArgument> Ys) {
  10791. if (Xs.size() != Ys.size())
  10792. return true;
  10793. R.resize(Xs.size());
  10794. for (size_t I = 0; I < R.size(); ++I) {
  10795. R[I] = getCommonTemplateArgument(Ctx, Xs[I], Ys[I]);
  10796. if (R[I].isNull())
  10797. return true;
  10798. }
  10799. return false;
  10800. }
  10801. static auto getCommonTemplateArguments(ASTContext &Ctx,
  10802. ArrayRef<TemplateArgument> Xs,
  10803. ArrayRef<TemplateArgument> Ys) {
  10804. SmallVector<TemplateArgument, 8> R;
  10805. bool Different = getCommonTemplateArguments(Ctx, R, Xs, Ys);
  10806. assert(!Different);
  10807. (void)Different;
  10808. return R;
  10809. }
  10810. template <class T>
  10811. static ElaboratedTypeKeyword getCommonTypeKeyword(const T *X, const T *Y) {
  10812. return X->getKeyword() == Y->getKeyword() ? X->getKeyword()
  10813. : ElaboratedTypeKeyword::ETK_None;
  10814. }
  10815. template <class T>
  10816. static NestedNameSpecifier *getCommonNNS(ASTContext &Ctx, const T *X,
  10817. const T *Y) {
  10818. // FIXME: Try to keep the common NNS sugar.
  10819. return X->getQualifier() == Y->getQualifier()
  10820. ? X->getQualifier()
  10821. : Ctx.getCanonicalNestedNameSpecifier(X->getQualifier());
  10822. }
  10823. template <class T>
  10824. static QualType getCommonElementType(ASTContext &Ctx, const T *X, const T *Y) {
  10825. return Ctx.getCommonSugaredType(X->getElementType(), Y->getElementType());
  10826. }
  10827. template <class T>
  10828. static QualType getCommonArrayElementType(ASTContext &Ctx, const T *X,
  10829. Qualifiers &QX, const T *Y,
  10830. Qualifiers &QY) {
  10831. QualType EX = X->getElementType(), EY = Y->getElementType();
  10832. QualType R = Ctx.getCommonSugaredType(EX, EY,
  10833. /*Unqualified=*/true);
  10834. Qualifiers RQ = R.getQualifiers();
  10835. QX += EX.getQualifiers() - RQ;
  10836. QY += EY.getQualifiers() - RQ;
  10837. return R;
  10838. }
  10839. template <class T>
  10840. static QualType getCommonPointeeType(ASTContext &Ctx, const T *X, const T *Y) {
  10841. return Ctx.getCommonSugaredType(X->getPointeeType(), Y->getPointeeType());
  10842. }
  10843. template <class T> static auto *getCommonSizeExpr(ASTContext &Ctx, T *X, T *Y) {
  10844. assert(Ctx.hasSameExpr(X->getSizeExpr(), Y->getSizeExpr()));
  10845. return X->getSizeExpr();
  10846. }
  10847. static auto getCommonSizeModifier(const ArrayType *X, const ArrayType *Y) {
  10848. assert(X->getSizeModifier() == Y->getSizeModifier());
  10849. return X->getSizeModifier();
  10850. }
  10851. static auto getCommonIndexTypeCVRQualifiers(const ArrayType *X,
  10852. const ArrayType *Y) {
  10853. assert(X->getIndexTypeCVRQualifiers() == Y->getIndexTypeCVRQualifiers());
  10854. return X->getIndexTypeCVRQualifiers();
  10855. }
  10856. // Merges two type lists such that the resulting vector will contain
  10857. // each type (in a canonical sense) only once, in the order they appear
  10858. // from X to Y. If they occur in both X and Y, the result will contain
  10859. // the common sugared type between them.
  10860. static void mergeTypeLists(ASTContext &Ctx, SmallVectorImpl<QualType> &Out,
  10861. ArrayRef<QualType> X, ArrayRef<QualType> Y) {
  10862. llvm::DenseMap<QualType, unsigned> Found;
  10863. for (auto Ts : {X, Y}) {
  10864. for (QualType T : Ts) {
  10865. auto Res = Found.try_emplace(Ctx.getCanonicalType(T), Out.size());
  10866. if (!Res.second) {
  10867. QualType &U = Out[Res.first->second];
  10868. U = Ctx.getCommonSugaredType(U, T);
  10869. } else {
  10870. Out.emplace_back(T);
  10871. }
  10872. }
  10873. }
  10874. }
  10875. FunctionProtoType::ExceptionSpecInfo
  10876. ASTContext::mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
  10877. FunctionProtoType::ExceptionSpecInfo ESI2,
  10878. SmallVectorImpl<QualType> &ExceptionTypeStorage,
  10879. bool AcceptDependent) {
  10880. ExceptionSpecificationType EST1 = ESI1.Type, EST2 = ESI2.Type;
  10881. // If either of them can throw anything, that is the result.
  10882. for (auto I : {EST_None, EST_MSAny, EST_NoexceptFalse}) {
  10883. if (EST1 == I)
  10884. return ESI1;
  10885. if (EST2 == I)
  10886. return ESI2;
  10887. }
  10888. // If either of them is non-throwing, the result is the other.
  10889. for (auto I :
  10890. {EST_NoThrow, EST_DynamicNone, EST_BasicNoexcept, EST_NoexceptTrue}) {
  10891. if (EST1 == I)
  10892. return ESI2;
  10893. if (EST2 == I)
  10894. return ESI1;
  10895. }
  10896. // If we're left with value-dependent computed noexcept expressions, we're
  10897. // stuck. Before C++17, we can just drop the exception specification entirely,
  10898. // since it's not actually part of the canonical type. And this should never
  10899. // happen in C++17, because it would mean we were computing the composite
  10900. // pointer type of dependent types, which should never happen.
  10901. if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
  10902. assert(AcceptDependent &&
  10903. "computing composite pointer type of dependent types");
  10904. return FunctionProtoType::ExceptionSpecInfo();
  10905. }
  10906. // Switch over the possibilities so that people adding new values know to
  10907. // update this function.
  10908. switch (EST1) {
  10909. case EST_None:
  10910. case EST_DynamicNone:
  10911. case EST_MSAny:
  10912. case EST_BasicNoexcept:
  10913. case EST_DependentNoexcept:
  10914. case EST_NoexceptFalse:
  10915. case EST_NoexceptTrue:
  10916. case EST_NoThrow:
  10917. llvm_unreachable("These ESTs should be handled above");
  10918. case EST_Dynamic: {
  10919. // This is the fun case: both exception specifications are dynamic. Form
  10920. // the union of the two lists.
  10921. assert(EST2 == EST_Dynamic && "other cases should already be handled");
  10922. mergeTypeLists(*this, ExceptionTypeStorage, ESI1.Exceptions,
  10923. ESI2.Exceptions);
  10924. FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
  10925. Result.Exceptions = ExceptionTypeStorage;
  10926. return Result;
  10927. }
  10928. case EST_Unevaluated:
  10929. case EST_Uninstantiated:
  10930. case EST_Unparsed:
  10931. llvm_unreachable("shouldn't see unresolved exception specifications here");
  10932. }
  10933. llvm_unreachable("invalid ExceptionSpecificationType");
  10934. }
  10935. static QualType getCommonNonSugarTypeNode(ASTContext &Ctx, const Type *X,
  10936. Qualifiers &QX, const Type *Y,
  10937. Qualifiers &QY) {
  10938. Type::TypeClass TC = X->getTypeClass();
  10939. assert(TC == Y->getTypeClass());
  10940. switch (TC) {
  10941. #define UNEXPECTED_TYPE(Class, Kind) \
  10942. case Type::Class: \
  10943. llvm_unreachable("Unexpected " Kind ": " #Class);
  10944. #define NON_CANONICAL_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "non-canonical")
  10945. #define TYPE(Class, Base)
  10946. #include "clang/AST/TypeNodes.inc"
  10947. #define SUGAR_FREE_TYPE(Class) UNEXPECTED_TYPE(Class, "sugar-free")
  10948. SUGAR_FREE_TYPE(Builtin)
  10949. SUGAR_FREE_TYPE(Decltype)
  10950. SUGAR_FREE_TYPE(DeducedTemplateSpecialization)
  10951. SUGAR_FREE_TYPE(DependentBitInt)
  10952. SUGAR_FREE_TYPE(Enum)
  10953. SUGAR_FREE_TYPE(BitInt)
  10954. SUGAR_FREE_TYPE(ObjCInterface)
  10955. SUGAR_FREE_TYPE(Record)
  10956. SUGAR_FREE_TYPE(SubstTemplateTypeParmPack)
  10957. SUGAR_FREE_TYPE(UnresolvedUsing)
  10958. #undef SUGAR_FREE_TYPE
  10959. #define NON_UNIQUE_TYPE(Class) UNEXPECTED_TYPE(Class, "non-unique")
  10960. NON_UNIQUE_TYPE(TypeOfExpr)
  10961. NON_UNIQUE_TYPE(VariableArray)
  10962. #undef NON_UNIQUE_TYPE
  10963. UNEXPECTED_TYPE(TypeOf, "sugar")
  10964. #undef UNEXPECTED_TYPE
  10965. case Type::Auto: {
  10966. const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
  10967. assert(AX->getDeducedType().isNull());
  10968. assert(AY->getDeducedType().isNull());
  10969. assert(AX->getKeyword() == AY->getKeyword());
  10970. assert(AX->isInstantiationDependentType() ==
  10971. AY->isInstantiationDependentType());
  10972. auto As = getCommonTemplateArguments(Ctx, AX->getTypeConstraintArguments(),
  10973. AY->getTypeConstraintArguments());
  10974. return Ctx.getAutoType(QualType(), AX->getKeyword(),
  10975. AX->isInstantiationDependentType(),
  10976. AX->containsUnexpandedParameterPack(),
  10977. getCommonDeclChecked(AX->getTypeConstraintConcept(),
  10978. AY->getTypeConstraintConcept()),
  10979. As);
  10980. }
  10981. case Type::IncompleteArray: {
  10982. const auto *AX = cast<IncompleteArrayType>(X),
  10983. *AY = cast<IncompleteArrayType>(Y);
  10984. return Ctx.getIncompleteArrayType(
  10985. getCommonArrayElementType(Ctx, AX, QX, AY, QY),
  10986. getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
  10987. }
  10988. case Type::DependentSizedArray: {
  10989. const auto *AX = cast<DependentSizedArrayType>(X),
  10990. *AY = cast<DependentSizedArrayType>(Y);
  10991. return Ctx.getDependentSizedArrayType(
  10992. getCommonArrayElementType(Ctx, AX, QX, AY, QY),
  10993. getCommonSizeExpr(Ctx, AX, AY), getCommonSizeModifier(AX, AY),
  10994. getCommonIndexTypeCVRQualifiers(AX, AY),
  10995. AX->getBracketsRange() == AY->getBracketsRange()
  10996. ? AX->getBracketsRange()
  10997. : SourceRange());
  10998. }
  10999. case Type::ConstantArray: {
  11000. const auto *AX = cast<ConstantArrayType>(X),
  11001. *AY = cast<ConstantArrayType>(Y);
  11002. assert(AX->getSize() == AY->getSize());
  11003. const Expr *SizeExpr = Ctx.hasSameExpr(AX->getSizeExpr(), AY->getSizeExpr())
  11004. ? AX->getSizeExpr()
  11005. : nullptr;
  11006. return Ctx.getConstantArrayType(
  11007. getCommonArrayElementType(Ctx, AX, QX, AY, QY), AX->getSize(), SizeExpr,
  11008. getCommonSizeModifier(AX, AY), getCommonIndexTypeCVRQualifiers(AX, AY));
  11009. }
  11010. case Type::Atomic: {
  11011. const auto *AX = cast<AtomicType>(X), *AY = cast<AtomicType>(Y);
  11012. return Ctx.getAtomicType(
  11013. Ctx.getCommonSugaredType(AX->getValueType(), AY->getValueType()));
  11014. }
  11015. case Type::Complex: {
  11016. const auto *CX = cast<ComplexType>(X), *CY = cast<ComplexType>(Y);
  11017. return Ctx.getComplexType(getCommonArrayElementType(Ctx, CX, QX, CY, QY));
  11018. }
  11019. case Type::Pointer: {
  11020. const auto *PX = cast<PointerType>(X), *PY = cast<PointerType>(Y);
  11021. return Ctx.getPointerType(getCommonPointeeType(Ctx, PX, PY));
  11022. }
  11023. case Type::BlockPointer: {
  11024. const auto *PX = cast<BlockPointerType>(X), *PY = cast<BlockPointerType>(Y);
  11025. return Ctx.getBlockPointerType(getCommonPointeeType(Ctx, PX, PY));
  11026. }
  11027. case Type::ObjCObjectPointer: {
  11028. const auto *PX = cast<ObjCObjectPointerType>(X),
  11029. *PY = cast<ObjCObjectPointerType>(Y);
  11030. return Ctx.getObjCObjectPointerType(getCommonPointeeType(Ctx, PX, PY));
  11031. }
  11032. case Type::MemberPointer: {
  11033. const auto *PX = cast<MemberPointerType>(X),
  11034. *PY = cast<MemberPointerType>(Y);
  11035. return Ctx.getMemberPointerType(
  11036. getCommonPointeeType(Ctx, PX, PY),
  11037. Ctx.getCommonSugaredType(QualType(PX->getClass(), 0),
  11038. QualType(PY->getClass(), 0))
  11039. .getTypePtr());
  11040. }
  11041. case Type::LValueReference: {
  11042. const auto *PX = cast<LValueReferenceType>(X),
  11043. *PY = cast<LValueReferenceType>(Y);
  11044. // FIXME: Preserve PointeeTypeAsWritten.
  11045. return Ctx.getLValueReferenceType(getCommonPointeeType(Ctx, PX, PY),
  11046. PX->isSpelledAsLValue() ||
  11047. PY->isSpelledAsLValue());
  11048. }
  11049. case Type::RValueReference: {
  11050. const auto *PX = cast<RValueReferenceType>(X),
  11051. *PY = cast<RValueReferenceType>(Y);
  11052. // FIXME: Preserve PointeeTypeAsWritten.
  11053. return Ctx.getRValueReferenceType(getCommonPointeeType(Ctx, PX, PY));
  11054. }
  11055. case Type::DependentAddressSpace: {
  11056. const auto *PX = cast<DependentAddressSpaceType>(X),
  11057. *PY = cast<DependentAddressSpaceType>(Y);
  11058. assert(Ctx.hasSameExpr(PX->getAddrSpaceExpr(), PY->getAddrSpaceExpr()));
  11059. return Ctx.getDependentAddressSpaceType(getCommonPointeeType(Ctx, PX, PY),
  11060. PX->getAddrSpaceExpr(),
  11061. getCommonAttrLoc(PX, PY));
  11062. }
  11063. case Type::FunctionNoProto: {
  11064. const auto *FX = cast<FunctionNoProtoType>(X),
  11065. *FY = cast<FunctionNoProtoType>(Y);
  11066. assert(FX->getExtInfo() == FY->getExtInfo());
  11067. return Ctx.getFunctionNoProtoType(
  11068. Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType()),
  11069. FX->getExtInfo());
  11070. }
  11071. case Type::FunctionProto: {
  11072. const auto *FX = cast<FunctionProtoType>(X),
  11073. *FY = cast<FunctionProtoType>(Y);
  11074. FunctionProtoType::ExtProtoInfo EPIX = FX->getExtProtoInfo(),
  11075. EPIY = FY->getExtProtoInfo();
  11076. assert(EPIX.ExtInfo == EPIY.ExtInfo);
  11077. assert(EPIX.ExtParameterInfos == EPIY.ExtParameterInfos);
  11078. assert(EPIX.RefQualifier == EPIY.RefQualifier);
  11079. assert(EPIX.TypeQuals == EPIY.TypeQuals);
  11080. assert(EPIX.Variadic == EPIY.Variadic);
  11081. // FIXME: Can we handle an empty EllipsisLoc?
  11082. // Use emtpy EllipsisLoc if X and Y differ.
  11083. EPIX.HasTrailingReturn = EPIX.HasTrailingReturn && EPIY.HasTrailingReturn;
  11084. QualType R =
  11085. Ctx.getCommonSugaredType(FX->getReturnType(), FY->getReturnType());
  11086. auto P = getCommonTypes(Ctx, FX->param_types(), FY->param_types(),
  11087. /*Unqualified=*/true);
  11088. SmallVector<QualType, 8> Exceptions;
  11089. EPIX.ExceptionSpec = Ctx.mergeExceptionSpecs(
  11090. EPIX.ExceptionSpec, EPIY.ExceptionSpec, Exceptions, true);
  11091. return Ctx.getFunctionType(R, P, EPIX);
  11092. }
  11093. case Type::ObjCObject: {
  11094. const auto *OX = cast<ObjCObjectType>(X), *OY = cast<ObjCObjectType>(Y);
  11095. assert(
  11096. std::equal(OX->getProtocols().begin(), OX->getProtocols().end(),
  11097. OY->getProtocols().begin(), OY->getProtocols().end(),
  11098. [](const ObjCProtocolDecl *P0, const ObjCProtocolDecl *P1) {
  11099. return P0->getCanonicalDecl() == P1->getCanonicalDecl();
  11100. }) &&
  11101. "protocol lists must be the same");
  11102. auto TAs = getCommonTypes(Ctx, OX->getTypeArgsAsWritten(),
  11103. OY->getTypeArgsAsWritten());
  11104. return Ctx.getObjCObjectType(
  11105. Ctx.getCommonSugaredType(OX->getBaseType(), OY->getBaseType()), TAs,
  11106. OX->getProtocols(),
  11107. OX->isKindOfTypeAsWritten() && OY->isKindOfTypeAsWritten());
  11108. }
  11109. case Type::ConstantMatrix: {
  11110. const auto *MX = cast<ConstantMatrixType>(X),
  11111. *MY = cast<ConstantMatrixType>(Y);
  11112. assert(MX->getNumRows() == MY->getNumRows());
  11113. assert(MX->getNumColumns() == MY->getNumColumns());
  11114. return Ctx.getConstantMatrixType(getCommonElementType(Ctx, MX, MY),
  11115. MX->getNumRows(), MX->getNumColumns());
  11116. }
  11117. case Type::DependentSizedMatrix: {
  11118. const auto *MX = cast<DependentSizedMatrixType>(X),
  11119. *MY = cast<DependentSizedMatrixType>(Y);
  11120. assert(Ctx.hasSameExpr(MX->getRowExpr(), MY->getRowExpr()));
  11121. assert(Ctx.hasSameExpr(MX->getColumnExpr(), MY->getColumnExpr()));
  11122. return Ctx.getDependentSizedMatrixType(
  11123. getCommonElementType(Ctx, MX, MY), MX->getRowExpr(),
  11124. MX->getColumnExpr(), getCommonAttrLoc(MX, MY));
  11125. }
  11126. case Type::Vector: {
  11127. const auto *VX = cast<VectorType>(X), *VY = cast<VectorType>(Y);
  11128. assert(VX->getNumElements() == VY->getNumElements());
  11129. assert(VX->getVectorKind() == VY->getVectorKind());
  11130. return Ctx.getVectorType(getCommonElementType(Ctx, VX, VY),
  11131. VX->getNumElements(), VX->getVectorKind());
  11132. }
  11133. case Type::ExtVector: {
  11134. const auto *VX = cast<ExtVectorType>(X), *VY = cast<ExtVectorType>(Y);
  11135. assert(VX->getNumElements() == VY->getNumElements());
  11136. return Ctx.getExtVectorType(getCommonElementType(Ctx, VX, VY),
  11137. VX->getNumElements());
  11138. }
  11139. case Type::DependentSizedExtVector: {
  11140. const auto *VX = cast<DependentSizedExtVectorType>(X),
  11141. *VY = cast<DependentSizedExtVectorType>(Y);
  11142. return Ctx.getDependentSizedExtVectorType(getCommonElementType(Ctx, VX, VY),
  11143. getCommonSizeExpr(Ctx, VX, VY),
  11144. getCommonAttrLoc(VX, VY));
  11145. }
  11146. case Type::DependentVector: {
  11147. const auto *VX = cast<DependentVectorType>(X),
  11148. *VY = cast<DependentVectorType>(Y);
  11149. assert(VX->getVectorKind() == VY->getVectorKind());
  11150. return Ctx.getDependentVectorType(
  11151. getCommonElementType(Ctx, VX, VY), getCommonSizeExpr(Ctx, VX, VY),
  11152. getCommonAttrLoc(VX, VY), VX->getVectorKind());
  11153. }
  11154. case Type::InjectedClassName: {
  11155. const auto *IX = cast<InjectedClassNameType>(X),
  11156. *IY = cast<InjectedClassNameType>(Y);
  11157. return Ctx.getInjectedClassNameType(
  11158. getCommonDeclChecked(IX->getDecl(), IY->getDecl()),
  11159. Ctx.getCommonSugaredType(IX->getInjectedSpecializationType(),
  11160. IY->getInjectedSpecializationType()));
  11161. }
  11162. case Type::TemplateSpecialization: {
  11163. const auto *TX = cast<TemplateSpecializationType>(X),
  11164. *TY = cast<TemplateSpecializationType>(Y);
  11165. auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
  11166. TY->template_arguments());
  11167. return Ctx.getTemplateSpecializationType(
  11168. ::getCommonTemplateNameChecked(Ctx, TX->getTemplateName(),
  11169. TY->getTemplateName()),
  11170. As, X->getCanonicalTypeInternal());
  11171. }
  11172. case Type::DependentName: {
  11173. const auto *NX = cast<DependentNameType>(X),
  11174. *NY = cast<DependentNameType>(Y);
  11175. assert(NX->getIdentifier() == NY->getIdentifier());
  11176. return Ctx.getDependentNameType(
  11177. getCommonTypeKeyword(NX, NY), getCommonNNS(Ctx, NX, NY),
  11178. NX->getIdentifier(), NX->getCanonicalTypeInternal());
  11179. }
  11180. case Type::DependentTemplateSpecialization: {
  11181. const auto *TX = cast<DependentTemplateSpecializationType>(X),
  11182. *TY = cast<DependentTemplateSpecializationType>(Y);
  11183. assert(TX->getIdentifier() == TY->getIdentifier());
  11184. auto As = getCommonTemplateArguments(Ctx, TX->template_arguments(),
  11185. TY->template_arguments());
  11186. return Ctx.getDependentTemplateSpecializationType(
  11187. getCommonTypeKeyword(TX, TY), getCommonNNS(Ctx, TX, TY),
  11188. TX->getIdentifier(), As);
  11189. }
  11190. case Type::UnaryTransform: {
  11191. const auto *TX = cast<UnaryTransformType>(X),
  11192. *TY = cast<UnaryTransformType>(Y);
  11193. assert(TX->getUTTKind() == TY->getUTTKind());
  11194. return Ctx.getUnaryTransformType(
  11195. Ctx.getCommonSugaredType(TX->getBaseType(), TY->getBaseType()),
  11196. Ctx.getCommonSugaredType(TX->getUnderlyingType(),
  11197. TY->getUnderlyingType()),
  11198. TX->getUTTKind());
  11199. }
  11200. case Type::PackExpansion: {
  11201. const auto *PX = cast<PackExpansionType>(X),
  11202. *PY = cast<PackExpansionType>(Y);
  11203. assert(PX->getNumExpansions() == PY->getNumExpansions());
  11204. return Ctx.getPackExpansionType(
  11205. Ctx.getCommonSugaredType(PX->getPattern(), PY->getPattern()),
  11206. PX->getNumExpansions(), false);
  11207. }
  11208. case Type::Pipe: {
  11209. const auto *PX = cast<PipeType>(X), *PY = cast<PipeType>(Y);
  11210. assert(PX->isReadOnly() == PY->isReadOnly());
  11211. auto MP = PX->isReadOnly() ? &ASTContext::getReadPipeType
  11212. : &ASTContext::getWritePipeType;
  11213. return (Ctx.*MP)(getCommonElementType(Ctx, PX, PY));
  11214. }
  11215. case Type::TemplateTypeParm: {
  11216. const auto *TX = cast<TemplateTypeParmType>(X),
  11217. *TY = cast<TemplateTypeParmType>(Y);
  11218. assert(TX->getDepth() == TY->getDepth());
  11219. assert(TX->getIndex() == TY->getIndex());
  11220. assert(TX->isParameterPack() == TY->isParameterPack());
  11221. return Ctx.getTemplateTypeParmType(
  11222. TX->getDepth(), TX->getIndex(), TX->isParameterPack(),
  11223. getCommonDecl(TX->getDecl(), TY->getDecl()));
  11224. }
  11225. }
  11226. llvm_unreachable("Unknown Type Class");
  11227. }
  11228. static QualType getCommonSugarTypeNode(ASTContext &Ctx, const Type *X,
  11229. const Type *Y,
  11230. SplitQualType Underlying) {
  11231. Type::TypeClass TC = X->getTypeClass();
  11232. if (TC != Y->getTypeClass())
  11233. return QualType();
  11234. switch (TC) {
  11235. #define UNEXPECTED_TYPE(Class, Kind) \
  11236. case Type::Class: \
  11237. llvm_unreachable("Unexpected " Kind ": " #Class);
  11238. #define TYPE(Class, Base)
  11239. #define DEPENDENT_TYPE(Class, Base) UNEXPECTED_TYPE(Class, "dependent")
  11240. #include "clang/AST/TypeNodes.inc"
  11241. #define CANONICAL_TYPE(Class) UNEXPECTED_TYPE(Class, "canonical")
  11242. CANONICAL_TYPE(Atomic)
  11243. CANONICAL_TYPE(BitInt)
  11244. CANONICAL_TYPE(BlockPointer)
  11245. CANONICAL_TYPE(Builtin)
  11246. CANONICAL_TYPE(Complex)
  11247. CANONICAL_TYPE(ConstantArray)
  11248. CANONICAL_TYPE(ConstantMatrix)
  11249. CANONICAL_TYPE(Enum)
  11250. CANONICAL_TYPE(ExtVector)
  11251. CANONICAL_TYPE(FunctionNoProto)
  11252. CANONICAL_TYPE(FunctionProto)
  11253. CANONICAL_TYPE(IncompleteArray)
  11254. CANONICAL_TYPE(LValueReference)
  11255. CANONICAL_TYPE(MemberPointer)
  11256. CANONICAL_TYPE(ObjCInterface)
  11257. CANONICAL_TYPE(ObjCObject)
  11258. CANONICAL_TYPE(ObjCObjectPointer)
  11259. CANONICAL_TYPE(Pipe)
  11260. CANONICAL_TYPE(Pointer)
  11261. CANONICAL_TYPE(Record)
  11262. CANONICAL_TYPE(RValueReference)
  11263. CANONICAL_TYPE(VariableArray)
  11264. CANONICAL_TYPE(Vector)
  11265. #undef CANONICAL_TYPE
  11266. #undef UNEXPECTED_TYPE
  11267. case Type::Adjusted: {
  11268. const auto *AX = cast<AdjustedType>(X), *AY = cast<AdjustedType>(Y);
  11269. QualType OX = AX->getOriginalType(), OY = AY->getOriginalType();
  11270. if (!Ctx.hasSameType(OX, OY))
  11271. return QualType();
  11272. // FIXME: It's inefficient to have to unify the original types.
  11273. return Ctx.getAdjustedType(Ctx.getCommonSugaredType(OX, OY),
  11274. Ctx.getQualifiedType(Underlying));
  11275. }
  11276. case Type::Decayed: {
  11277. const auto *DX = cast<DecayedType>(X), *DY = cast<DecayedType>(Y);
  11278. QualType OX = DX->getOriginalType(), OY = DY->getOriginalType();
  11279. if (!Ctx.hasSameType(OX, OY))
  11280. return QualType();
  11281. // FIXME: It's inefficient to have to unify the original types.
  11282. return Ctx.getDecayedType(Ctx.getCommonSugaredType(OX, OY),
  11283. Ctx.getQualifiedType(Underlying));
  11284. }
  11285. case Type::Attributed: {
  11286. const auto *AX = cast<AttributedType>(X), *AY = cast<AttributedType>(Y);
  11287. AttributedType::Kind Kind = AX->getAttrKind();
  11288. if (Kind != AY->getAttrKind())
  11289. return QualType();
  11290. QualType MX = AX->getModifiedType(), MY = AY->getModifiedType();
  11291. if (!Ctx.hasSameType(MX, MY))
  11292. return QualType();
  11293. // FIXME: It's inefficient to have to unify the modified types.
  11294. return Ctx.getAttributedType(Kind, Ctx.getCommonSugaredType(MX, MY),
  11295. Ctx.getQualifiedType(Underlying));
  11296. }
  11297. case Type::BTFTagAttributed: {
  11298. const auto *BX = cast<BTFTagAttributedType>(X);
  11299. const BTFTypeTagAttr *AX = BX->getAttr();
  11300. // The attribute is not uniqued, so just compare the tag.
  11301. if (AX->getBTFTypeTag() !=
  11302. cast<BTFTagAttributedType>(Y)->getAttr()->getBTFTypeTag())
  11303. return QualType();
  11304. return Ctx.getBTFTagAttributedType(AX, Ctx.getQualifiedType(Underlying));
  11305. }
  11306. case Type::Auto: {
  11307. const auto *AX = cast<AutoType>(X), *AY = cast<AutoType>(Y);
  11308. AutoTypeKeyword KW = AX->getKeyword();
  11309. if (KW != AY->getKeyword())
  11310. return QualType();
  11311. ConceptDecl *CD = ::getCommonDecl(AX->getTypeConstraintConcept(),
  11312. AY->getTypeConstraintConcept());
  11313. SmallVector<TemplateArgument, 8> As;
  11314. if (CD &&
  11315. getCommonTemplateArguments(Ctx, As, AX->getTypeConstraintArguments(),
  11316. AY->getTypeConstraintArguments()))
  11317. CD = nullptr; // The arguments differ, so make it unconstrained.
  11318. // Both auto types can't be dependent, otherwise they wouldn't have been
  11319. // sugar. This implies they can't contain unexpanded packs either.
  11320. return Ctx.getAutoType(Ctx.getQualifiedType(Underlying), AX->getKeyword(),
  11321. /*IsDependent=*/false, /*IsPack=*/false, CD, As);
  11322. }
  11323. case Type::Decltype:
  11324. return QualType();
  11325. case Type::DeducedTemplateSpecialization:
  11326. // FIXME: Try to merge these.
  11327. return QualType();
  11328. case Type::Elaborated: {
  11329. const auto *EX = cast<ElaboratedType>(X), *EY = cast<ElaboratedType>(Y);
  11330. return Ctx.getElaboratedType(
  11331. ::getCommonTypeKeyword(EX, EY), ::getCommonNNS(Ctx, EX, EY),
  11332. Ctx.getQualifiedType(Underlying),
  11333. ::getCommonDecl(EX->getOwnedTagDecl(), EY->getOwnedTagDecl()));
  11334. }
  11335. case Type::MacroQualified: {
  11336. const auto *MX = cast<MacroQualifiedType>(X),
  11337. *MY = cast<MacroQualifiedType>(Y);
  11338. const IdentifierInfo *IX = MX->getMacroIdentifier();
  11339. if (IX != MY->getMacroIdentifier())
  11340. return QualType();
  11341. return Ctx.getMacroQualifiedType(Ctx.getQualifiedType(Underlying), IX);
  11342. }
  11343. case Type::SubstTemplateTypeParm: {
  11344. const auto *SX = cast<SubstTemplateTypeParmType>(X),
  11345. *SY = cast<SubstTemplateTypeParmType>(Y);
  11346. Decl *CD =
  11347. ::getCommonDecl(SX->getAssociatedDecl(), SY->getAssociatedDecl());
  11348. if (!CD)
  11349. return QualType();
  11350. unsigned Index = SX->getIndex();
  11351. if (Index != SY->getIndex())
  11352. return QualType();
  11353. auto PackIndex = SX->getPackIndex();
  11354. if (PackIndex != SY->getPackIndex())
  11355. return QualType();
  11356. return Ctx.getSubstTemplateTypeParmType(Ctx.getQualifiedType(Underlying),
  11357. CD, Index, PackIndex);
  11358. }
  11359. case Type::ObjCTypeParam:
  11360. // FIXME: Try to merge these.
  11361. return QualType();
  11362. case Type::Paren:
  11363. return Ctx.getParenType(Ctx.getQualifiedType(Underlying));
  11364. case Type::TemplateSpecialization: {
  11365. const auto *TX = cast<TemplateSpecializationType>(X),
  11366. *TY = cast<TemplateSpecializationType>(Y);
  11367. TemplateName CTN = ::getCommonTemplateName(Ctx, TX->getTemplateName(),
  11368. TY->getTemplateName());
  11369. if (!CTN.getAsVoidPointer())
  11370. return QualType();
  11371. SmallVector<TemplateArgument, 8> Args;
  11372. if (getCommonTemplateArguments(Ctx, Args, TX->template_arguments(),
  11373. TY->template_arguments()))
  11374. return QualType();
  11375. return Ctx.getTemplateSpecializationType(CTN, Args,
  11376. Ctx.getQualifiedType(Underlying));
  11377. }
  11378. case Type::Typedef: {
  11379. const auto *TX = cast<TypedefType>(X), *TY = cast<TypedefType>(Y);
  11380. const TypedefNameDecl *CD = ::getCommonDecl(TX->getDecl(), TY->getDecl());
  11381. if (!CD)
  11382. return QualType();
  11383. return Ctx.getTypedefType(CD, Ctx.getQualifiedType(Underlying));
  11384. }
  11385. case Type::TypeOf: {
  11386. // The common sugar between two typeof expressions, where one is
  11387. // potentially a typeof_unqual and the other is not, we unify to the
  11388. // qualified type as that retains the most information along with the type.
  11389. // We only return a typeof_unqual type when both types are unqual types.
  11390. TypeOfKind Kind = TypeOfKind::Qualified;
  11391. if (cast<TypeOfType>(X)->getKind() == cast<TypeOfType>(Y)->getKind() &&
  11392. cast<TypeOfType>(X)->getKind() == TypeOfKind::Unqualified)
  11393. Kind = TypeOfKind::Unqualified;
  11394. return Ctx.getTypeOfType(Ctx.getQualifiedType(Underlying), Kind);
  11395. }
  11396. case Type::TypeOfExpr:
  11397. return QualType();
  11398. case Type::UnaryTransform: {
  11399. const auto *UX = cast<UnaryTransformType>(X),
  11400. *UY = cast<UnaryTransformType>(Y);
  11401. UnaryTransformType::UTTKind KX = UX->getUTTKind();
  11402. if (KX != UY->getUTTKind())
  11403. return QualType();
  11404. QualType BX = UX->getBaseType(), BY = UY->getBaseType();
  11405. if (!Ctx.hasSameType(BX, BY))
  11406. return QualType();
  11407. // FIXME: It's inefficient to have to unify the base types.
  11408. return Ctx.getUnaryTransformType(Ctx.getCommonSugaredType(BX, BY),
  11409. Ctx.getQualifiedType(Underlying), KX);
  11410. }
  11411. case Type::Using: {
  11412. const auto *UX = cast<UsingType>(X), *UY = cast<UsingType>(Y);
  11413. const UsingShadowDecl *CD =
  11414. ::getCommonDecl(UX->getFoundDecl(), UY->getFoundDecl());
  11415. if (!CD)
  11416. return QualType();
  11417. return Ctx.getUsingType(CD, Ctx.getQualifiedType(Underlying));
  11418. }
  11419. }
  11420. llvm_unreachable("Unhandled Type Class");
  11421. }
  11422. static auto unwrapSugar(SplitQualType &T, Qualifiers &QTotal) {
  11423. SmallVector<SplitQualType, 8> R;
  11424. while (true) {
  11425. QTotal += T.Quals;
  11426. QualType NT = T.Ty->getLocallyUnqualifiedSingleStepDesugaredType();
  11427. if (NT == QualType(T.Ty, 0))
  11428. break;
  11429. R.push_back(T);
  11430. T = NT.split();
  11431. }
  11432. return R;
  11433. }
  11434. QualType ASTContext::getCommonSugaredType(QualType X, QualType Y,
  11435. bool Unqualified) {
  11436. assert(Unqualified ? hasSameUnqualifiedType(X, Y) : hasSameType(X, Y));
  11437. if (X == Y)
  11438. return X;
  11439. if (!Unqualified) {
  11440. if (X.isCanonical())
  11441. return X;
  11442. if (Y.isCanonical())
  11443. return Y;
  11444. }
  11445. SplitQualType SX = X.split(), SY = Y.split();
  11446. Qualifiers QX, QY;
  11447. // Desugar SX and SY, setting the sugar and qualifiers aside into Xs and Ys,
  11448. // until we reach their underlying "canonical nodes". Note these are not
  11449. // necessarily canonical types, as they may still have sugared properties.
  11450. // QX and QY will store the sum of all qualifiers in Xs and Ys respectively.
  11451. auto Xs = ::unwrapSugar(SX, QX), Ys = ::unwrapSugar(SY, QY);
  11452. if (SX.Ty != SY.Ty) {
  11453. // The canonical nodes differ. Build a common canonical node out of the two,
  11454. // unifying their sugar. This may recurse back here.
  11455. SX.Ty =
  11456. ::getCommonNonSugarTypeNode(*this, SX.Ty, QX, SY.Ty, QY).getTypePtr();
  11457. } else {
  11458. // The canonical nodes were identical: We may have desugared too much.
  11459. // Add any common sugar back in.
  11460. while (!Xs.empty() && !Ys.empty() && Xs.back().Ty == Ys.back().Ty) {
  11461. QX -= SX.Quals;
  11462. QY -= SY.Quals;
  11463. SX = Xs.pop_back_val();
  11464. SY = Ys.pop_back_val();
  11465. }
  11466. }
  11467. if (Unqualified)
  11468. QX = Qualifiers::removeCommonQualifiers(QX, QY);
  11469. else
  11470. assert(QX == QY);
  11471. // Even though the remaining sugar nodes in Xs and Ys differ, some may be
  11472. // related. Walk up these nodes, unifying them and adding the result.
  11473. while (!Xs.empty() && !Ys.empty()) {
  11474. auto Underlying = SplitQualType(
  11475. SX.Ty, Qualifiers::removeCommonQualifiers(SX.Quals, SY.Quals));
  11476. SX = Xs.pop_back_val();
  11477. SY = Ys.pop_back_val();
  11478. SX.Ty = ::getCommonSugarTypeNode(*this, SX.Ty, SY.Ty, Underlying)
  11479. .getTypePtrOrNull();
  11480. // Stop at the first pair which is unrelated.
  11481. if (!SX.Ty) {
  11482. SX.Ty = Underlying.Ty;
  11483. break;
  11484. }
  11485. QX -= Underlying.Quals;
  11486. };
  11487. // Add back the missing accumulated qualifiers, which were stripped off
  11488. // with the sugar nodes we could not unify.
  11489. QualType R = getQualifiedType(SX.Ty, QX);
  11490. assert(Unqualified ? hasSameUnqualifiedType(R, X) : hasSameType(R, X));
  11491. return R;
  11492. }
  11493. QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
  11494. assert(Ty->isFixedPointType());
  11495. if (Ty->isSaturatedFixedPointType()) return Ty;
  11496. switch (Ty->castAs<BuiltinType>()->getKind()) {
  11497. default:
  11498. llvm_unreachable("Not a fixed point type!");
  11499. case BuiltinType::ShortAccum:
  11500. return SatShortAccumTy;
  11501. case BuiltinType::Accum:
  11502. return SatAccumTy;
  11503. case BuiltinType::LongAccum:
  11504. return SatLongAccumTy;
  11505. case BuiltinType::UShortAccum:
  11506. return SatUnsignedShortAccumTy;
  11507. case BuiltinType::UAccum:
  11508. return SatUnsignedAccumTy;
  11509. case BuiltinType::ULongAccum:
  11510. return SatUnsignedLongAccumTy;
  11511. case BuiltinType::ShortFract:
  11512. return SatShortFractTy;
  11513. case BuiltinType::Fract:
  11514. return SatFractTy;
  11515. case BuiltinType::LongFract:
  11516. return SatLongFractTy;
  11517. case BuiltinType::UShortFract:
  11518. return SatUnsignedShortFractTy;
  11519. case BuiltinType::UFract:
  11520. return SatUnsignedFractTy;
  11521. case BuiltinType::ULongFract:
  11522. return SatUnsignedLongFractTy;
  11523. }
  11524. }
  11525. LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
  11526. if (LangOpts.OpenCL)
  11527. return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
  11528. if (LangOpts.CUDA)
  11529. return getTargetInfo().getCUDABuiltinAddressSpace(AS);
  11530. return getLangASFromTargetAS(AS);
  11531. }
  11532. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  11533. // doesn't include ASTContext.h
  11534. template
  11535. clang::LazyGenerationalUpdatePtr<
  11536. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  11537. clang::LazyGenerationalUpdatePtr<
  11538. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  11539. const clang::ASTContext &Ctx, Decl *Value);
  11540. unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
  11541. assert(Ty->isFixedPointType());
  11542. const TargetInfo &Target = getTargetInfo();
  11543. switch (Ty->castAs<BuiltinType>()->getKind()) {
  11544. default:
  11545. llvm_unreachable("Not a fixed point type!");
  11546. case BuiltinType::ShortAccum:
  11547. case BuiltinType::SatShortAccum:
  11548. return Target.getShortAccumScale();
  11549. case BuiltinType::Accum:
  11550. case BuiltinType::SatAccum:
  11551. return Target.getAccumScale();
  11552. case BuiltinType::LongAccum:
  11553. case BuiltinType::SatLongAccum:
  11554. return Target.getLongAccumScale();
  11555. case BuiltinType::UShortAccum:
  11556. case BuiltinType::SatUShortAccum:
  11557. return Target.getUnsignedShortAccumScale();
  11558. case BuiltinType::UAccum:
  11559. case BuiltinType::SatUAccum:
  11560. return Target.getUnsignedAccumScale();
  11561. case BuiltinType::ULongAccum:
  11562. case BuiltinType::SatULongAccum:
  11563. return Target.getUnsignedLongAccumScale();
  11564. case BuiltinType::ShortFract:
  11565. case BuiltinType::SatShortFract:
  11566. return Target.getShortFractScale();
  11567. case BuiltinType::Fract:
  11568. case BuiltinType::SatFract:
  11569. return Target.getFractScale();
  11570. case BuiltinType::LongFract:
  11571. case BuiltinType::SatLongFract:
  11572. return Target.getLongFractScale();
  11573. case BuiltinType::UShortFract:
  11574. case BuiltinType::SatUShortFract:
  11575. return Target.getUnsignedShortFractScale();
  11576. case BuiltinType::UFract:
  11577. case BuiltinType::SatUFract:
  11578. return Target.getUnsignedFractScale();
  11579. case BuiltinType::ULongFract:
  11580. case BuiltinType::SatULongFract:
  11581. return Target.getUnsignedLongFractScale();
  11582. }
  11583. }
  11584. unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
  11585. assert(Ty->isFixedPointType());
  11586. const TargetInfo &Target = getTargetInfo();
  11587. switch (Ty->castAs<BuiltinType>()->getKind()) {
  11588. default:
  11589. llvm_unreachable("Not a fixed point type!");
  11590. case BuiltinType::ShortAccum:
  11591. case BuiltinType::SatShortAccum:
  11592. return Target.getShortAccumIBits();
  11593. case BuiltinType::Accum:
  11594. case BuiltinType::SatAccum:
  11595. return Target.getAccumIBits();
  11596. case BuiltinType::LongAccum:
  11597. case BuiltinType::SatLongAccum:
  11598. return Target.getLongAccumIBits();
  11599. case BuiltinType::UShortAccum:
  11600. case BuiltinType::SatUShortAccum:
  11601. return Target.getUnsignedShortAccumIBits();
  11602. case BuiltinType::UAccum:
  11603. case BuiltinType::SatUAccum:
  11604. return Target.getUnsignedAccumIBits();
  11605. case BuiltinType::ULongAccum:
  11606. case BuiltinType::SatULongAccum:
  11607. return Target.getUnsignedLongAccumIBits();
  11608. case BuiltinType::ShortFract:
  11609. case BuiltinType::SatShortFract:
  11610. case BuiltinType::Fract:
  11611. case BuiltinType::SatFract:
  11612. case BuiltinType::LongFract:
  11613. case BuiltinType::SatLongFract:
  11614. case BuiltinType::UShortFract:
  11615. case BuiltinType::SatUShortFract:
  11616. case BuiltinType::UFract:
  11617. case BuiltinType::SatUFract:
  11618. case BuiltinType::ULongFract:
  11619. case BuiltinType::SatULongFract:
  11620. return 0;
  11621. }
  11622. }
  11623. llvm::FixedPointSemantics
  11624. ASTContext::getFixedPointSemantics(QualType Ty) const {
  11625. assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
  11626. "Can only get the fixed point semantics for a "
  11627. "fixed point or integer type.");
  11628. if (Ty->isIntegerType())
  11629. return llvm::FixedPointSemantics::GetIntegerSemantics(
  11630. getIntWidth(Ty), Ty->isSignedIntegerType());
  11631. bool isSigned = Ty->isSignedFixedPointType();
  11632. return llvm::FixedPointSemantics(
  11633. static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
  11634. Ty->isSaturatedFixedPointType(),
  11635. !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
  11636. }
  11637. llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
  11638. assert(Ty->isFixedPointType());
  11639. return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
  11640. }
  11641. llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
  11642. assert(Ty->isFixedPointType());
  11643. return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
  11644. }
  11645. QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
  11646. assert(Ty->isUnsignedFixedPointType() &&
  11647. "Expected unsigned fixed point type");
  11648. switch (Ty->castAs<BuiltinType>()->getKind()) {
  11649. case BuiltinType::UShortAccum:
  11650. return ShortAccumTy;
  11651. case BuiltinType::UAccum:
  11652. return AccumTy;
  11653. case BuiltinType::ULongAccum:
  11654. return LongAccumTy;
  11655. case BuiltinType::SatUShortAccum:
  11656. return SatShortAccumTy;
  11657. case BuiltinType::SatUAccum:
  11658. return SatAccumTy;
  11659. case BuiltinType::SatULongAccum:
  11660. return SatLongAccumTy;
  11661. case BuiltinType::UShortFract:
  11662. return ShortFractTy;
  11663. case BuiltinType::UFract:
  11664. return FractTy;
  11665. case BuiltinType::ULongFract:
  11666. return LongFractTy;
  11667. case BuiltinType::SatUShortFract:
  11668. return SatShortFractTy;
  11669. case BuiltinType::SatUFract:
  11670. return SatFractTy;
  11671. case BuiltinType::SatULongFract:
  11672. return SatLongFractTy;
  11673. default:
  11674. llvm_unreachable("Unexpected unsigned fixed point type");
  11675. }
  11676. }
  11677. std::vector<std::string> ASTContext::filterFunctionTargetVersionAttrs(
  11678. const TargetVersionAttr *TV) const {
  11679. assert(TV != nullptr);
  11680. llvm::SmallVector<StringRef, 8> Feats;
  11681. std::vector<std::string> ResFeats;
  11682. TV->getFeatures(Feats);
  11683. for (auto &Feature : Feats)
  11684. if (Target->validateCpuSupports(Feature.str()))
  11685. ResFeats.push_back("?" + Feature.str());
  11686. return ResFeats;
  11687. }
  11688. ParsedTargetAttr
  11689. ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
  11690. assert(TD != nullptr);
  11691. ParsedTargetAttr ParsedAttr = Target->parseTargetAttr(TD->getFeaturesStr());
  11692. llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
  11693. return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
  11694. });
  11695. return ParsedAttr;
  11696. }
  11697. void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  11698. const FunctionDecl *FD) const {
  11699. if (FD)
  11700. getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
  11701. else
  11702. Target->initFeatureMap(FeatureMap, getDiagnostics(),
  11703. Target->getTargetOpts().CPU,
  11704. Target->getTargetOpts().Features);
  11705. }
  11706. // Fills in the supplied string map with the set of target features for the
  11707. // passed in function.
  11708. void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  11709. GlobalDecl GD) const {
  11710. StringRef TargetCPU = Target->getTargetOpts().CPU;
  11711. const FunctionDecl *FD = GD.getDecl()->getAsFunction();
  11712. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  11713. ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
  11714. // Make a copy of the features as passed on the command line into the
  11715. // beginning of the additional features from the function to override.
  11716. ParsedAttr.Features.insert(
  11717. ParsedAttr.Features.begin(),
  11718. Target->getTargetOpts().FeaturesAsWritten.begin(),
  11719. Target->getTargetOpts().FeaturesAsWritten.end());
  11720. if (ParsedAttr.CPU != "" && Target->isValidCPUName(ParsedAttr.CPU))
  11721. TargetCPU = ParsedAttr.CPU;
  11722. // Now populate the feature map, first with the TargetCPU which is either
  11723. // the default or a new one from the target attribute string. Then we'll use
  11724. // the passed in features (FeaturesAsWritten) along with the new ones from
  11725. // the attribute.
  11726. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
  11727. ParsedAttr.Features);
  11728. } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
  11729. llvm::SmallVector<StringRef, 32> FeaturesTmp;
  11730. Target->getCPUSpecificCPUDispatchFeatures(
  11731. SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
  11732. std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
  11733. Features.insert(Features.begin(),
  11734. Target->getTargetOpts().FeaturesAsWritten.begin(),
  11735. Target->getTargetOpts().FeaturesAsWritten.end());
  11736. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
  11737. } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
  11738. std::vector<std::string> Features;
  11739. StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
  11740. if (Target->getTriple().isAArch64()) {
  11741. // TargetClones for AArch64
  11742. if (VersionStr != "default") {
  11743. SmallVector<StringRef, 1> VersionFeatures;
  11744. VersionStr.split(VersionFeatures, "+");
  11745. for (auto &VFeature : VersionFeatures) {
  11746. VFeature = VFeature.trim();
  11747. Features.push_back((StringRef{"?"} + VFeature).str());
  11748. }
  11749. }
  11750. Features.insert(Features.begin(),
  11751. Target->getTargetOpts().FeaturesAsWritten.begin(),
  11752. Target->getTargetOpts().FeaturesAsWritten.end());
  11753. } else {
  11754. if (VersionStr.startswith("arch="))
  11755. TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
  11756. else if (VersionStr != "default")
  11757. Features.push_back((StringRef{"+"} + VersionStr).str());
  11758. }
  11759. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
  11760. } else if (const auto *TV = FD->getAttr<TargetVersionAttr>()) {
  11761. std::vector<std::string> Feats = filterFunctionTargetVersionAttrs(TV);
  11762. Feats.insert(Feats.begin(),
  11763. Target->getTargetOpts().FeaturesAsWritten.begin(),
  11764. Target->getTargetOpts().FeaturesAsWritten.end());
  11765. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Feats);
  11766. } else {
  11767. FeatureMap = Target->getTargetOpts().FeatureMap;
  11768. }
  11769. }
  11770. OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
  11771. OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
  11772. return *OMPTraitInfoVector.back();
  11773. }
  11774. const StreamingDiagnostic &clang::
  11775. operator<<(const StreamingDiagnostic &DB,
  11776. const ASTContext::SectionInfo &Section) {
  11777. if (Section.Decl)
  11778. return DB << Section.Decl;
  11779. return DB << "a prior #pragma section";
  11780. }
  11781. bool ASTContext::mayExternalize(const Decl *D) const {
  11782. bool IsStaticVar =
  11783. isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
  11784. bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
  11785. !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
  11786. (D->hasAttr<CUDAConstantAttr>() &&
  11787. !D->getAttr<CUDAConstantAttr>()->isImplicit());
  11788. // CUDA/HIP: static managed variables need to be externalized since it is
  11789. // a declaration in IR, therefore cannot have internal linkage. Kernels in
  11790. // anonymous name space needs to be externalized to avoid duplicate symbols.
  11791. return (IsStaticVar &&
  11792. (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
  11793. (D->hasAttr<CUDAGlobalAttr>() &&
  11794. basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
  11795. GVA_Internal);
  11796. }
  11797. bool ASTContext::shouldExternalize(const Decl *D) const {
  11798. return mayExternalize(D) &&
  11799. (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
  11800. CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
  11801. }
  11802. StringRef ASTContext::getCUIDHash() const {
  11803. if (!CUIDHash.empty())
  11804. return CUIDHash;
  11805. if (LangOpts.CUID.empty())
  11806. return StringRef();
  11807. CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
  11808. return CUIDHash;
  11809. }