ASTContext.cpp 447 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288
  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/None.h"
  74. #include "llvm/ADT/Optional.h"
  75. #include "llvm/ADT/PointerUnion.h"
  76. #include "llvm/ADT/STLExtras.h"
  77. #include "llvm/ADT/SmallPtrSet.h"
  78. #include "llvm/ADT/SmallVector.h"
  79. #include "llvm/ADT/StringExtras.h"
  80. #include "llvm/ADT/StringRef.h"
  81. #include "llvm/ADT/Triple.h"
  82. #include "llvm/Support/Capacity.h"
  83. #include "llvm/Support/Casting.h"
  84. #include "llvm/Support/Compiler.h"
  85. #include "llvm/Support/ErrorHandling.h"
  86. #include "llvm/Support/MD5.h"
  87. #include "llvm/Support/MathExtras.h"
  88. #include "llvm/Support/raw_ostream.h"
  89. #include <algorithm>
  90. #include <cassert>
  91. #include <cstddef>
  92. #include <cstdint>
  93. #include <cstdlib>
  94. #include <map>
  95. #include <memory>
  96. #include <string>
  97. #include <tuple>
  98. #include <utility>
  99. using namespace clang;
  100. enum FloatingRank {
  101. BFloat16Rank,
  102. Float16Rank,
  103. HalfRank,
  104. FloatRank,
  105. DoubleRank,
  106. LongDoubleRank,
  107. Float128Rank,
  108. Ibm128Rank
  109. };
  110. /// \returns location that is relevant when searching for Doc comments related
  111. /// to \p D.
  112. static SourceLocation getDeclLocForCommentSearch(const Decl *D,
  113. SourceManager &SourceMgr) {
  114. assert(D);
  115. // User can not attach documentation to implicit declarations.
  116. if (D->isImplicit())
  117. return {};
  118. // User can not attach documentation to implicit instantiations.
  119. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  120. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  121. return {};
  122. }
  123. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  124. if (VD->isStaticDataMember() &&
  125. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  126. return {};
  127. }
  128. if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
  129. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  130. return {};
  131. }
  132. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  133. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  134. if (TSK == TSK_ImplicitInstantiation ||
  135. TSK == TSK_Undeclared)
  136. return {};
  137. }
  138. if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  139. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  140. return {};
  141. }
  142. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  143. // When tag declaration (but not definition!) is part of the
  144. // decl-specifier-seq of some other declaration, it doesn't get comment
  145. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  146. return {};
  147. }
  148. // TODO: handle comments for function parameters properly.
  149. if (isa<ParmVarDecl>(D))
  150. return {};
  151. // TODO: we could look up template parameter documentation in the template
  152. // documentation.
  153. if (isa<TemplateTypeParmDecl>(D) ||
  154. isa<NonTypeTemplateParmDecl>(D) ||
  155. isa<TemplateTemplateParmDecl>(D))
  156. return {};
  157. // Find declaration location.
  158. // For Objective-C declarations we generally don't expect to have multiple
  159. // declarators, thus use declaration starting location as the "declaration
  160. // location".
  161. // For all other declarations multiple declarators are used quite frequently,
  162. // so we use the location of the identifier as the "declaration location".
  163. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  164. isa<ObjCPropertyDecl>(D) ||
  165. isa<RedeclarableTemplateDecl>(D) ||
  166. isa<ClassTemplateSpecializationDecl>(D) ||
  167. // Allow association with Y across {} in `typedef struct X {} Y`.
  168. isa<TypedefDecl>(D))
  169. return D->getBeginLoc();
  170. const SourceLocation DeclLoc = D->getLocation();
  171. if (DeclLoc.isMacroID()) {
  172. if (isa<TypedefDecl>(D)) {
  173. // If location of the typedef name is in a macro, it is because being
  174. // declared via a macro. Try using declaration's starting location as
  175. // the "declaration location".
  176. return D->getBeginLoc();
  177. }
  178. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  179. // If location of the tag decl is inside a macro, but the spelling of
  180. // the tag name comes from a macro argument, it looks like a special
  181. // macro like NS_ENUM is being used to define the tag decl. In that
  182. // case, adjust the source location to the expansion loc so that we can
  183. // attach the comment to the tag decl.
  184. if (SourceMgr.isMacroArgExpansion(DeclLoc) && TD->isCompleteDefinition())
  185. return SourceMgr.getExpansionLoc(DeclLoc);
  186. }
  187. }
  188. return DeclLoc;
  189. }
  190. RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
  191. const Decl *D, const SourceLocation RepresentativeLocForDecl,
  192. const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
  193. // If the declaration doesn't map directly to a location in a file, we
  194. // can't find the comment.
  195. if (RepresentativeLocForDecl.isInvalid() ||
  196. !RepresentativeLocForDecl.isFileID())
  197. return nullptr;
  198. // If there are no comments anywhere, we won't find anything.
  199. if (CommentsInTheFile.empty())
  200. return nullptr;
  201. // Decompose the location for the declaration and find the beginning of the
  202. // file buffer.
  203. const std::pair<FileID, unsigned> DeclLocDecomp =
  204. SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
  205. // Slow path.
  206. auto OffsetCommentBehindDecl =
  207. CommentsInTheFile.lower_bound(DeclLocDecomp.second);
  208. // First check whether we have a trailing comment.
  209. if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
  210. RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
  211. if ((CommentBehindDecl->isDocumentation() ||
  212. LangOpts.CommentOpts.ParseAllComments) &&
  213. CommentBehindDecl->isTrailingComment() &&
  214. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  215. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  216. // Check that Doxygen trailing comment comes after the declaration, starts
  217. // on the same line and in the same file as the declaration.
  218. if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
  219. Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
  220. OffsetCommentBehindDecl->first)) {
  221. return CommentBehindDecl;
  222. }
  223. }
  224. }
  225. // The comment just after the declaration was not a trailing comment.
  226. // Let's look at the previous comment.
  227. if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
  228. return nullptr;
  229. auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
  230. RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
  231. // Check that we actually have a non-member Doxygen comment.
  232. if (!(CommentBeforeDecl->isDocumentation() ||
  233. LangOpts.CommentOpts.ParseAllComments) ||
  234. CommentBeforeDecl->isTrailingComment())
  235. return nullptr;
  236. // Decompose the end of the comment.
  237. const unsigned CommentEndOffset =
  238. Comments.getCommentEndOffset(CommentBeforeDecl);
  239. // Get the corresponding buffer.
  240. bool Invalid = false;
  241. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  242. &Invalid).data();
  243. if (Invalid)
  244. return nullptr;
  245. // Extract text between the comment and declaration.
  246. StringRef Text(Buffer + CommentEndOffset,
  247. DeclLocDecomp.second - CommentEndOffset);
  248. // There should be no other declarations or preprocessor directives between
  249. // comment and declaration.
  250. if (Text.find_first_of(";{}#@") != StringRef::npos)
  251. return nullptr;
  252. return CommentBeforeDecl;
  253. }
  254. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  255. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  256. // If the declaration doesn't map directly to a location in a file, we
  257. // can't find the comment.
  258. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  259. return nullptr;
  260. if (ExternalSource && !CommentsLoaded) {
  261. ExternalSource->ReadComments();
  262. CommentsLoaded = true;
  263. }
  264. if (Comments.empty())
  265. return nullptr;
  266. const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
  267. const auto CommentsInThisFile = Comments.getCommentsInFile(File);
  268. if (!CommentsInThisFile || CommentsInThisFile->empty())
  269. return nullptr;
  270. return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
  271. }
  272. void ASTContext::addComment(const RawComment &RC) {
  273. assert(LangOpts.RetainCommentsFromSystemHeaders ||
  274. !SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
  275. Comments.addComment(RC, LangOpts.CommentOpts, BumpAlloc);
  276. }
  277. /// If we have a 'templated' declaration for a template, adjust 'D' to
  278. /// refer to the actual template.
  279. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  280. static const Decl &adjustDeclToTemplate(const Decl &D) {
  281. if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
  282. // Is this function declaration part of a function template?
  283. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  284. return *FTD;
  285. // Nothing to do if function is not an implicit instantiation.
  286. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  287. return D;
  288. // Function is an implicit instantiation of a function template?
  289. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  290. return *FTD;
  291. // Function is instantiated from a member definition of a class template?
  292. if (const FunctionDecl *MemberDecl =
  293. FD->getInstantiatedFromMemberFunction())
  294. return *MemberDecl;
  295. return D;
  296. }
  297. if (const auto *VD = dyn_cast<VarDecl>(&D)) {
  298. // Static data member is instantiated from a member definition of a class
  299. // template?
  300. if (VD->isStaticDataMember())
  301. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  302. return *MemberDecl;
  303. return D;
  304. }
  305. if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
  306. // Is this class declaration part of a class template?
  307. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  308. return *CTD;
  309. // Class is an implicit instantiation of a class template or partial
  310. // specialization?
  311. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  312. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  313. return D;
  314. llvm::PointerUnion<ClassTemplateDecl *,
  315. ClassTemplatePartialSpecializationDecl *>
  316. PU = CTSD->getSpecializedTemplateOrPartial();
  317. return PU.is<ClassTemplateDecl *>()
  318. ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
  319. : *static_cast<const Decl *>(
  320. PU.get<ClassTemplatePartialSpecializationDecl *>());
  321. }
  322. // Class is instantiated from a member definition of a class template?
  323. if (const MemberSpecializationInfo *Info =
  324. CRD->getMemberSpecializationInfo())
  325. return *Info->getInstantiatedFrom();
  326. return D;
  327. }
  328. if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
  329. // Enum is instantiated from a member definition of a class template?
  330. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  331. return *MemberDecl;
  332. return D;
  333. }
  334. // FIXME: Adjust alias templates?
  335. return D;
  336. }
  337. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  338. const Decl *D,
  339. const Decl **OriginalDecl) const {
  340. if (!D) {
  341. if (OriginalDecl)
  342. OriginalDecl = nullptr;
  343. return nullptr;
  344. }
  345. D = &adjustDeclToTemplate(*D);
  346. // Any comment directly attached to D?
  347. {
  348. auto DeclComment = DeclRawComments.find(D);
  349. if (DeclComment != DeclRawComments.end()) {
  350. if (OriginalDecl)
  351. *OriginalDecl = D;
  352. return DeclComment->second;
  353. }
  354. }
  355. // Any comment attached to any redeclaration of D?
  356. const Decl *CanonicalD = D->getCanonicalDecl();
  357. if (!CanonicalD)
  358. return nullptr;
  359. {
  360. auto RedeclComment = RedeclChainComments.find(CanonicalD);
  361. if (RedeclComment != RedeclChainComments.end()) {
  362. if (OriginalDecl)
  363. *OriginalDecl = RedeclComment->second;
  364. auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
  365. assert(CommentAtRedecl != DeclRawComments.end() &&
  366. "This decl is supposed to have comment attached.");
  367. return CommentAtRedecl->second;
  368. }
  369. }
  370. // Any redeclarations of D that we haven't checked for comments yet?
  371. // We can't use DenseMap::iterator directly since it'd get invalid.
  372. auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
  373. auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
  374. if (LookupRes != CommentlessRedeclChains.end())
  375. return LookupRes->second;
  376. return nullptr;
  377. }();
  378. for (const auto Redecl : D->redecls()) {
  379. assert(Redecl);
  380. // Skip all redeclarations that have been checked previously.
  381. if (LastCheckedRedecl) {
  382. if (LastCheckedRedecl == Redecl) {
  383. LastCheckedRedecl = nullptr;
  384. }
  385. continue;
  386. }
  387. const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
  388. if (RedeclComment) {
  389. cacheRawCommentForDecl(*Redecl, *RedeclComment);
  390. if (OriginalDecl)
  391. *OriginalDecl = Redecl;
  392. return RedeclComment;
  393. }
  394. CommentlessRedeclChains[CanonicalD] = Redecl;
  395. }
  396. if (OriginalDecl)
  397. *OriginalDecl = nullptr;
  398. return nullptr;
  399. }
  400. void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
  401. const RawComment &Comment) const {
  402. assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
  403. DeclRawComments.try_emplace(&OriginalD, &Comment);
  404. const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
  405. RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
  406. CommentlessRedeclChains.erase(CanonicalDecl);
  407. }
  408. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  409. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  410. const DeclContext *DC = ObjCMethod->getDeclContext();
  411. if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  412. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  413. if (!ID)
  414. return;
  415. // Add redeclared method here.
  416. for (const auto *Ext : ID->known_extensions()) {
  417. if (ObjCMethodDecl *RedeclaredMethod =
  418. Ext->getMethod(ObjCMethod->getSelector(),
  419. ObjCMethod->isInstanceMethod()))
  420. Redeclared.push_back(RedeclaredMethod);
  421. }
  422. }
  423. }
  424. void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
  425. const Preprocessor *PP) {
  426. if (Comments.empty() || Decls.empty())
  427. return;
  428. FileID File;
  429. for (Decl *D : Decls) {
  430. SourceLocation Loc = D->getLocation();
  431. if (Loc.isValid()) {
  432. // See if there are any new comments that are not attached to a decl.
  433. // The location doesn't have to be precise - we care only about the file.
  434. File = SourceMgr.getDecomposedLoc(Loc).first;
  435. break;
  436. }
  437. }
  438. if (File.isInvalid())
  439. return;
  440. auto CommentsInThisFile = Comments.getCommentsInFile(File);
  441. if (!CommentsInThisFile || CommentsInThisFile->empty() ||
  442. CommentsInThisFile->rbegin()->second->isAttached())
  443. return;
  444. // There is at least one comment not attached to a decl.
  445. // Maybe it should be attached to one of Decls?
  446. //
  447. // Note that this way we pick up not only comments that precede the
  448. // declaration, but also comments that *follow* the declaration -- thanks to
  449. // the lookahead in the lexer: we've consumed the semicolon and looked
  450. // ahead through comments.
  451. for (const Decl *D : Decls) {
  452. assert(D);
  453. if (D->isInvalidDecl())
  454. continue;
  455. D = &adjustDeclToTemplate(*D);
  456. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  457. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  458. continue;
  459. if (DeclRawComments.count(D) > 0)
  460. continue;
  461. if (RawComment *const DocComment =
  462. getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
  463. cacheRawCommentForDecl(*D, *DocComment);
  464. comments::FullComment *FC = DocComment->parse(*this, PP, D);
  465. ParsedComments[D->getCanonicalDecl()] = FC;
  466. }
  467. }
  468. }
  469. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  470. const Decl *D) const {
  471. auto *ThisDeclInfo = new (*this) comments::DeclInfo;
  472. ThisDeclInfo->CommentDecl = D;
  473. ThisDeclInfo->IsFilled = false;
  474. ThisDeclInfo->fill();
  475. ThisDeclInfo->CommentDecl = FC->getDecl();
  476. if (!ThisDeclInfo->TemplateParameters)
  477. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  478. comments::FullComment *CFC =
  479. new (*this) comments::FullComment(FC->getBlocks(),
  480. ThisDeclInfo);
  481. return CFC;
  482. }
  483. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  484. const RawComment *RC = getRawCommentForDeclNoCache(D);
  485. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  486. }
  487. comments::FullComment *ASTContext::getCommentForDecl(
  488. const Decl *D,
  489. const Preprocessor *PP) const {
  490. if (!D || D->isInvalidDecl())
  491. return nullptr;
  492. D = &adjustDeclToTemplate(*D);
  493. const Decl *Canonical = D->getCanonicalDecl();
  494. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  495. ParsedComments.find(Canonical);
  496. if (Pos != ParsedComments.end()) {
  497. if (Canonical != D) {
  498. comments::FullComment *FC = Pos->second;
  499. comments::FullComment *CFC = cloneFullComment(FC, D);
  500. return CFC;
  501. }
  502. return Pos->second;
  503. }
  504. const Decl *OriginalDecl = nullptr;
  505. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  506. if (!RC) {
  507. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  508. SmallVector<const NamedDecl*, 8> Overridden;
  509. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  510. if (OMD && OMD->isPropertyAccessor())
  511. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  512. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  513. return cloneFullComment(FC, D);
  514. if (OMD)
  515. addRedeclaredMethods(OMD, Overridden);
  516. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  517. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  518. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  519. return cloneFullComment(FC, D);
  520. }
  521. else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  522. // Attach any tag type's documentation to its typedef if latter
  523. // does not have one of its own.
  524. QualType QT = TD->getUnderlyingType();
  525. if (const auto *TT = QT->getAs<TagType>())
  526. if (const Decl *TD = TT->getDecl())
  527. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  528. return cloneFullComment(FC, D);
  529. }
  530. else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  531. while (IC->getSuperClass()) {
  532. IC = IC->getSuperClass();
  533. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  534. return cloneFullComment(FC, D);
  535. }
  536. }
  537. else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  538. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  539. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  540. return cloneFullComment(FC, D);
  541. }
  542. else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  543. if (!(RD = RD->getDefinition()))
  544. return nullptr;
  545. // Check non-virtual bases.
  546. for (const auto &I : RD->bases()) {
  547. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  548. continue;
  549. QualType Ty = I.getType();
  550. if (Ty.isNull())
  551. continue;
  552. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  553. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  554. continue;
  555. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  556. return cloneFullComment(FC, D);
  557. }
  558. }
  559. // Check virtual bases.
  560. for (const auto &I : RD->vbases()) {
  561. if (I.getAccessSpecifier() != AS_public)
  562. continue;
  563. QualType Ty = I.getType();
  564. if (Ty.isNull())
  565. continue;
  566. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  567. if (!(VirtualBase= VirtualBase->getDefinition()))
  568. continue;
  569. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  570. return cloneFullComment(FC, D);
  571. }
  572. }
  573. }
  574. return nullptr;
  575. }
  576. // If the RawComment was attached to other redeclaration of this Decl, we
  577. // should parse the comment in context of that other Decl. This is important
  578. // because comments can contain references to parameter names which can be
  579. // different across redeclarations.
  580. if (D != OriginalDecl && OriginalDecl)
  581. return getCommentForDecl(OriginalDecl, PP);
  582. comments::FullComment *FC = RC->parse(*this, PP, D);
  583. ParsedComments[Canonical] = FC;
  584. return FC;
  585. }
  586. void
  587. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  588. const ASTContext &C,
  589. TemplateTemplateParmDecl *Parm) {
  590. ID.AddInteger(Parm->getDepth());
  591. ID.AddInteger(Parm->getPosition());
  592. ID.AddBoolean(Parm->isParameterPack());
  593. TemplateParameterList *Params = Parm->getTemplateParameters();
  594. ID.AddInteger(Params->size());
  595. for (TemplateParameterList::const_iterator P = Params->begin(),
  596. PEnd = Params->end();
  597. P != PEnd; ++P) {
  598. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  599. ID.AddInteger(0);
  600. ID.AddBoolean(TTP->isParameterPack());
  601. const TypeConstraint *TC = TTP->getTypeConstraint();
  602. ID.AddBoolean(TC != nullptr);
  603. if (TC)
  604. TC->getImmediatelyDeclaredConstraint()->Profile(ID, C,
  605. /*Canonical=*/true);
  606. if (TTP->isExpandedParameterPack()) {
  607. ID.AddBoolean(true);
  608. ID.AddInteger(TTP->getNumExpansionParameters());
  609. } else
  610. ID.AddBoolean(false);
  611. continue;
  612. }
  613. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  614. ID.AddInteger(1);
  615. ID.AddBoolean(NTTP->isParameterPack());
  616. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  617. if (NTTP->isExpandedParameterPack()) {
  618. ID.AddBoolean(true);
  619. ID.AddInteger(NTTP->getNumExpansionTypes());
  620. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  621. QualType T = NTTP->getExpansionType(I);
  622. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  623. }
  624. } else
  625. ID.AddBoolean(false);
  626. continue;
  627. }
  628. auto *TTP = cast<TemplateTemplateParmDecl>(*P);
  629. ID.AddInteger(2);
  630. Profile(ID, C, TTP);
  631. }
  632. Expr *RequiresClause = Parm->getTemplateParameters()->getRequiresClause();
  633. ID.AddBoolean(RequiresClause != nullptr);
  634. if (RequiresClause)
  635. RequiresClause->Profile(ID, C, /*Canonical=*/true);
  636. }
  637. static Expr *
  638. canonicalizeImmediatelyDeclaredConstraint(const ASTContext &C, Expr *IDC,
  639. QualType ConstrainedType) {
  640. // This is a bit ugly - we need to form a new immediately-declared
  641. // constraint that references the new parameter; this would ideally
  642. // require semantic analysis (e.g. template<C T> struct S {}; - the
  643. // converted arguments of C<T> could be an argument pack if C is
  644. // declared as template<typename... T> concept C = ...).
  645. // We don't have semantic analysis here so we dig deep into the
  646. // ready-made constraint expr and change the thing manually.
  647. ConceptSpecializationExpr *CSE;
  648. if (const auto *Fold = dyn_cast<CXXFoldExpr>(IDC))
  649. CSE = cast<ConceptSpecializationExpr>(Fold->getLHS());
  650. else
  651. CSE = cast<ConceptSpecializationExpr>(IDC);
  652. ArrayRef<TemplateArgument> OldConverted = CSE->getTemplateArguments();
  653. SmallVector<TemplateArgument, 3> NewConverted;
  654. NewConverted.reserve(OldConverted.size());
  655. if (OldConverted.front().getKind() == TemplateArgument::Pack) {
  656. // The case:
  657. // template<typename... T> concept C = true;
  658. // template<C<int> T> struct S; -> constraint is C<{T, int}>
  659. NewConverted.push_back(ConstrainedType);
  660. for (auto &Arg : OldConverted.front().pack_elements().drop_front(1))
  661. NewConverted.push_back(Arg);
  662. TemplateArgument NewPack(NewConverted);
  663. NewConverted.clear();
  664. NewConverted.push_back(NewPack);
  665. assert(OldConverted.size() == 1 &&
  666. "Template parameter pack should be the last parameter");
  667. } else {
  668. assert(OldConverted.front().getKind() == TemplateArgument::Type &&
  669. "Unexpected first argument kind for immediately-declared "
  670. "constraint");
  671. NewConverted.push_back(ConstrainedType);
  672. for (auto &Arg : OldConverted.drop_front(1))
  673. NewConverted.push_back(Arg);
  674. }
  675. Expr *NewIDC = ConceptSpecializationExpr::Create(
  676. C, CSE->getNamedConcept(), NewConverted, nullptr,
  677. CSE->isInstantiationDependent(), CSE->containsUnexpandedParameterPack());
  678. if (auto *OrigFold = dyn_cast<CXXFoldExpr>(IDC))
  679. NewIDC = new (C) CXXFoldExpr(
  680. OrigFold->getType(), /*Callee*/nullptr, SourceLocation(), NewIDC,
  681. BinaryOperatorKind::BO_LAnd, SourceLocation(), /*RHS=*/nullptr,
  682. SourceLocation(), /*NumExpansions=*/None);
  683. return NewIDC;
  684. }
  685. TemplateTemplateParmDecl *
  686. ASTContext::getCanonicalTemplateTemplateParmDecl(
  687. TemplateTemplateParmDecl *TTP) const {
  688. // Check if we already have a canonical template template parameter.
  689. llvm::FoldingSetNodeID ID;
  690. CanonicalTemplateTemplateParm::Profile(ID, *this, TTP);
  691. void *InsertPos = nullptr;
  692. CanonicalTemplateTemplateParm *Canonical
  693. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  694. if (Canonical)
  695. return Canonical->getParam();
  696. // Build a canonical template parameter list.
  697. TemplateParameterList *Params = TTP->getTemplateParameters();
  698. SmallVector<NamedDecl *, 4> CanonParams;
  699. CanonParams.reserve(Params->size());
  700. for (TemplateParameterList::const_iterator P = Params->begin(),
  701. PEnd = Params->end();
  702. P != PEnd; ++P) {
  703. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  704. TemplateTypeParmDecl *NewTTP = TemplateTypeParmDecl::Create(*this,
  705. getTranslationUnitDecl(), SourceLocation(), SourceLocation(),
  706. TTP->getDepth(), TTP->getIndex(), nullptr, false,
  707. TTP->isParameterPack(), TTP->hasTypeConstraint(),
  708. TTP->isExpandedParameterPack() ?
  709. llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
  710. if (const auto *TC = TTP->getTypeConstraint()) {
  711. QualType ParamAsArgument(NewTTP->getTypeForDecl(), 0);
  712. Expr *NewIDC = canonicalizeImmediatelyDeclaredConstraint(
  713. *this, TC->getImmediatelyDeclaredConstraint(),
  714. ParamAsArgument);
  715. TemplateArgumentListInfo CanonArgsAsWritten;
  716. if (auto *Args = TC->getTemplateArgsAsWritten())
  717. for (const auto &ArgLoc : Args->arguments())
  718. CanonArgsAsWritten.addArgument(
  719. TemplateArgumentLoc(ArgLoc.getArgument(),
  720. TemplateArgumentLocInfo()));
  721. NewTTP->setTypeConstraint(
  722. NestedNameSpecifierLoc(),
  723. DeclarationNameInfo(TC->getNamedConcept()->getDeclName(),
  724. SourceLocation()), /*FoundDecl=*/nullptr,
  725. // Actually canonicalizing a TemplateArgumentLoc is difficult so we
  726. // simply omit the ArgsAsWritten
  727. TC->getNamedConcept(), /*ArgsAsWritten=*/nullptr, NewIDC);
  728. }
  729. CanonParams.push_back(NewTTP);
  730. } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  731. QualType T = getCanonicalType(NTTP->getType());
  732. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  733. NonTypeTemplateParmDecl *Param;
  734. if (NTTP->isExpandedParameterPack()) {
  735. SmallVector<QualType, 2> ExpandedTypes;
  736. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  737. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  738. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  739. ExpandedTInfos.push_back(
  740. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  741. }
  742. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  743. SourceLocation(),
  744. SourceLocation(),
  745. NTTP->getDepth(),
  746. NTTP->getPosition(), nullptr,
  747. T,
  748. TInfo,
  749. ExpandedTypes,
  750. ExpandedTInfos);
  751. } else {
  752. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  753. SourceLocation(),
  754. SourceLocation(),
  755. NTTP->getDepth(),
  756. NTTP->getPosition(), nullptr,
  757. T,
  758. NTTP->isParameterPack(),
  759. TInfo);
  760. }
  761. if (AutoType *AT = T->getContainedAutoType()) {
  762. if (AT->isConstrained()) {
  763. Param->setPlaceholderTypeConstraint(
  764. canonicalizeImmediatelyDeclaredConstraint(
  765. *this, NTTP->getPlaceholderTypeConstraint(), T));
  766. }
  767. }
  768. CanonParams.push_back(Param);
  769. } else
  770. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  771. cast<TemplateTemplateParmDecl>(*P)));
  772. }
  773. Expr *CanonRequiresClause = nullptr;
  774. if (Expr *RequiresClause = TTP->getTemplateParameters()->getRequiresClause())
  775. CanonRequiresClause = RequiresClause;
  776. TemplateTemplateParmDecl *CanonTTP
  777. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  778. SourceLocation(), TTP->getDepth(),
  779. TTP->getPosition(),
  780. TTP->isParameterPack(),
  781. nullptr,
  782. TemplateParameterList::Create(*this, SourceLocation(),
  783. SourceLocation(),
  784. CanonParams,
  785. SourceLocation(),
  786. CanonRequiresClause));
  787. // Get the new insert position for the node we care about.
  788. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  789. assert(!Canonical && "Shouldn't be in the map!");
  790. (void)Canonical;
  791. // Create the canonical template template parameter entry.
  792. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  793. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  794. return CanonTTP;
  795. }
  796. TargetCXXABI::Kind ASTContext::getCXXABIKind() const {
  797. auto Kind = getTargetInfo().getCXXABI().getKind();
  798. return getLangOpts().CXXABI.getValueOr(Kind);
  799. }
  800. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  801. if (!LangOpts.CPlusPlus) return nullptr;
  802. switch (getCXXABIKind()) {
  803. case TargetCXXABI::AppleARM64:
  804. case TargetCXXABI::Fuchsia:
  805. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  806. case TargetCXXABI::iOS:
  807. case TargetCXXABI::WatchOS:
  808. case TargetCXXABI::GenericAArch64:
  809. case TargetCXXABI::GenericMIPS:
  810. case TargetCXXABI::GenericItanium:
  811. case TargetCXXABI::WebAssembly:
  812. case TargetCXXABI::XL:
  813. return CreateItaniumCXXABI(*this);
  814. case TargetCXXABI::Microsoft:
  815. return CreateMicrosoftCXXABI(*this);
  816. }
  817. llvm_unreachable("Invalid CXXABI type!");
  818. }
  819. interp::Context &ASTContext::getInterpContext() {
  820. if (!InterpContext) {
  821. InterpContext.reset(new interp::Context(*this));
  822. }
  823. return *InterpContext.get();
  824. }
  825. ParentMapContext &ASTContext::getParentMapContext() {
  826. if (!ParentMapCtx)
  827. ParentMapCtx.reset(new ParentMapContext(*this));
  828. return *ParentMapCtx.get();
  829. }
  830. static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
  831. const LangOptions &LOpts) {
  832. if (LOpts.FakeAddressSpaceMap) {
  833. // The fake address space map must have a distinct entry for each
  834. // language-specific address space.
  835. static const unsigned FakeAddrSpaceMap[] = {
  836. 0, // Default
  837. 1, // opencl_global
  838. 3, // opencl_local
  839. 2, // opencl_constant
  840. 0, // opencl_private
  841. 4, // opencl_generic
  842. 5, // opencl_global_device
  843. 6, // opencl_global_host
  844. 7, // cuda_device
  845. 8, // cuda_constant
  846. 9, // cuda_shared
  847. 1, // sycl_global
  848. 5, // sycl_global_device
  849. 6, // sycl_global_host
  850. 3, // sycl_local
  851. 0, // sycl_private
  852. 10, // ptr32_sptr
  853. 11, // ptr32_uptr
  854. 12 // ptr64
  855. };
  856. return &FakeAddrSpaceMap;
  857. } else {
  858. return &T.getAddressSpaceMap();
  859. }
  860. }
  861. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  862. const LangOptions &LangOpts) {
  863. switch (LangOpts.getAddressSpaceMapMangling()) {
  864. case LangOptions::ASMM_Target:
  865. return TI.useAddressSpaceMapMangling();
  866. case LangOptions::ASMM_On:
  867. return true;
  868. case LangOptions::ASMM_Off:
  869. return false;
  870. }
  871. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  872. }
  873. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  874. IdentifierTable &idents, SelectorTable &sels,
  875. Builtin::Context &builtins, TranslationUnitKind TUKind)
  876. : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
  877. TemplateSpecializationTypes(this_()),
  878. DependentTemplateSpecializationTypes(this_()), AutoTypes(this_()),
  879. SubstTemplateTemplateParmPacks(this_()),
  880. CanonTemplateTemplateParms(this_()), SourceMgr(SM), LangOpts(LOpts),
  881. NoSanitizeL(new NoSanitizeList(LangOpts.NoSanitizeFiles, SM)),
  882. XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
  883. LangOpts.XRayNeverInstrumentFiles,
  884. LangOpts.XRayAttrListFiles, SM)),
  885. ProfList(new ProfileList(LangOpts.ProfileListFiles, SM)),
  886. PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
  887. BuiltinInfo(builtins), TUKind(TUKind), DeclarationNames(*this),
  888. Comments(SM), CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
  889. CompCategories(this_()), LastSDM(nullptr, 0) {
  890. addTranslationUnitDecl();
  891. }
  892. void ASTContext::cleanup() {
  893. // Release the DenseMaps associated with DeclContext objects.
  894. // FIXME: Is this the ideal solution?
  895. ReleaseDeclContextMaps();
  896. // Call all of the deallocation functions on all of their targets.
  897. for (auto &Pair : Deallocations)
  898. (Pair.first)(Pair.second);
  899. Deallocations.clear();
  900. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  901. // because they can contain DenseMaps.
  902. for (llvm::DenseMap<const ObjCContainerDecl*,
  903. const ASTRecordLayout*>::iterator
  904. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  905. // Increment in loop to prevent using deallocated memory.
  906. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  907. R->Destroy(*this);
  908. ObjCLayouts.clear();
  909. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  910. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  911. // Increment in loop to prevent using deallocated memory.
  912. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  913. R->Destroy(*this);
  914. }
  915. ASTRecordLayouts.clear();
  916. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  917. AEnd = DeclAttrs.end();
  918. A != AEnd; ++A)
  919. A->second->~AttrVec();
  920. DeclAttrs.clear();
  921. for (const auto &Value : ModuleInitializers)
  922. Value.second->~PerModuleInitializers();
  923. ModuleInitializers.clear();
  924. }
  925. ASTContext::~ASTContext() { cleanup(); }
  926. void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
  927. TraversalScope = TopLevelDecls;
  928. getParentMapContext().clear();
  929. }
  930. void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
  931. Deallocations.push_back({Callback, Data});
  932. }
  933. void
  934. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  935. ExternalSource = std::move(Source);
  936. }
  937. void ASTContext::PrintStats() const {
  938. llvm::errs() << "\n*** AST Context Stats:\n";
  939. llvm::errs() << " " << Types.size() << " types total.\n";
  940. unsigned counts[] = {
  941. #define TYPE(Name, Parent) 0,
  942. #define ABSTRACT_TYPE(Name, Parent)
  943. #include "clang/AST/TypeNodes.inc"
  944. 0 // Extra
  945. };
  946. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  947. Type *T = Types[i];
  948. counts[(unsigned)T->getTypeClass()]++;
  949. }
  950. unsigned Idx = 0;
  951. unsigned TotalBytes = 0;
  952. #define TYPE(Name, Parent) \
  953. if (counts[Idx]) \
  954. llvm::errs() << " " << counts[Idx] << " " << #Name \
  955. << " types, " << sizeof(Name##Type) << " each " \
  956. << "(" << counts[Idx] * sizeof(Name##Type) \
  957. << " bytes)\n"; \
  958. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  959. ++Idx;
  960. #define ABSTRACT_TYPE(Name, Parent)
  961. #include "clang/AST/TypeNodes.inc"
  962. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  963. // Implicit special member functions.
  964. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  965. << NumImplicitDefaultConstructors
  966. << " implicit default constructors created\n";
  967. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  968. << NumImplicitCopyConstructors
  969. << " implicit copy constructors created\n";
  970. if (getLangOpts().CPlusPlus)
  971. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  972. << NumImplicitMoveConstructors
  973. << " implicit move constructors created\n";
  974. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  975. << NumImplicitCopyAssignmentOperators
  976. << " implicit copy assignment operators created\n";
  977. if (getLangOpts().CPlusPlus)
  978. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  979. << NumImplicitMoveAssignmentOperators
  980. << " implicit move assignment operators created\n";
  981. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  982. << NumImplicitDestructors
  983. << " implicit destructors created\n";
  984. if (ExternalSource) {
  985. llvm::errs() << "\n";
  986. ExternalSource->PrintStats();
  987. }
  988. BumpAlloc.PrintStats();
  989. }
  990. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  991. bool NotifyListeners) {
  992. if (NotifyListeners)
  993. if (auto *Listener = getASTMutationListener())
  994. Listener->RedefinedHiddenDefinition(ND, M);
  995. MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
  996. }
  997. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  998. auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
  999. if (It == MergedDefModules.end())
  1000. return;
  1001. auto &Merged = It->second;
  1002. llvm::DenseSet<Module*> Found;
  1003. for (Module *&M : Merged)
  1004. if (!Found.insert(M).second)
  1005. M = nullptr;
  1006. llvm::erase_value(Merged, nullptr);
  1007. }
  1008. ArrayRef<Module *>
  1009. ASTContext::getModulesWithMergedDefinition(const NamedDecl *Def) {
  1010. auto MergedIt =
  1011. MergedDefModules.find(cast<NamedDecl>(Def->getCanonicalDecl()));
  1012. if (MergedIt == MergedDefModules.end())
  1013. return None;
  1014. return MergedIt->second;
  1015. }
  1016. void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
  1017. if (LazyInitializers.empty())
  1018. return;
  1019. auto *Source = Ctx.getExternalSource();
  1020. assert(Source && "lazy initializers but no external source");
  1021. auto LazyInits = std::move(LazyInitializers);
  1022. LazyInitializers.clear();
  1023. for (auto ID : LazyInits)
  1024. Initializers.push_back(Source->GetExternalDecl(ID));
  1025. assert(LazyInitializers.empty() &&
  1026. "GetExternalDecl for lazy module initializer added more inits");
  1027. }
  1028. void ASTContext::addModuleInitializer(Module *M, Decl *D) {
  1029. // One special case: if we add a module initializer that imports another
  1030. // module, and that module's only initializer is an ImportDecl, simplify.
  1031. if (const auto *ID = dyn_cast<ImportDecl>(D)) {
  1032. auto It = ModuleInitializers.find(ID->getImportedModule());
  1033. // Maybe the ImportDecl does nothing at all. (Common case.)
  1034. if (It == ModuleInitializers.end())
  1035. return;
  1036. // Maybe the ImportDecl only imports another ImportDecl.
  1037. auto &Imported = *It->second;
  1038. if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
  1039. Imported.resolve(*this);
  1040. auto *OnlyDecl = Imported.Initializers.front();
  1041. if (isa<ImportDecl>(OnlyDecl))
  1042. D = OnlyDecl;
  1043. }
  1044. }
  1045. auto *&Inits = ModuleInitializers[M];
  1046. if (!Inits)
  1047. Inits = new (*this) PerModuleInitializers;
  1048. Inits->Initializers.push_back(D);
  1049. }
  1050. void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
  1051. auto *&Inits = ModuleInitializers[M];
  1052. if (!Inits)
  1053. Inits = new (*this) PerModuleInitializers;
  1054. Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
  1055. IDs.begin(), IDs.end());
  1056. }
  1057. ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
  1058. auto It = ModuleInitializers.find(M);
  1059. if (It == ModuleInitializers.end())
  1060. return None;
  1061. auto *Inits = It->second;
  1062. Inits->resolve(*this);
  1063. return Inits->Initializers;
  1064. }
  1065. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  1066. if (!ExternCContext)
  1067. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  1068. return ExternCContext;
  1069. }
  1070. BuiltinTemplateDecl *
  1071. ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
  1072. const IdentifierInfo *II) const {
  1073. auto *BuiltinTemplate =
  1074. BuiltinTemplateDecl::Create(*this, getTranslationUnitDecl(), II, BTK);
  1075. BuiltinTemplate->setImplicit();
  1076. getTranslationUnitDecl()->addDecl(BuiltinTemplate);
  1077. return BuiltinTemplate;
  1078. }
  1079. BuiltinTemplateDecl *
  1080. ASTContext::getMakeIntegerSeqDecl() const {
  1081. if (!MakeIntegerSeqDecl)
  1082. MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
  1083. getMakeIntegerSeqName());
  1084. return MakeIntegerSeqDecl;
  1085. }
  1086. BuiltinTemplateDecl *
  1087. ASTContext::getTypePackElementDecl() const {
  1088. if (!TypePackElementDecl)
  1089. TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
  1090. getTypePackElementName());
  1091. return TypePackElementDecl;
  1092. }
  1093. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  1094. RecordDecl::TagKind TK) const {
  1095. SourceLocation Loc;
  1096. RecordDecl *NewDecl;
  1097. if (getLangOpts().CPlusPlus)
  1098. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  1099. Loc, &Idents.get(Name));
  1100. else
  1101. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  1102. &Idents.get(Name));
  1103. NewDecl->setImplicit();
  1104. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  1105. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  1106. return NewDecl;
  1107. }
  1108. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  1109. StringRef Name) const {
  1110. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  1111. TypedefDecl *NewDecl = TypedefDecl::Create(
  1112. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  1113. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  1114. NewDecl->setImplicit();
  1115. return NewDecl;
  1116. }
  1117. TypedefDecl *ASTContext::getInt128Decl() const {
  1118. if (!Int128Decl)
  1119. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  1120. return Int128Decl;
  1121. }
  1122. TypedefDecl *ASTContext::getUInt128Decl() const {
  1123. if (!UInt128Decl)
  1124. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  1125. return UInt128Decl;
  1126. }
  1127. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  1128. auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
  1129. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  1130. Types.push_back(Ty);
  1131. }
  1132. void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
  1133. const TargetInfo *AuxTarget) {
  1134. assert((!this->Target || this->Target == &Target) &&
  1135. "Incorrect target reinitialization");
  1136. assert(VoidTy.isNull() && "Context reinitialized?");
  1137. this->Target = &Target;
  1138. this->AuxTarget = AuxTarget;
  1139. ABI.reset(createCXXABI(Target));
  1140. AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
  1141. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  1142. // C99 6.2.5p19.
  1143. InitBuiltinType(VoidTy, BuiltinType::Void);
  1144. // C99 6.2.5p2.
  1145. InitBuiltinType(BoolTy, BuiltinType::Bool);
  1146. // C99 6.2.5p3.
  1147. if (LangOpts.CharIsSigned)
  1148. InitBuiltinType(CharTy, BuiltinType::Char_S);
  1149. else
  1150. InitBuiltinType(CharTy, BuiltinType::Char_U);
  1151. // C99 6.2.5p4.
  1152. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  1153. InitBuiltinType(ShortTy, BuiltinType::Short);
  1154. InitBuiltinType(IntTy, BuiltinType::Int);
  1155. InitBuiltinType(LongTy, BuiltinType::Long);
  1156. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  1157. // C99 6.2.5p6.
  1158. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  1159. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  1160. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  1161. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  1162. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  1163. // C99 6.2.5p10.
  1164. InitBuiltinType(FloatTy, BuiltinType::Float);
  1165. InitBuiltinType(DoubleTy, BuiltinType::Double);
  1166. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  1167. // GNU extension, __float128 for IEEE quadruple precision
  1168. InitBuiltinType(Float128Ty, BuiltinType::Float128);
  1169. // __ibm128 for IBM extended precision
  1170. InitBuiltinType(Ibm128Ty, BuiltinType::Ibm128);
  1171. // C11 extension ISO/IEC TS 18661-3
  1172. InitBuiltinType(Float16Ty, BuiltinType::Float16);
  1173. // ISO/IEC JTC1 SC22 WG14 N1169 Extension
  1174. InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
  1175. InitBuiltinType(AccumTy, BuiltinType::Accum);
  1176. InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
  1177. InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
  1178. InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
  1179. InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
  1180. InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
  1181. InitBuiltinType(FractTy, BuiltinType::Fract);
  1182. InitBuiltinType(LongFractTy, BuiltinType::LongFract);
  1183. InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
  1184. InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
  1185. InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
  1186. InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
  1187. InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
  1188. InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
  1189. InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
  1190. InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
  1191. InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
  1192. InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
  1193. InitBuiltinType(SatFractTy, BuiltinType::SatFract);
  1194. InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
  1195. InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
  1196. InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
  1197. InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
  1198. // GNU extension, 128-bit integers.
  1199. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  1200. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  1201. // C++ 3.9.1p5
  1202. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  1203. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  1204. else // -fshort-wchar makes wchar_t be unsigned.
  1205. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  1206. if (LangOpts.CPlusPlus && LangOpts.WChar)
  1207. WideCharTy = WCharTy;
  1208. else {
  1209. // C99 (or C++ using -fno-wchar).
  1210. WideCharTy = getFromTargetType(Target.getWCharType());
  1211. }
  1212. WIntTy = getFromTargetType(Target.getWIntType());
  1213. // C++20 (proposed)
  1214. InitBuiltinType(Char8Ty, BuiltinType::Char8);
  1215. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1216. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  1217. else // C99
  1218. Char16Ty = getFromTargetType(Target.getChar16Type());
  1219. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1220. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  1221. else // C99
  1222. Char32Ty = getFromTargetType(Target.getChar32Type());
  1223. // Placeholder type for type-dependent expressions whose type is
  1224. // completely unknown. No code should ever check a type against
  1225. // DependentTy and users should never see it; however, it is here to
  1226. // help diagnose failures to properly check for type-dependent
  1227. // expressions.
  1228. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  1229. // Placeholder type for functions.
  1230. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  1231. // Placeholder type for bound members.
  1232. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  1233. // Placeholder type for pseudo-objects.
  1234. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  1235. // "any" type; useful for debugger-like clients.
  1236. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  1237. // Placeholder type for unbridged ARC casts.
  1238. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  1239. // Placeholder type for builtin functions.
  1240. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  1241. // Placeholder type for OMP array sections.
  1242. if (LangOpts.OpenMP) {
  1243. InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
  1244. InitBuiltinType(OMPArrayShapingTy, BuiltinType::OMPArrayShaping);
  1245. InitBuiltinType(OMPIteratorTy, BuiltinType::OMPIterator);
  1246. }
  1247. if (LangOpts.MatrixTypes)
  1248. InitBuiltinType(IncompleteMatrixIdxTy, BuiltinType::IncompleteMatrixIdx);
  1249. // Builtin types for 'id', 'Class', and 'SEL'.
  1250. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  1251. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  1252. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  1253. if (LangOpts.OpenCL) {
  1254. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1255. InitBuiltinType(SingletonId, BuiltinType::Id);
  1256. #include "clang/Basic/OpenCLImageTypes.def"
  1257. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  1258. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  1259. InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
  1260. InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
  1261. InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
  1262. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1263. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1264. #include "clang/Basic/OpenCLExtensionTypes.def"
  1265. }
  1266. if (Target.hasAArch64SVETypes()) {
  1267. #define SVE_TYPE(Name, Id, SingletonId) \
  1268. InitBuiltinType(SingletonId, BuiltinType::Id);
  1269. #include "clang/Basic/AArch64SVEACLETypes.def"
  1270. }
  1271. if (Target.getTriple().isPPC64()) {
  1272. #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
  1273. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1274. #include "clang/Basic/PPCTypes.def"
  1275. #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
  1276. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1277. #include "clang/Basic/PPCTypes.def"
  1278. }
  1279. if (Target.hasRISCVVTypes()) {
  1280. #define RVV_TYPE(Name, Id, SingletonId) \
  1281. InitBuiltinType(SingletonId, BuiltinType::Id);
  1282. #include "clang/Basic/RISCVVTypes.def"
  1283. }
  1284. // Builtin type for __objc_yes and __objc_no
  1285. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  1286. SignedCharTy : BoolTy);
  1287. ObjCConstantStringType = QualType();
  1288. ObjCSuperType = QualType();
  1289. // void * type
  1290. if (LangOpts.OpenCLGenericAddressSpace) {
  1291. auto Q = VoidTy.getQualifiers();
  1292. Q.setAddressSpace(LangAS::opencl_generic);
  1293. VoidPtrTy = getPointerType(getCanonicalType(
  1294. getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
  1295. } else {
  1296. VoidPtrTy = getPointerType(VoidTy);
  1297. }
  1298. // nullptr type (C++0x 2.14.7)
  1299. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  1300. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  1301. InitBuiltinType(HalfTy, BuiltinType::Half);
  1302. InitBuiltinType(BFloat16Ty, BuiltinType::BFloat16);
  1303. // Builtin type used to help define __builtin_va_list.
  1304. VaListTagDecl = nullptr;
  1305. // MSVC predeclares struct _GUID, and we need it to create MSGuidDecls.
  1306. if (LangOpts.MicrosoftExt || LangOpts.Borland) {
  1307. MSGuidTagDecl = buildImplicitRecord("_GUID");
  1308. getTranslationUnitDecl()->addDecl(MSGuidTagDecl);
  1309. }
  1310. }
  1311. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  1312. return SourceMgr.getDiagnostics();
  1313. }
  1314. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  1315. AttrVec *&Result = DeclAttrs[D];
  1316. if (!Result) {
  1317. void *Mem = Allocate(sizeof(AttrVec));
  1318. Result = new (Mem) AttrVec;
  1319. }
  1320. return *Result;
  1321. }
  1322. /// Erase the attributes corresponding to the given declaration.
  1323. void ASTContext::eraseDeclAttrs(const Decl *D) {
  1324. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  1325. if (Pos != DeclAttrs.end()) {
  1326. Pos->second->~AttrVec();
  1327. DeclAttrs.erase(Pos);
  1328. }
  1329. }
  1330. // FIXME: Remove ?
  1331. MemberSpecializationInfo *
  1332. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  1333. assert(Var->isStaticDataMember() && "Not a static data member");
  1334. return getTemplateOrSpecializationInfo(Var)
  1335. .dyn_cast<MemberSpecializationInfo *>();
  1336. }
  1337. ASTContext::TemplateOrSpecializationInfo
  1338. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  1339. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  1340. TemplateOrInstantiation.find(Var);
  1341. if (Pos == TemplateOrInstantiation.end())
  1342. return {};
  1343. return Pos->second;
  1344. }
  1345. void
  1346. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1347. TemplateSpecializationKind TSK,
  1348. SourceLocation PointOfInstantiation) {
  1349. assert(Inst->isStaticDataMember() && "Not a static data member");
  1350. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1351. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1352. Tmpl, TSK, PointOfInstantiation));
  1353. }
  1354. void
  1355. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1356. TemplateOrSpecializationInfo TSI) {
  1357. assert(!TemplateOrInstantiation[Inst] &&
  1358. "Already noted what the variable was instantiated from");
  1359. TemplateOrInstantiation[Inst] = TSI;
  1360. }
  1361. NamedDecl *
  1362. ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
  1363. auto Pos = InstantiatedFromUsingDecl.find(UUD);
  1364. if (Pos == InstantiatedFromUsingDecl.end())
  1365. return nullptr;
  1366. return Pos->second;
  1367. }
  1368. void
  1369. ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
  1370. assert((isa<UsingDecl>(Pattern) ||
  1371. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1372. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1373. "pattern decl is not a using decl");
  1374. assert((isa<UsingDecl>(Inst) ||
  1375. isa<UnresolvedUsingValueDecl>(Inst) ||
  1376. isa<UnresolvedUsingTypenameDecl>(Inst)) &&
  1377. "instantiation did not produce a using decl");
  1378. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1379. InstantiatedFromUsingDecl[Inst] = Pattern;
  1380. }
  1381. UsingEnumDecl *
  1382. ASTContext::getInstantiatedFromUsingEnumDecl(UsingEnumDecl *UUD) {
  1383. auto Pos = InstantiatedFromUsingEnumDecl.find(UUD);
  1384. if (Pos == InstantiatedFromUsingEnumDecl.end())
  1385. return nullptr;
  1386. return Pos->second;
  1387. }
  1388. void ASTContext::setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
  1389. UsingEnumDecl *Pattern) {
  1390. assert(!InstantiatedFromUsingEnumDecl[Inst] && "pattern already exists");
  1391. InstantiatedFromUsingEnumDecl[Inst] = Pattern;
  1392. }
  1393. UsingShadowDecl *
  1394. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1395. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1396. = InstantiatedFromUsingShadowDecl.find(Inst);
  1397. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1398. return nullptr;
  1399. return Pos->second;
  1400. }
  1401. void
  1402. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1403. UsingShadowDecl *Pattern) {
  1404. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1405. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1406. }
  1407. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1408. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1409. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1410. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1411. return nullptr;
  1412. return Pos->second;
  1413. }
  1414. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1415. FieldDecl *Tmpl) {
  1416. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1417. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1418. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1419. "Already noted what unnamed field was instantiated from");
  1420. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1421. }
  1422. ASTContext::overridden_cxx_method_iterator
  1423. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1424. return overridden_methods(Method).begin();
  1425. }
  1426. ASTContext::overridden_cxx_method_iterator
  1427. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1428. return overridden_methods(Method).end();
  1429. }
  1430. unsigned
  1431. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1432. auto Range = overridden_methods(Method);
  1433. return Range.end() - Range.begin();
  1434. }
  1435. ASTContext::overridden_method_range
  1436. ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
  1437. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
  1438. OverriddenMethods.find(Method->getCanonicalDecl());
  1439. if (Pos == OverriddenMethods.end())
  1440. return overridden_method_range(nullptr, nullptr);
  1441. return overridden_method_range(Pos->second.begin(), Pos->second.end());
  1442. }
  1443. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1444. const CXXMethodDecl *Overridden) {
  1445. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1446. OverriddenMethods[Method].push_back(Overridden);
  1447. }
  1448. void ASTContext::getOverriddenMethods(
  1449. const NamedDecl *D,
  1450. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1451. assert(D);
  1452. if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1453. Overridden.append(overridden_methods_begin(CXXMethod),
  1454. overridden_methods_end(CXXMethod));
  1455. return;
  1456. }
  1457. const auto *Method = dyn_cast<ObjCMethodDecl>(D);
  1458. if (!Method)
  1459. return;
  1460. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1461. Method->getOverriddenMethods(OverDecls);
  1462. Overridden.append(OverDecls.begin(), OverDecls.end());
  1463. }
  1464. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1465. assert(!Import->getNextLocalImport() &&
  1466. "Import declaration already in the chain");
  1467. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1468. if (!FirstLocalImport) {
  1469. FirstLocalImport = Import;
  1470. LastLocalImport = Import;
  1471. return;
  1472. }
  1473. LastLocalImport->setNextLocalImport(Import);
  1474. LastLocalImport = Import;
  1475. }
  1476. //===----------------------------------------------------------------------===//
  1477. // Type Sizing and Analysis
  1478. //===----------------------------------------------------------------------===//
  1479. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1480. /// scalar floating point type.
  1481. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1482. switch (T->castAs<BuiltinType>()->getKind()) {
  1483. default:
  1484. llvm_unreachable("Not a floating point type!");
  1485. case BuiltinType::BFloat16:
  1486. return Target->getBFloat16Format();
  1487. case BuiltinType::Float16:
  1488. case BuiltinType::Half:
  1489. return Target->getHalfFormat();
  1490. case BuiltinType::Float: return Target->getFloatFormat();
  1491. case BuiltinType::Double: return Target->getDoubleFormat();
  1492. case BuiltinType::Ibm128:
  1493. return Target->getIbm128Format();
  1494. case BuiltinType::LongDouble:
  1495. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1496. return AuxTarget->getLongDoubleFormat();
  1497. return Target->getLongDoubleFormat();
  1498. case BuiltinType::Float128:
  1499. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1500. return AuxTarget->getFloat128Format();
  1501. return Target->getFloat128Format();
  1502. }
  1503. }
  1504. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1505. unsigned Align = Target->getCharWidth();
  1506. bool UseAlignAttrOnly = false;
  1507. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1508. Align = AlignFromAttr;
  1509. // __attribute__((aligned)) can increase or decrease alignment
  1510. // *except* on a struct or struct member, where it only increases
  1511. // alignment unless 'packed' is also specified.
  1512. //
  1513. // It is an error for alignas to decrease alignment, so we can
  1514. // ignore that possibility; Sema should diagnose it.
  1515. if (isa<FieldDecl>(D)) {
  1516. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1517. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1518. } else {
  1519. UseAlignAttrOnly = true;
  1520. }
  1521. }
  1522. else if (isa<FieldDecl>(D))
  1523. UseAlignAttrOnly =
  1524. D->hasAttr<PackedAttr>() ||
  1525. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1526. // If we're using the align attribute only, just ignore everything
  1527. // else about the declaration and its type.
  1528. if (UseAlignAttrOnly) {
  1529. // do nothing
  1530. } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  1531. QualType T = VD->getType();
  1532. if (const auto *RT = T->getAs<ReferenceType>()) {
  1533. if (ForAlignof)
  1534. T = RT->getPointeeType();
  1535. else
  1536. T = getPointerType(RT->getPointeeType());
  1537. }
  1538. QualType BaseT = getBaseElementType(T);
  1539. if (T->isFunctionType())
  1540. Align = getTypeInfoImpl(T.getTypePtr()).Align;
  1541. else if (!BaseT->isIncompleteType()) {
  1542. // Adjust alignments of declarations with array type by the
  1543. // large-array alignment on the target.
  1544. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1545. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1546. if (!ForAlignof && MinWidth) {
  1547. if (isa<VariableArrayType>(arrayType))
  1548. Align = std::max(Align, Target->getLargeArrayAlign());
  1549. else if (isa<ConstantArrayType>(arrayType) &&
  1550. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1551. Align = std::max(Align, Target->getLargeArrayAlign());
  1552. }
  1553. }
  1554. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1555. if (BaseT.getQualifiers().hasUnaligned())
  1556. Align = Target->getCharWidth();
  1557. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1558. if (VD->hasGlobalStorage() && !ForAlignof) {
  1559. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  1560. Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
  1561. }
  1562. }
  1563. }
  1564. // Fields can be subject to extra alignment constraints, like if
  1565. // the field is packed, the struct is packed, or the struct has a
  1566. // a max-field-alignment constraint (#pragma pack). So calculate
  1567. // the actual alignment of the field within the struct, and then
  1568. // (as we're expected to) constrain that by the alignment of the type.
  1569. if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
  1570. const RecordDecl *Parent = Field->getParent();
  1571. // We can only produce a sensible answer if the record is valid.
  1572. if (!Parent->isInvalidDecl()) {
  1573. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1574. // Start with the record's overall alignment.
  1575. unsigned FieldAlign = toBits(Layout.getAlignment());
  1576. // Use the GCD of that and the offset within the record.
  1577. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1578. if (Offset > 0) {
  1579. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1580. // which means we get to do this crazy thing instead of Euclid's.
  1581. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1582. if (LowBitOfOffset < FieldAlign)
  1583. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1584. }
  1585. Align = std::min(Align, FieldAlign);
  1586. }
  1587. }
  1588. }
  1589. // Some targets have hard limitation on the maximum requestable alignment in
  1590. // aligned attribute for static variables.
  1591. const unsigned MaxAlignedAttr = getTargetInfo().getMaxAlignedAttribute();
  1592. const auto *VD = dyn_cast<VarDecl>(D);
  1593. if (MaxAlignedAttr && VD && VD->getStorageClass() == SC_Static)
  1594. Align = std::min(Align, MaxAlignedAttr);
  1595. return toCharUnitsFromBits(Align);
  1596. }
  1597. CharUnits ASTContext::getExnObjectAlignment() const {
  1598. return toCharUnitsFromBits(Target->getExnObjectAlignment());
  1599. }
  1600. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1601. // chars. If the type is a record, its data size is returned. This is
  1602. // the size of the memcpy that's performed when assigning this type
  1603. // using a trivial copy/move assignment operator.
  1604. TypeInfoChars ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1605. TypeInfoChars Info = getTypeInfoInChars(T);
  1606. // In C++, objects can sometimes be allocated into the tail padding
  1607. // of a base-class subobject. We decide whether that's possible
  1608. // during class layout, so here we can just trust the layout results.
  1609. if (getLangOpts().CPlusPlus) {
  1610. if (const auto *RT = T->getAs<RecordType>()) {
  1611. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1612. Info.Width = layout.getDataSize();
  1613. }
  1614. }
  1615. return Info;
  1616. }
  1617. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1618. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1619. TypeInfoChars
  1620. static getConstantArrayInfoInChars(const ASTContext &Context,
  1621. const ConstantArrayType *CAT) {
  1622. TypeInfoChars EltInfo = Context.getTypeInfoInChars(CAT->getElementType());
  1623. uint64_t Size = CAT->getSize().getZExtValue();
  1624. assert((Size == 0 || static_cast<uint64_t>(EltInfo.Width.getQuantity()) <=
  1625. (uint64_t)(-1)/Size) &&
  1626. "Overflow in array type char size evaluation");
  1627. uint64_t Width = EltInfo.Width.getQuantity() * Size;
  1628. unsigned Align = EltInfo.Align.getQuantity();
  1629. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1630. Context.getTargetInfo().getPointerWidth(0) == 64)
  1631. Width = llvm::alignTo(Width, Align);
  1632. return TypeInfoChars(CharUnits::fromQuantity(Width),
  1633. CharUnits::fromQuantity(Align),
  1634. EltInfo.AlignRequirement);
  1635. }
  1636. TypeInfoChars ASTContext::getTypeInfoInChars(const Type *T) const {
  1637. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1638. return getConstantArrayInfoInChars(*this, CAT);
  1639. TypeInfo Info = getTypeInfo(T);
  1640. return TypeInfoChars(toCharUnitsFromBits(Info.Width),
  1641. toCharUnitsFromBits(Info.Align), Info.AlignRequirement);
  1642. }
  1643. TypeInfoChars ASTContext::getTypeInfoInChars(QualType T) const {
  1644. return getTypeInfoInChars(T.getTypePtr());
  1645. }
  1646. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1647. return getTypeInfo(T).AlignRequirement != AlignRequirementKind::None;
  1648. }
  1649. bool ASTContext::isAlignmentRequired(QualType T) const {
  1650. return isAlignmentRequired(T.getTypePtr());
  1651. }
  1652. unsigned ASTContext::getTypeAlignIfKnown(QualType T,
  1653. bool NeedsPreferredAlignment) const {
  1654. // An alignment on a typedef overrides anything else.
  1655. if (const auto *TT = T->getAs<TypedefType>())
  1656. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1657. return Align;
  1658. // If we have an (array of) complete type, we're done.
  1659. T = getBaseElementType(T);
  1660. if (!T->isIncompleteType())
  1661. return NeedsPreferredAlignment ? getPreferredTypeAlign(T) : getTypeAlign(T);
  1662. // If we had an array type, its element type might be a typedef
  1663. // type with an alignment attribute.
  1664. if (const auto *TT = T->getAs<TypedefType>())
  1665. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1666. return Align;
  1667. // Otherwise, see if the declaration of the type had an attribute.
  1668. if (const auto *TT = T->getAs<TagType>())
  1669. return TT->getDecl()->getMaxAlignment();
  1670. return 0;
  1671. }
  1672. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1673. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1674. if (I != MemoizedTypeInfo.end())
  1675. return I->second;
  1676. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1677. TypeInfo TI = getTypeInfoImpl(T);
  1678. MemoizedTypeInfo[T] = TI;
  1679. return TI;
  1680. }
  1681. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1682. /// method does not work on incomplete types.
  1683. ///
  1684. /// FIXME: Pointers into different addr spaces could have different sizes and
  1685. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1686. /// should take a QualType, &c.
  1687. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1688. uint64_t Width = 0;
  1689. unsigned Align = 8;
  1690. AlignRequirementKind AlignRequirement = AlignRequirementKind::None;
  1691. unsigned AS = 0;
  1692. switch (T->getTypeClass()) {
  1693. #define TYPE(Class, Base)
  1694. #define ABSTRACT_TYPE(Class, Base)
  1695. #define NON_CANONICAL_TYPE(Class, Base)
  1696. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1697. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1698. case Type::Class: \
  1699. assert(!T->isDependentType() && "should not see dependent types here"); \
  1700. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1701. #include "clang/AST/TypeNodes.inc"
  1702. llvm_unreachable("Should not see dependent types");
  1703. case Type::FunctionNoProto:
  1704. case Type::FunctionProto:
  1705. // GCC extension: alignof(function) = 32 bits
  1706. Width = 0;
  1707. Align = 32;
  1708. break;
  1709. case Type::IncompleteArray:
  1710. case Type::VariableArray:
  1711. case Type::ConstantArray: {
  1712. // Model non-constant sized arrays as size zero, but track the alignment.
  1713. uint64_t Size = 0;
  1714. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1715. Size = CAT->getSize().getZExtValue();
  1716. TypeInfo EltInfo = getTypeInfo(cast<ArrayType>(T)->getElementType());
  1717. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1718. "Overflow in array type bit size evaluation");
  1719. Width = EltInfo.Width * Size;
  1720. Align = EltInfo.Align;
  1721. AlignRequirement = EltInfo.AlignRequirement;
  1722. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1723. getTargetInfo().getPointerWidth(0) == 64)
  1724. Width = llvm::alignTo(Width, Align);
  1725. break;
  1726. }
  1727. case Type::ExtVector:
  1728. case Type::Vector: {
  1729. const auto *VT = cast<VectorType>(T);
  1730. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1731. Width = EltInfo.Width * VT->getNumElements();
  1732. Align = Width;
  1733. // If the alignment is not a power of 2, round up to the next power of 2.
  1734. // This happens for non-power-of-2 length vectors.
  1735. if (Align & (Align-1)) {
  1736. Align = llvm::NextPowerOf2(Align);
  1737. Width = llvm::alignTo(Width, Align);
  1738. }
  1739. // Adjust the alignment based on the target max.
  1740. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1741. if (TargetVectorAlign && TargetVectorAlign < Align)
  1742. Align = TargetVectorAlign;
  1743. if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
  1744. // Adjust the alignment for fixed-length SVE vectors. This is important
  1745. // for non-power-of-2 vector lengths.
  1746. Align = 128;
  1747. else if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  1748. // Adjust the alignment for fixed-length SVE predicates.
  1749. Align = 16;
  1750. break;
  1751. }
  1752. case Type::ConstantMatrix: {
  1753. const auto *MT = cast<ConstantMatrixType>(T);
  1754. TypeInfo ElementInfo = getTypeInfo(MT->getElementType());
  1755. // The internal layout of a matrix value is implementation defined.
  1756. // Initially be ABI compatible with arrays with respect to alignment and
  1757. // size.
  1758. Width = ElementInfo.Width * MT->getNumRows() * MT->getNumColumns();
  1759. Align = ElementInfo.Align;
  1760. break;
  1761. }
  1762. case Type::Builtin:
  1763. switch (cast<BuiltinType>(T)->getKind()) {
  1764. default: llvm_unreachable("Unknown builtin type!");
  1765. case BuiltinType::Void:
  1766. // GCC extension: alignof(void) = 8 bits.
  1767. Width = 0;
  1768. Align = 8;
  1769. break;
  1770. case BuiltinType::Bool:
  1771. Width = Target->getBoolWidth();
  1772. Align = Target->getBoolAlign();
  1773. break;
  1774. case BuiltinType::Char_S:
  1775. case BuiltinType::Char_U:
  1776. case BuiltinType::UChar:
  1777. case BuiltinType::SChar:
  1778. case BuiltinType::Char8:
  1779. Width = Target->getCharWidth();
  1780. Align = Target->getCharAlign();
  1781. break;
  1782. case BuiltinType::WChar_S:
  1783. case BuiltinType::WChar_U:
  1784. Width = Target->getWCharWidth();
  1785. Align = Target->getWCharAlign();
  1786. break;
  1787. case BuiltinType::Char16:
  1788. Width = Target->getChar16Width();
  1789. Align = Target->getChar16Align();
  1790. break;
  1791. case BuiltinType::Char32:
  1792. Width = Target->getChar32Width();
  1793. Align = Target->getChar32Align();
  1794. break;
  1795. case BuiltinType::UShort:
  1796. case BuiltinType::Short:
  1797. Width = Target->getShortWidth();
  1798. Align = Target->getShortAlign();
  1799. break;
  1800. case BuiltinType::UInt:
  1801. case BuiltinType::Int:
  1802. Width = Target->getIntWidth();
  1803. Align = Target->getIntAlign();
  1804. break;
  1805. case BuiltinType::ULong:
  1806. case BuiltinType::Long:
  1807. Width = Target->getLongWidth();
  1808. Align = Target->getLongAlign();
  1809. break;
  1810. case BuiltinType::ULongLong:
  1811. case BuiltinType::LongLong:
  1812. Width = Target->getLongLongWidth();
  1813. Align = Target->getLongLongAlign();
  1814. break;
  1815. case BuiltinType::Int128:
  1816. case BuiltinType::UInt128:
  1817. Width = 128;
  1818. Align = 128; // int128_t is 128-bit aligned on all targets.
  1819. break;
  1820. case BuiltinType::ShortAccum:
  1821. case BuiltinType::UShortAccum:
  1822. case BuiltinType::SatShortAccum:
  1823. case BuiltinType::SatUShortAccum:
  1824. Width = Target->getShortAccumWidth();
  1825. Align = Target->getShortAccumAlign();
  1826. break;
  1827. case BuiltinType::Accum:
  1828. case BuiltinType::UAccum:
  1829. case BuiltinType::SatAccum:
  1830. case BuiltinType::SatUAccum:
  1831. Width = Target->getAccumWidth();
  1832. Align = Target->getAccumAlign();
  1833. break;
  1834. case BuiltinType::LongAccum:
  1835. case BuiltinType::ULongAccum:
  1836. case BuiltinType::SatLongAccum:
  1837. case BuiltinType::SatULongAccum:
  1838. Width = Target->getLongAccumWidth();
  1839. Align = Target->getLongAccumAlign();
  1840. break;
  1841. case BuiltinType::ShortFract:
  1842. case BuiltinType::UShortFract:
  1843. case BuiltinType::SatShortFract:
  1844. case BuiltinType::SatUShortFract:
  1845. Width = Target->getShortFractWidth();
  1846. Align = Target->getShortFractAlign();
  1847. break;
  1848. case BuiltinType::Fract:
  1849. case BuiltinType::UFract:
  1850. case BuiltinType::SatFract:
  1851. case BuiltinType::SatUFract:
  1852. Width = Target->getFractWidth();
  1853. Align = Target->getFractAlign();
  1854. break;
  1855. case BuiltinType::LongFract:
  1856. case BuiltinType::ULongFract:
  1857. case BuiltinType::SatLongFract:
  1858. case BuiltinType::SatULongFract:
  1859. Width = Target->getLongFractWidth();
  1860. Align = Target->getLongFractAlign();
  1861. break;
  1862. case BuiltinType::BFloat16:
  1863. Width = Target->getBFloat16Width();
  1864. Align = Target->getBFloat16Align();
  1865. break;
  1866. case BuiltinType::Float16:
  1867. case BuiltinType::Half:
  1868. if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
  1869. !getLangOpts().OpenMPIsDevice) {
  1870. Width = Target->getHalfWidth();
  1871. Align = Target->getHalfAlign();
  1872. } else {
  1873. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1874. "Expected OpenMP device compilation.");
  1875. Width = AuxTarget->getHalfWidth();
  1876. Align = AuxTarget->getHalfAlign();
  1877. }
  1878. break;
  1879. case BuiltinType::Float:
  1880. Width = Target->getFloatWidth();
  1881. Align = Target->getFloatAlign();
  1882. break;
  1883. case BuiltinType::Double:
  1884. Width = Target->getDoubleWidth();
  1885. Align = Target->getDoubleAlign();
  1886. break;
  1887. case BuiltinType::Ibm128:
  1888. Width = Target->getIbm128Width();
  1889. Align = Target->getIbm128Align();
  1890. break;
  1891. case BuiltinType::LongDouble:
  1892. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1893. (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
  1894. Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
  1895. Width = AuxTarget->getLongDoubleWidth();
  1896. Align = AuxTarget->getLongDoubleAlign();
  1897. } else {
  1898. Width = Target->getLongDoubleWidth();
  1899. Align = Target->getLongDoubleAlign();
  1900. }
  1901. break;
  1902. case BuiltinType::Float128:
  1903. if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
  1904. !getLangOpts().OpenMPIsDevice) {
  1905. Width = Target->getFloat128Width();
  1906. Align = Target->getFloat128Align();
  1907. } else {
  1908. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1909. "Expected OpenMP device compilation.");
  1910. Width = AuxTarget->getFloat128Width();
  1911. Align = AuxTarget->getFloat128Align();
  1912. }
  1913. break;
  1914. case BuiltinType::NullPtr:
  1915. Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
  1916. Align = Target->getPointerAlign(0); // == sizeof(void*)
  1917. break;
  1918. case BuiltinType::ObjCId:
  1919. case BuiltinType::ObjCClass:
  1920. case BuiltinType::ObjCSel:
  1921. Width = Target->getPointerWidth(0);
  1922. Align = Target->getPointerAlign(0);
  1923. break;
  1924. case BuiltinType::OCLSampler:
  1925. case BuiltinType::OCLEvent:
  1926. case BuiltinType::OCLClkEvent:
  1927. case BuiltinType::OCLQueue:
  1928. case BuiltinType::OCLReserveID:
  1929. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1930. case BuiltinType::Id:
  1931. #include "clang/Basic/OpenCLImageTypes.def"
  1932. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1933. case BuiltinType::Id:
  1934. #include "clang/Basic/OpenCLExtensionTypes.def"
  1935. AS = getTargetAddressSpace(
  1936. Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
  1937. Width = Target->getPointerWidth(AS);
  1938. Align = Target->getPointerAlign(AS);
  1939. break;
  1940. // The SVE types are effectively target-specific. The length of an
  1941. // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
  1942. // of 128 bits. There is one predicate bit for each vector byte, so the
  1943. // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
  1944. //
  1945. // Because the length is only known at runtime, we use a dummy value
  1946. // of 0 for the static length. The alignment values are those defined
  1947. // by the Procedure Call Standard for the Arm Architecture.
  1948. #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
  1949. IsSigned, IsFP, IsBF) \
  1950. case BuiltinType::Id: \
  1951. Width = 0; \
  1952. Align = 128; \
  1953. break;
  1954. #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
  1955. case BuiltinType::Id: \
  1956. Width = 0; \
  1957. Align = 16; \
  1958. break;
  1959. #include "clang/Basic/AArch64SVEACLETypes.def"
  1960. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  1961. case BuiltinType::Id: \
  1962. Width = Size; \
  1963. Align = Size; \
  1964. break;
  1965. #include "clang/Basic/PPCTypes.def"
  1966. #define RVV_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, NF, IsSigned, \
  1967. IsFP) \
  1968. case BuiltinType::Id: \
  1969. Width = 0; \
  1970. Align = ElBits; \
  1971. break;
  1972. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
  1973. case BuiltinType::Id: \
  1974. Width = 0; \
  1975. Align = 8; \
  1976. break;
  1977. #include "clang/Basic/RISCVVTypes.def"
  1978. }
  1979. break;
  1980. case Type::ObjCObjectPointer:
  1981. Width = Target->getPointerWidth(0);
  1982. Align = Target->getPointerAlign(0);
  1983. break;
  1984. case Type::BlockPointer:
  1985. AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
  1986. Width = Target->getPointerWidth(AS);
  1987. Align = Target->getPointerAlign(AS);
  1988. break;
  1989. case Type::LValueReference:
  1990. case Type::RValueReference:
  1991. // alignof and sizeof should never enter this code path here, so we go
  1992. // the pointer route.
  1993. AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
  1994. Width = Target->getPointerWidth(AS);
  1995. Align = Target->getPointerAlign(AS);
  1996. break;
  1997. case Type::Pointer:
  1998. AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
  1999. Width = Target->getPointerWidth(AS);
  2000. Align = Target->getPointerAlign(AS);
  2001. break;
  2002. case Type::MemberPointer: {
  2003. const auto *MPT = cast<MemberPointerType>(T);
  2004. CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
  2005. Width = MPI.Width;
  2006. Align = MPI.Align;
  2007. break;
  2008. }
  2009. case Type::Complex: {
  2010. // Complex types have the same alignment as their elements, but twice the
  2011. // size.
  2012. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  2013. Width = EltInfo.Width * 2;
  2014. Align = EltInfo.Align;
  2015. break;
  2016. }
  2017. case Type::ObjCObject:
  2018. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  2019. case Type::Adjusted:
  2020. case Type::Decayed:
  2021. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  2022. case Type::ObjCInterface: {
  2023. const auto *ObjCI = cast<ObjCInterfaceType>(T);
  2024. if (ObjCI->getDecl()->isInvalidDecl()) {
  2025. Width = 8;
  2026. Align = 8;
  2027. break;
  2028. }
  2029. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  2030. Width = toBits(Layout.getSize());
  2031. Align = toBits(Layout.getAlignment());
  2032. break;
  2033. }
  2034. case Type::BitInt: {
  2035. const auto *EIT = cast<BitIntType>(T);
  2036. Align =
  2037. std::min(static_cast<unsigned>(std::max(
  2038. getCharWidth(), llvm::PowerOf2Ceil(EIT->getNumBits()))),
  2039. Target->getLongLongAlign());
  2040. Width = llvm::alignTo(EIT->getNumBits(), Align);
  2041. break;
  2042. }
  2043. case Type::Record:
  2044. case Type::Enum: {
  2045. const auto *TT = cast<TagType>(T);
  2046. if (TT->getDecl()->isInvalidDecl()) {
  2047. Width = 8;
  2048. Align = 8;
  2049. break;
  2050. }
  2051. if (const auto *ET = dyn_cast<EnumType>(TT)) {
  2052. const EnumDecl *ED = ET->getDecl();
  2053. TypeInfo Info =
  2054. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  2055. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  2056. Info.Align = AttrAlign;
  2057. Info.AlignRequirement = AlignRequirementKind::RequiredByEnum;
  2058. }
  2059. return Info;
  2060. }
  2061. const auto *RT = cast<RecordType>(TT);
  2062. const RecordDecl *RD = RT->getDecl();
  2063. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  2064. Width = toBits(Layout.getSize());
  2065. Align = toBits(Layout.getAlignment());
  2066. AlignRequirement = RD->hasAttr<AlignedAttr>()
  2067. ? AlignRequirementKind::RequiredByRecord
  2068. : AlignRequirementKind::None;
  2069. break;
  2070. }
  2071. case Type::SubstTemplateTypeParm:
  2072. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  2073. getReplacementType().getTypePtr());
  2074. case Type::Auto:
  2075. case Type::DeducedTemplateSpecialization: {
  2076. const auto *A = cast<DeducedType>(T);
  2077. assert(!A->getDeducedType().isNull() &&
  2078. "cannot request the size of an undeduced or dependent auto type");
  2079. return getTypeInfo(A->getDeducedType().getTypePtr());
  2080. }
  2081. case Type::Paren:
  2082. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  2083. case Type::MacroQualified:
  2084. return getTypeInfo(
  2085. cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
  2086. case Type::ObjCTypeParam:
  2087. return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
  2088. case Type::Using:
  2089. return getTypeInfo(cast<UsingType>(T)->desugar().getTypePtr());
  2090. case Type::Typedef: {
  2091. const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
  2092. TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
  2093. // If the typedef has an aligned attribute on it, it overrides any computed
  2094. // alignment we have. This violates the GCC documentation (which says that
  2095. // attribute(aligned) can only round up) but matches its implementation.
  2096. if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
  2097. Align = AttrAlign;
  2098. AlignRequirement = AlignRequirementKind::RequiredByTypedef;
  2099. } else {
  2100. Align = Info.Align;
  2101. AlignRequirement = Info.AlignRequirement;
  2102. }
  2103. Width = Info.Width;
  2104. break;
  2105. }
  2106. case Type::Elaborated:
  2107. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  2108. case Type::Attributed:
  2109. return getTypeInfo(
  2110. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  2111. case Type::Atomic: {
  2112. // Start with the base type information.
  2113. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  2114. Width = Info.Width;
  2115. Align = Info.Align;
  2116. if (!Width) {
  2117. // An otherwise zero-sized type should still generate an
  2118. // atomic operation.
  2119. Width = Target->getCharWidth();
  2120. assert(Align);
  2121. } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
  2122. // If the size of the type doesn't exceed the platform's max
  2123. // atomic promotion width, make the size and alignment more
  2124. // favorable to atomic operations:
  2125. // Round the size up to a power of 2.
  2126. if (!llvm::isPowerOf2_64(Width))
  2127. Width = llvm::NextPowerOf2(Width);
  2128. // Set the alignment equal to the size.
  2129. Align = static_cast<unsigned>(Width);
  2130. }
  2131. }
  2132. break;
  2133. case Type::Pipe:
  2134. Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
  2135. Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
  2136. break;
  2137. }
  2138. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  2139. return TypeInfo(Width, Align, AlignRequirement);
  2140. }
  2141. unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
  2142. UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
  2143. if (I != MemoizedUnadjustedAlign.end())
  2144. return I->second;
  2145. unsigned UnadjustedAlign;
  2146. if (const auto *RT = T->getAs<RecordType>()) {
  2147. const RecordDecl *RD = RT->getDecl();
  2148. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  2149. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  2150. } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
  2151. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  2152. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  2153. } else {
  2154. UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
  2155. }
  2156. MemoizedUnadjustedAlign[T] = UnadjustedAlign;
  2157. return UnadjustedAlign;
  2158. }
  2159. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  2160. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  2161. return SimdAlign;
  2162. }
  2163. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  2164. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  2165. return CharUnits::fromQuantity(BitSize / getCharWidth());
  2166. }
  2167. /// toBits - Convert a size in characters to a size in characters.
  2168. int64_t ASTContext::toBits(CharUnits CharSize) const {
  2169. return CharSize.getQuantity() * getCharWidth();
  2170. }
  2171. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  2172. /// This method does not work on incomplete types.
  2173. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  2174. return getTypeInfoInChars(T).Width;
  2175. }
  2176. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  2177. return getTypeInfoInChars(T).Width;
  2178. }
  2179. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  2180. /// characters. This method does not work on incomplete types.
  2181. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  2182. return toCharUnitsFromBits(getTypeAlign(T));
  2183. }
  2184. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  2185. return toCharUnitsFromBits(getTypeAlign(T));
  2186. }
  2187. /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
  2188. /// type, in characters, before alignment adustments. This method does
  2189. /// not work on incomplete types.
  2190. CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
  2191. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2192. }
  2193. CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
  2194. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2195. }
  2196. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  2197. /// type for the current target in bits. This can be different than the ABI
  2198. /// alignment in cases where it is beneficial for performance or backwards
  2199. /// compatibility preserving to overalign a data type. (Note: despite the name,
  2200. /// the preferred alignment is ABI-impacting, and not an optimization.)
  2201. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  2202. TypeInfo TI = getTypeInfo(T);
  2203. unsigned ABIAlign = TI.Align;
  2204. T = T->getBaseElementTypeUnsafe();
  2205. // The preferred alignment of member pointers is that of a pointer.
  2206. if (T->isMemberPointerType())
  2207. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  2208. if (!Target->allowsLargerPreferedTypeAlignment())
  2209. return ABIAlign;
  2210. if (const auto *RT = T->getAs<RecordType>()) {
  2211. const RecordDecl *RD = RT->getDecl();
  2212. // When used as part of a typedef, or together with a 'packed' attribute,
  2213. // the 'aligned' attribute can be used to decrease alignment. Note that the
  2214. // 'packed' case is already taken into consideration when computing the
  2215. // alignment, we only need to handle the typedef case here.
  2216. if (TI.AlignRequirement == AlignRequirementKind::RequiredByTypedef ||
  2217. RD->isInvalidDecl())
  2218. return ABIAlign;
  2219. unsigned PreferredAlign = static_cast<unsigned>(
  2220. toBits(getASTRecordLayout(RD).PreferredAlignment));
  2221. assert(PreferredAlign >= ABIAlign &&
  2222. "PreferredAlign should be at least as large as ABIAlign.");
  2223. return PreferredAlign;
  2224. }
  2225. // Double (and, for targets supporting AIX `power` alignment, long double) and
  2226. // long long should be naturally aligned (despite requiring less alignment) if
  2227. // possible.
  2228. if (const auto *CT = T->getAs<ComplexType>())
  2229. T = CT->getElementType().getTypePtr();
  2230. if (const auto *ET = T->getAs<EnumType>())
  2231. T = ET->getDecl()->getIntegerType().getTypePtr();
  2232. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  2233. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  2234. T->isSpecificBuiltinType(BuiltinType::ULongLong) ||
  2235. (T->isSpecificBuiltinType(BuiltinType::LongDouble) &&
  2236. Target->defaultsToAIXPowerAlignment()))
  2237. // Don't increase the alignment if an alignment attribute was specified on a
  2238. // typedef declaration.
  2239. if (!TI.isAlignRequired())
  2240. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  2241. return ABIAlign;
  2242. }
  2243. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  2244. /// for __attribute__((aligned)) on this target, to be used if no alignment
  2245. /// value is specified.
  2246. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
  2247. return getTargetInfo().getDefaultAlignForAttributeAligned();
  2248. }
  2249. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  2250. /// to a global variable of the specified type.
  2251. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  2252. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  2253. return std::max(getPreferredTypeAlign(T),
  2254. getTargetInfo().getMinGlobalAlign(TypeSize));
  2255. }
  2256. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  2257. /// should be given to a global variable of the specified type.
  2258. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  2259. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  2260. }
  2261. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  2262. CharUnits Offset = CharUnits::Zero();
  2263. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  2264. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  2265. Offset += Layout->getBaseClassOffset(Base);
  2266. Layout = &getASTRecordLayout(Base);
  2267. }
  2268. return Offset;
  2269. }
  2270. CharUnits ASTContext::getMemberPointerPathAdjustment(const APValue &MP) const {
  2271. const ValueDecl *MPD = MP.getMemberPointerDecl();
  2272. CharUnits ThisAdjustment = CharUnits::Zero();
  2273. ArrayRef<const CXXRecordDecl*> Path = MP.getMemberPointerPath();
  2274. bool DerivedMember = MP.isMemberPointerToDerivedMember();
  2275. const CXXRecordDecl *RD = cast<CXXRecordDecl>(MPD->getDeclContext());
  2276. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  2277. const CXXRecordDecl *Base = RD;
  2278. const CXXRecordDecl *Derived = Path[I];
  2279. if (DerivedMember)
  2280. std::swap(Base, Derived);
  2281. ThisAdjustment += getASTRecordLayout(Derived).getBaseClassOffset(Base);
  2282. RD = Path[I];
  2283. }
  2284. if (DerivedMember)
  2285. ThisAdjustment = -ThisAdjustment;
  2286. return ThisAdjustment;
  2287. }
  2288. /// DeepCollectObjCIvars -
  2289. /// This routine first collects all declared, but not synthesized, ivars in
  2290. /// super class and then collects all ivars, including those synthesized for
  2291. /// current class. This routine is used for implementation of current class
  2292. /// when all ivars, declared and synthesized are known.
  2293. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  2294. bool leafClass,
  2295. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  2296. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  2297. DeepCollectObjCIvars(SuperClass, false, Ivars);
  2298. if (!leafClass) {
  2299. for (const auto *I : OI->ivars())
  2300. Ivars.push_back(I);
  2301. } else {
  2302. auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  2303. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  2304. Iv= Iv->getNextIvar())
  2305. Ivars.push_back(Iv);
  2306. }
  2307. }
  2308. /// CollectInheritedProtocols - Collect all protocols in current class and
  2309. /// those inherited by it.
  2310. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  2311. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  2312. if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2313. // We can use protocol_iterator here instead of
  2314. // all_referenced_protocol_iterator since we are walking all categories.
  2315. for (auto *Proto : OI->all_referenced_protocols()) {
  2316. CollectInheritedProtocols(Proto, Protocols);
  2317. }
  2318. // Categories of this Interface.
  2319. for (const auto *Cat : OI->visible_categories())
  2320. CollectInheritedProtocols(Cat, Protocols);
  2321. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  2322. while (SD) {
  2323. CollectInheritedProtocols(SD, Protocols);
  2324. SD = SD->getSuperClass();
  2325. }
  2326. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2327. for (auto *Proto : OC->protocols()) {
  2328. CollectInheritedProtocols(Proto, Protocols);
  2329. }
  2330. } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  2331. // Insert the protocol.
  2332. if (!Protocols.insert(
  2333. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  2334. return;
  2335. for (auto *Proto : OP->protocols())
  2336. CollectInheritedProtocols(Proto, Protocols);
  2337. }
  2338. }
  2339. static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
  2340. const RecordDecl *RD) {
  2341. assert(RD->isUnion() && "Must be union type");
  2342. CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
  2343. for (const auto *Field : RD->fields()) {
  2344. if (!Context.hasUniqueObjectRepresentations(Field->getType()))
  2345. return false;
  2346. CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
  2347. if (FieldSize != UnionSize)
  2348. return false;
  2349. }
  2350. return !RD->field_empty();
  2351. }
  2352. static int64_t getSubobjectOffset(const FieldDecl *Field,
  2353. const ASTContext &Context,
  2354. const clang::ASTRecordLayout & /*Layout*/) {
  2355. return Context.getFieldOffset(Field);
  2356. }
  2357. static int64_t getSubobjectOffset(const CXXRecordDecl *RD,
  2358. const ASTContext &Context,
  2359. const clang::ASTRecordLayout &Layout) {
  2360. return Context.toBits(Layout.getBaseClassOffset(RD));
  2361. }
  2362. static llvm::Optional<int64_t>
  2363. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2364. const RecordDecl *RD);
  2365. static llvm::Optional<int64_t>
  2366. getSubobjectSizeInBits(const FieldDecl *Field, const ASTContext &Context) {
  2367. if (Field->getType()->isRecordType()) {
  2368. const RecordDecl *RD = Field->getType()->getAsRecordDecl();
  2369. if (!RD->isUnion())
  2370. return structHasUniqueObjectRepresentations(Context, RD);
  2371. }
  2372. if (!Field->getType()->isReferenceType() &&
  2373. !Context.hasUniqueObjectRepresentations(Field->getType()))
  2374. return llvm::None;
  2375. int64_t FieldSizeInBits =
  2376. Context.toBits(Context.getTypeSizeInChars(Field->getType()));
  2377. if (Field->isBitField()) {
  2378. int64_t BitfieldSize = Field->getBitWidthValue(Context);
  2379. if (BitfieldSize > FieldSizeInBits)
  2380. return llvm::None;
  2381. FieldSizeInBits = BitfieldSize;
  2382. }
  2383. return FieldSizeInBits;
  2384. }
  2385. static llvm::Optional<int64_t>
  2386. getSubobjectSizeInBits(const CXXRecordDecl *RD, const ASTContext &Context) {
  2387. return structHasUniqueObjectRepresentations(Context, RD);
  2388. }
  2389. template <typename RangeT>
  2390. static llvm::Optional<int64_t> structSubobjectsHaveUniqueObjectRepresentations(
  2391. const RangeT &Subobjects, int64_t CurOffsetInBits,
  2392. const ASTContext &Context, const clang::ASTRecordLayout &Layout) {
  2393. for (const auto *Subobject : Subobjects) {
  2394. llvm::Optional<int64_t> SizeInBits =
  2395. getSubobjectSizeInBits(Subobject, Context);
  2396. if (!SizeInBits)
  2397. return llvm::None;
  2398. if (*SizeInBits != 0) {
  2399. int64_t Offset = getSubobjectOffset(Subobject, Context, Layout);
  2400. if (Offset != CurOffsetInBits)
  2401. return llvm::None;
  2402. CurOffsetInBits += *SizeInBits;
  2403. }
  2404. }
  2405. return CurOffsetInBits;
  2406. }
  2407. static llvm::Optional<int64_t>
  2408. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2409. const RecordDecl *RD) {
  2410. assert(!RD->isUnion() && "Must be struct/class type");
  2411. const auto &Layout = Context.getASTRecordLayout(RD);
  2412. int64_t CurOffsetInBits = 0;
  2413. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
  2414. if (ClassDecl->isDynamicClass())
  2415. return llvm::None;
  2416. SmallVector<CXXRecordDecl *, 4> Bases;
  2417. for (const auto &Base : ClassDecl->bases()) {
  2418. // Empty types can be inherited from, and non-empty types can potentially
  2419. // have tail padding, so just make sure there isn't an error.
  2420. Bases.emplace_back(Base.getType()->getAsCXXRecordDecl());
  2421. }
  2422. llvm::sort(Bases, [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
  2423. return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
  2424. });
  2425. llvm::Optional<int64_t> OffsetAfterBases =
  2426. structSubobjectsHaveUniqueObjectRepresentations(Bases, CurOffsetInBits,
  2427. Context, Layout);
  2428. if (!OffsetAfterBases)
  2429. return llvm::None;
  2430. CurOffsetInBits = *OffsetAfterBases;
  2431. }
  2432. llvm::Optional<int64_t> OffsetAfterFields =
  2433. structSubobjectsHaveUniqueObjectRepresentations(
  2434. RD->fields(), CurOffsetInBits, Context, Layout);
  2435. if (!OffsetAfterFields)
  2436. return llvm::None;
  2437. CurOffsetInBits = *OffsetAfterFields;
  2438. return CurOffsetInBits;
  2439. }
  2440. bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
  2441. // C++17 [meta.unary.prop]:
  2442. // The predicate condition for a template specialization
  2443. // has_unique_object_representations<T> shall be
  2444. // satisfied if and only if:
  2445. // (9.1) - T is trivially copyable, and
  2446. // (9.2) - any two objects of type T with the same value have the same
  2447. // object representation, where two objects
  2448. // of array or non-union class type are considered to have the same value
  2449. // if their respective sequences of
  2450. // direct subobjects have the same values, and two objects of union type
  2451. // are considered to have the same
  2452. // value if they have the same active member and the corresponding members
  2453. // have the same value.
  2454. // The set of scalar types for which this condition holds is
  2455. // implementation-defined. [ Note: If a type has padding
  2456. // bits, the condition does not hold; otherwise, the condition holds true
  2457. // for unsigned integral types. -- end note ]
  2458. assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
  2459. // Arrays are unique only if their element type is unique.
  2460. if (Ty->isArrayType())
  2461. return hasUniqueObjectRepresentations(getBaseElementType(Ty));
  2462. // (9.1) - T is trivially copyable...
  2463. if (!Ty.isTriviallyCopyableType(*this))
  2464. return false;
  2465. // All integrals and enums are unique.
  2466. if (Ty->isIntegralOrEnumerationType())
  2467. return true;
  2468. // All other pointers are unique.
  2469. if (Ty->isPointerType())
  2470. return true;
  2471. if (Ty->isMemberPointerType()) {
  2472. const auto *MPT = Ty->getAs<MemberPointerType>();
  2473. return !ABI->getMemberPointerInfo(MPT).HasPadding;
  2474. }
  2475. if (Ty->isRecordType()) {
  2476. const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
  2477. if (Record->isInvalidDecl())
  2478. return false;
  2479. if (Record->isUnion())
  2480. return unionHasUniqueObjectRepresentations(*this, Record);
  2481. Optional<int64_t> StructSize =
  2482. structHasUniqueObjectRepresentations(*this, Record);
  2483. return StructSize &&
  2484. StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
  2485. }
  2486. // FIXME: More cases to handle here (list by rsmith):
  2487. // vectors (careful about, eg, vector of 3 foo)
  2488. // _Complex int and friends
  2489. // _Atomic T
  2490. // Obj-C block pointers
  2491. // Obj-C object pointers
  2492. // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
  2493. // clk_event_t, queue_t, reserve_id_t)
  2494. // There're also Obj-C class types and the Obj-C selector type, but I think it
  2495. // makes sense for those to return false here.
  2496. return false;
  2497. }
  2498. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  2499. unsigned count = 0;
  2500. // Count ivars declared in class extension.
  2501. for (const auto *Ext : OI->known_extensions())
  2502. count += Ext->ivar_size();
  2503. // Count ivar defined in this class's implementation. This
  2504. // includes synthesized ivars.
  2505. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  2506. count += ImplDecl->ivar_size();
  2507. return count;
  2508. }
  2509. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  2510. if (!E)
  2511. return false;
  2512. // nullptr_t is always treated as null.
  2513. if (E->getType()->isNullPtrType()) return true;
  2514. if (E->getType()->isAnyPointerType() &&
  2515. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  2516. Expr::NPC_ValueDependentIsNull))
  2517. return true;
  2518. // Unfortunately, __null has type 'int'.
  2519. if (isa<GNUNullExpr>(E)) return true;
  2520. return false;
  2521. }
  2522. /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
  2523. /// exists.
  2524. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  2525. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2526. I = ObjCImpls.find(D);
  2527. if (I != ObjCImpls.end())
  2528. return cast<ObjCImplementationDecl>(I->second);
  2529. return nullptr;
  2530. }
  2531. /// Get the implementation of ObjCCategoryDecl, or nullptr if none
  2532. /// exists.
  2533. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  2534. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2535. I = ObjCImpls.find(D);
  2536. if (I != ObjCImpls.end())
  2537. return cast<ObjCCategoryImplDecl>(I->second);
  2538. return nullptr;
  2539. }
  2540. /// Set the implementation of ObjCInterfaceDecl.
  2541. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  2542. ObjCImplementationDecl *ImplD) {
  2543. assert(IFaceD && ImplD && "Passed null params");
  2544. ObjCImpls[IFaceD] = ImplD;
  2545. }
  2546. /// Set the implementation of ObjCCategoryDecl.
  2547. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  2548. ObjCCategoryImplDecl *ImplD) {
  2549. assert(CatD && ImplD && "Passed null params");
  2550. ObjCImpls[CatD] = ImplD;
  2551. }
  2552. const ObjCMethodDecl *
  2553. ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
  2554. return ObjCMethodRedecls.lookup(MD);
  2555. }
  2556. void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
  2557. const ObjCMethodDecl *Redecl) {
  2558. assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
  2559. ObjCMethodRedecls[MD] = Redecl;
  2560. }
  2561. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  2562. const NamedDecl *ND) const {
  2563. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  2564. return ID;
  2565. if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  2566. return CD->getClassInterface();
  2567. if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  2568. return IMD->getClassInterface();
  2569. return nullptr;
  2570. }
  2571. /// Get the copy initialization expression of VarDecl, or nullptr if
  2572. /// none exists.
  2573. BlockVarCopyInit ASTContext::getBlockVarCopyInit(const VarDecl *VD) const {
  2574. assert(VD && "Passed null params");
  2575. assert(VD->hasAttr<BlocksAttr>() &&
  2576. "getBlockVarCopyInits - not __block var");
  2577. auto I = BlockVarCopyInits.find(VD);
  2578. if (I != BlockVarCopyInits.end())
  2579. return I->second;
  2580. return {nullptr, false};
  2581. }
  2582. /// Set the copy initialization expression of a block var decl.
  2583. void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
  2584. bool CanThrow) {
  2585. assert(VD && CopyExpr && "Passed null params");
  2586. assert(VD->hasAttr<BlocksAttr>() &&
  2587. "setBlockVarCopyInits - not __block var");
  2588. BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
  2589. }
  2590. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  2591. unsigned DataSize) const {
  2592. if (!DataSize)
  2593. DataSize = TypeLoc::getFullDataSizeForType(T);
  2594. else
  2595. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  2596. "incorrect data size provided to CreateTypeSourceInfo!");
  2597. auto *TInfo =
  2598. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  2599. new (TInfo) TypeSourceInfo(T);
  2600. return TInfo;
  2601. }
  2602. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  2603. SourceLocation L) const {
  2604. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  2605. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  2606. return DI;
  2607. }
  2608. const ASTRecordLayout &
  2609. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  2610. return getObjCLayout(D, nullptr);
  2611. }
  2612. const ASTRecordLayout &
  2613. ASTContext::getASTObjCImplementationLayout(
  2614. const ObjCImplementationDecl *D) const {
  2615. return getObjCLayout(D->getClassInterface(), D);
  2616. }
  2617. //===----------------------------------------------------------------------===//
  2618. // Type creation/memoization methods
  2619. //===----------------------------------------------------------------------===//
  2620. QualType
  2621. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  2622. unsigned fastQuals = quals.getFastQualifiers();
  2623. quals.removeFastQualifiers();
  2624. // Check if we've already instantiated this type.
  2625. llvm::FoldingSetNodeID ID;
  2626. ExtQuals::Profile(ID, baseType, quals);
  2627. void *insertPos = nullptr;
  2628. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  2629. assert(eq->getQualifiers() == quals);
  2630. return QualType(eq, fastQuals);
  2631. }
  2632. // If the base type is not canonical, make the appropriate canonical type.
  2633. QualType canon;
  2634. if (!baseType->isCanonicalUnqualified()) {
  2635. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  2636. canonSplit.Quals.addConsistentQualifiers(quals);
  2637. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  2638. // Re-find the insert position.
  2639. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  2640. }
  2641. auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  2642. ExtQualNodes.InsertNode(eq, insertPos);
  2643. return QualType(eq, fastQuals);
  2644. }
  2645. QualType ASTContext::getAddrSpaceQualType(QualType T,
  2646. LangAS AddressSpace) const {
  2647. QualType CanT = getCanonicalType(T);
  2648. if (CanT.getAddressSpace() == AddressSpace)
  2649. return T;
  2650. // If we are composing extended qualifiers together, merge together
  2651. // into one ExtQuals node.
  2652. QualifierCollector Quals;
  2653. const Type *TypeNode = Quals.strip(T);
  2654. // If this type already has an address space specified, it cannot get
  2655. // another one.
  2656. assert(!Quals.hasAddressSpace() &&
  2657. "Type cannot be in multiple addr spaces!");
  2658. Quals.addAddressSpace(AddressSpace);
  2659. return getExtQualType(TypeNode, Quals);
  2660. }
  2661. QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
  2662. // If the type is not qualified with an address space, just return it
  2663. // immediately.
  2664. if (!T.hasAddressSpace())
  2665. return T;
  2666. // If we are composing extended qualifiers together, merge together
  2667. // into one ExtQuals node.
  2668. QualifierCollector Quals;
  2669. const Type *TypeNode;
  2670. while (T.hasAddressSpace()) {
  2671. TypeNode = Quals.strip(T);
  2672. // If the type no longer has an address space after stripping qualifiers,
  2673. // jump out.
  2674. if (!QualType(TypeNode, 0).hasAddressSpace())
  2675. break;
  2676. // There might be sugar in the way. Strip it and try again.
  2677. T = T.getSingleStepDesugaredType(*this);
  2678. }
  2679. Quals.removeAddressSpace();
  2680. // Removal of the address space can mean there are no longer any
  2681. // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
  2682. // or required.
  2683. if (Quals.hasNonFastQualifiers())
  2684. return getExtQualType(TypeNode, Quals);
  2685. else
  2686. return QualType(TypeNode, Quals.getFastQualifiers());
  2687. }
  2688. QualType ASTContext::getObjCGCQualType(QualType T,
  2689. Qualifiers::GC GCAttr) const {
  2690. QualType CanT = getCanonicalType(T);
  2691. if (CanT.getObjCGCAttr() == GCAttr)
  2692. return T;
  2693. if (const auto *ptr = T->getAs<PointerType>()) {
  2694. QualType Pointee = ptr->getPointeeType();
  2695. if (Pointee->isAnyPointerType()) {
  2696. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  2697. return getPointerType(ResultType);
  2698. }
  2699. }
  2700. // If we are composing extended qualifiers together, merge together
  2701. // into one ExtQuals node.
  2702. QualifierCollector Quals;
  2703. const Type *TypeNode = Quals.strip(T);
  2704. // If this type already has an ObjCGC specified, it cannot get
  2705. // another one.
  2706. assert(!Quals.hasObjCGCAttr() &&
  2707. "Type cannot have multiple ObjCGCs!");
  2708. Quals.addObjCGCAttr(GCAttr);
  2709. return getExtQualType(TypeNode, Quals);
  2710. }
  2711. QualType ASTContext::removePtrSizeAddrSpace(QualType T) const {
  2712. if (const PointerType *Ptr = T->getAs<PointerType>()) {
  2713. QualType Pointee = Ptr->getPointeeType();
  2714. if (isPtrSizeAddressSpace(Pointee.getAddressSpace())) {
  2715. return getPointerType(removeAddrSpaceQualType(Pointee));
  2716. }
  2717. }
  2718. return T;
  2719. }
  2720. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  2721. FunctionType::ExtInfo Info) {
  2722. if (T->getExtInfo() == Info)
  2723. return T;
  2724. QualType Result;
  2725. if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  2726. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  2727. } else {
  2728. const auto *FPT = cast<FunctionProtoType>(T);
  2729. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2730. EPI.ExtInfo = Info;
  2731. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
  2732. }
  2733. return cast<FunctionType>(Result.getTypePtr());
  2734. }
  2735. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  2736. QualType ResultType) {
  2737. FD = FD->getMostRecentDecl();
  2738. while (true) {
  2739. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  2740. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2741. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
  2742. if (FunctionDecl *Next = FD->getPreviousDecl())
  2743. FD = Next;
  2744. else
  2745. break;
  2746. }
  2747. if (ASTMutationListener *L = getASTMutationListener())
  2748. L->DeducedReturnType(FD, ResultType);
  2749. }
  2750. /// Get a function type and produce the equivalent function type with the
  2751. /// specified exception specification. Type sugar that can be present on a
  2752. /// declaration of a function with an exception specification is permitted
  2753. /// and preserved. Other type sugar (for instance, typedefs) is not.
  2754. QualType ASTContext::getFunctionTypeWithExceptionSpec(
  2755. QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
  2756. // Might have some parens.
  2757. if (const auto *PT = dyn_cast<ParenType>(Orig))
  2758. return getParenType(
  2759. getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
  2760. // Might be wrapped in a macro qualified type.
  2761. if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
  2762. return getMacroQualifiedType(
  2763. getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
  2764. MQT->getMacroIdentifier());
  2765. // Might have a calling-convention attribute.
  2766. if (const auto *AT = dyn_cast<AttributedType>(Orig))
  2767. return getAttributedType(
  2768. AT->getAttrKind(),
  2769. getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
  2770. getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
  2771. // Anything else must be a function type. Rebuild it with the new exception
  2772. // specification.
  2773. const auto *Proto = Orig->castAs<FunctionProtoType>();
  2774. return getFunctionType(
  2775. Proto->getReturnType(), Proto->getParamTypes(),
  2776. Proto->getExtProtoInfo().withExceptionSpec(ESI));
  2777. }
  2778. bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
  2779. QualType U) {
  2780. return hasSameType(T, U) ||
  2781. (getLangOpts().CPlusPlus17 &&
  2782. hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
  2783. getFunctionTypeWithExceptionSpec(U, EST_None)));
  2784. }
  2785. QualType ASTContext::getFunctionTypeWithoutPtrSizes(QualType T) {
  2786. if (const auto *Proto = T->getAs<FunctionProtoType>()) {
  2787. QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
  2788. SmallVector<QualType, 16> Args(Proto->param_types());
  2789. for (unsigned i = 0, n = Args.size(); i != n; ++i)
  2790. Args[i] = removePtrSizeAddrSpace(Args[i]);
  2791. return getFunctionType(RetTy, Args, Proto->getExtProtoInfo());
  2792. }
  2793. if (const FunctionNoProtoType *Proto = T->getAs<FunctionNoProtoType>()) {
  2794. QualType RetTy = removePtrSizeAddrSpace(Proto->getReturnType());
  2795. return getFunctionNoProtoType(RetTy, Proto->getExtInfo());
  2796. }
  2797. return T;
  2798. }
  2799. bool ASTContext::hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U) {
  2800. return hasSameType(T, U) ||
  2801. hasSameType(getFunctionTypeWithoutPtrSizes(T),
  2802. getFunctionTypeWithoutPtrSizes(U));
  2803. }
  2804. void ASTContext::adjustExceptionSpec(
  2805. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  2806. bool AsWritten) {
  2807. // Update the type.
  2808. QualType Updated =
  2809. getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
  2810. FD->setType(Updated);
  2811. if (!AsWritten)
  2812. return;
  2813. // Update the type in the type source information too.
  2814. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2815. // If the type and the type-as-written differ, we may need to update
  2816. // the type-as-written too.
  2817. if (TSInfo->getType() != FD->getType())
  2818. Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
  2819. // FIXME: When we get proper type location information for exceptions,
  2820. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2821. // up the TypeSourceInfo;
  2822. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2823. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2824. "TypeLoc size mismatch from updating exception specification");
  2825. TSInfo->overrideType(Updated);
  2826. }
  2827. }
  2828. /// getComplexType - Return the uniqued reference to the type for a complex
  2829. /// number with the specified element type.
  2830. QualType ASTContext::getComplexType(QualType T) const {
  2831. // Unique pointers, to guarantee there is only one pointer of a particular
  2832. // structure.
  2833. llvm::FoldingSetNodeID ID;
  2834. ComplexType::Profile(ID, T);
  2835. void *InsertPos = nullptr;
  2836. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2837. return QualType(CT, 0);
  2838. // If the pointee type isn't canonical, this won't be a canonical type either,
  2839. // so fill in the canonical type field.
  2840. QualType Canonical;
  2841. if (!T.isCanonical()) {
  2842. Canonical = getComplexType(getCanonicalType(T));
  2843. // Get the new insert position for the node we care about.
  2844. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2845. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2846. }
  2847. auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2848. Types.push_back(New);
  2849. ComplexTypes.InsertNode(New, InsertPos);
  2850. return QualType(New, 0);
  2851. }
  2852. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2853. /// the specified type.
  2854. QualType ASTContext::getPointerType(QualType T) const {
  2855. // Unique pointers, to guarantee there is only one pointer of a particular
  2856. // structure.
  2857. llvm::FoldingSetNodeID ID;
  2858. PointerType::Profile(ID, T);
  2859. void *InsertPos = nullptr;
  2860. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2861. return QualType(PT, 0);
  2862. // If the pointee type isn't canonical, this won't be a canonical type either,
  2863. // so fill in the canonical type field.
  2864. QualType Canonical;
  2865. if (!T.isCanonical()) {
  2866. Canonical = getPointerType(getCanonicalType(T));
  2867. // Get the new insert position for the node we care about.
  2868. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2869. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2870. }
  2871. auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2872. Types.push_back(New);
  2873. PointerTypes.InsertNode(New, InsertPos);
  2874. return QualType(New, 0);
  2875. }
  2876. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2877. llvm::FoldingSetNodeID ID;
  2878. AdjustedType::Profile(ID, Orig, New);
  2879. void *InsertPos = nullptr;
  2880. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2881. if (AT)
  2882. return QualType(AT, 0);
  2883. QualType Canonical = getCanonicalType(New);
  2884. // Get the new insert position for the node we care about.
  2885. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2886. assert(!AT && "Shouldn't be in the map!");
  2887. AT = new (*this, TypeAlignment)
  2888. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2889. Types.push_back(AT);
  2890. AdjustedTypes.InsertNode(AT, InsertPos);
  2891. return QualType(AT, 0);
  2892. }
  2893. QualType ASTContext::getDecayedType(QualType T) const {
  2894. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2895. QualType Decayed;
  2896. // C99 6.7.5.3p7:
  2897. // A declaration of a parameter as "array of type" shall be
  2898. // adjusted to "qualified pointer to type", where the type
  2899. // qualifiers (if any) are those specified within the [ and ] of
  2900. // the array type derivation.
  2901. if (T->isArrayType())
  2902. Decayed = getArrayDecayedType(T);
  2903. // C99 6.7.5.3p8:
  2904. // A declaration of a parameter as "function returning type"
  2905. // shall be adjusted to "pointer to function returning type", as
  2906. // in 6.3.2.1.
  2907. if (T->isFunctionType())
  2908. Decayed = getPointerType(T);
  2909. llvm::FoldingSetNodeID ID;
  2910. AdjustedType::Profile(ID, T, Decayed);
  2911. void *InsertPos = nullptr;
  2912. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2913. if (AT)
  2914. return QualType(AT, 0);
  2915. QualType Canonical = getCanonicalType(Decayed);
  2916. // Get the new insert position for the node we care about.
  2917. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2918. assert(!AT && "Shouldn't be in the map!");
  2919. AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
  2920. Types.push_back(AT);
  2921. AdjustedTypes.InsertNode(AT, InsertPos);
  2922. return QualType(AT, 0);
  2923. }
  2924. /// getBlockPointerType - Return the uniqued reference to the type for
  2925. /// a pointer to the specified block.
  2926. QualType ASTContext::getBlockPointerType(QualType T) const {
  2927. assert(T->isFunctionType() && "block of function types only");
  2928. // Unique pointers, to guarantee there is only one block of a particular
  2929. // structure.
  2930. llvm::FoldingSetNodeID ID;
  2931. BlockPointerType::Profile(ID, T);
  2932. void *InsertPos = nullptr;
  2933. if (BlockPointerType *PT =
  2934. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2935. return QualType(PT, 0);
  2936. // If the block pointee type isn't canonical, this won't be a canonical
  2937. // type either so fill in the canonical type field.
  2938. QualType Canonical;
  2939. if (!T.isCanonical()) {
  2940. Canonical = getBlockPointerType(getCanonicalType(T));
  2941. // Get the new insert position for the node we care about.
  2942. BlockPointerType *NewIP =
  2943. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2944. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2945. }
  2946. auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2947. Types.push_back(New);
  2948. BlockPointerTypes.InsertNode(New, InsertPos);
  2949. return QualType(New, 0);
  2950. }
  2951. /// getLValueReferenceType - Return the uniqued reference to the type for an
  2952. /// lvalue reference to the specified type.
  2953. QualType
  2954. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  2955. assert((!T->isPlaceholderType() ||
  2956. T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
  2957. "Unresolved placeholder type");
  2958. // Unique pointers, to guarantee there is only one pointer of a particular
  2959. // structure.
  2960. llvm::FoldingSetNodeID ID;
  2961. ReferenceType::Profile(ID, T, SpelledAsLValue);
  2962. void *InsertPos = nullptr;
  2963. if (LValueReferenceType *RT =
  2964. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2965. return QualType(RT, 0);
  2966. const auto *InnerRef = T->getAs<ReferenceType>();
  2967. // If the referencee type isn't canonical, this won't be a canonical type
  2968. // either, so fill in the canonical type field.
  2969. QualType Canonical;
  2970. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  2971. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2972. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  2973. // Get the new insert position for the node we care about.
  2974. LValueReferenceType *NewIP =
  2975. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2976. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2977. }
  2978. auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  2979. SpelledAsLValue);
  2980. Types.push_back(New);
  2981. LValueReferenceTypes.InsertNode(New, InsertPos);
  2982. return QualType(New, 0);
  2983. }
  2984. /// getRValueReferenceType - Return the uniqued reference to the type for an
  2985. /// rvalue reference to the specified type.
  2986. QualType ASTContext::getRValueReferenceType(QualType T) const {
  2987. assert((!T->isPlaceholderType() ||
  2988. T->isSpecificPlaceholderType(BuiltinType::UnknownAny)) &&
  2989. "Unresolved placeholder type");
  2990. // Unique pointers, to guarantee there is only one pointer of a particular
  2991. // structure.
  2992. llvm::FoldingSetNodeID ID;
  2993. ReferenceType::Profile(ID, T, false);
  2994. void *InsertPos = nullptr;
  2995. if (RValueReferenceType *RT =
  2996. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2997. return QualType(RT, 0);
  2998. const auto *InnerRef = T->getAs<ReferenceType>();
  2999. // If the referencee type isn't canonical, this won't be a canonical type
  3000. // either, so fill in the canonical type field.
  3001. QualType Canonical;
  3002. if (InnerRef || !T.isCanonical()) {
  3003. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  3004. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  3005. // Get the new insert position for the node we care about.
  3006. RValueReferenceType *NewIP =
  3007. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  3008. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3009. }
  3010. auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  3011. Types.push_back(New);
  3012. RValueReferenceTypes.InsertNode(New, InsertPos);
  3013. return QualType(New, 0);
  3014. }
  3015. /// getMemberPointerType - Return the uniqued reference to the type for a
  3016. /// member pointer to the specified type, in the specified class.
  3017. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  3018. // Unique pointers, to guarantee there is only one pointer of a particular
  3019. // structure.
  3020. llvm::FoldingSetNodeID ID;
  3021. MemberPointerType::Profile(ID, T, Cls);
  3022. void *InsertPos = nullptr;
  3023. if (MemberPointerType *PT =
  3024. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  3025. return QualType(PT, 0);
  3026. // If the pointee or class type isn't canonical, this won't be a canonical
  3027. // type either, so fill in the canonical type field.
  3028. QualType Canonical;
  3029. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  3030. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  3031. // Get the new insert position for the node we care about.
  3032. MemberPointerType *NewIP =
  3033. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  3034. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3035. }
  3036. auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  3037. Types.push_back(New);
  3038. MemberPointerTypes.InsertNode(New, InsertPos);
  3039. return QualType(New, 0);
  3040. }
  3041. /// getConstantArrayType - Return the unique reference to the type for an
  3042. /// array of the specified element type.
  3043. QualType ASTContext::getConstantArrayType(QualType EltTy,
  3044. const llvm::APInt &ArySizeIn,
  3045. const Expr *SizeExpr,
  3046. ArrayType::ArraySizeModifier ASM,
  3047. unsigned IndexTypeQuals) const {
  3048. assert((EltTy->isDependentType() ||
  3049. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  3050. "Constant array of VLAs is illegal!");
  3051. // We only need the size as part of the type if it's instantiation-dependent.
  3052. if (SizeExpr && !SizeExpr->isInstantiationDependent())
  3053. SizeExpr = nullptr;
  3054. // Convert the array size into a canonical width matching the pointer size for
  3055. // the target.
  3056. llvm::APInt ArySize(ArySizeIn);
  3057. ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
  3058. llvm::FoldingSetNodeID ID;
  3059. ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
  3060. IndexTypeQuals);
  3061. void *InsertPos = nullptr;
  3062. if (ConstantArrayType *ATP =
  3063. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  3064. return QualType(ATP, 0);
  3065. // If the element type isn't canonical or has qualifiers, or the array bound
  3066. // is instantiation-dependent, this won't be a canonical type either, so fill
  3067. // in the canonical type field.
  3068. QualType Canon;
  3069. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
  3070. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  3071. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
  3072. ASM, IndexTypeQuals);
  3073. Canon = getQualifiedType(Canon, canonSplit.Quals);
  3074. // Get the new insert position for the node we care about.
  3075. ConstantArrayType *NewIP =
  3076. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  3077. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3078. }
  3079. void *Mem = Allocate(
  3080. ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
  3081. TypeAlignment);
  3082. auto *New = new (Mem)
  3083. ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
  3084. ConstantArrayTypes.InsertNode(New, InsertPos);
  3085. Types.push_back(New);
  3086. return QualType(New, 0);
  3087. }
  3088. /// getVariableArrayDecayedType - Turns the given type, which may be
  3089. /// variably-modified, into the corresponding type with all the known
  3090. /// sizes replaced with [*].
  3091. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  3092. // Vastly most common case.
  3093. if (!type->isVariablyModifiedType()) return type;
  3094. QualType result;
  3095. SplitQualType split = type.getSplitDesugaredType();
  3096. const Type *ty = split.Ty;
  3097. switch (ty->getTypeClass()) {
  3098. #define TYPE(Class, Base)
  3099. #define ABSTRACT_TYPE(Class, Base)
  3100. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  3101. #include "clang/AST/TypeNodes.inc"
  3102. llvm_unreachable("didn't desugar past all non-canonical types?");
  3103. // These types should never be variably-modified.
  3104. case Type::Builtin:
  3105. case Type::Complex:
  3106. case Type::Vector:
  3107. case Type::DependentVector:
  3108. case Type::ExtVector:
  3109. case Type::DependentSizedExtVector:
  3110. case Type::ConstantMatrix:
  3111. case Type::DependentSizedMatrix:
  3112. case Type::DependentAddressSpace:
  3113. case Type::ObjCObject:
  3114. case Type::ObjCInterface:
  3115. case Type::ObjCObjectPointer:
  3116. case Type::Record:
  3117. case Type::Enum:
  3118. case Type::UnresolvedUsing:
  3119. case Type::TypeOfExpr:
  3120. case Type::TypeOf:
  3121. case Type::Decltype:
  3122. case Type::UnaryTransform:
  3123. case Type::DependentName:
  3124. case Type::InjectedClassName:
  3125. case Type::TemplateSpecialization:
  3126. case Type::DependentTemplateSpecialization:
  3127. case Type::TemplateTypeParm:
  3128. case Type::SubstTemplateTypeParmPack:
  3129. case Type::Auto:
  3130. case Type::DeducedTemplateSpecialization:
  3131. case Type::PackExpansion:
  3132. case Type::BitInt:
  3133. case Type::DependentBitInt:
  3134. llvm_unreachable("type should never be variably-modified");
  3135. // These types can be variably-modified but should never need to
  3136. // further decay.
  3137. case Type::FunctionNoProto:
  3138. case Type::FunctionProto:
  3139. case Type::BlockPointer:
  3140. case Type::MemberPointer:
  3141. case Type::Pipe:
  3142. return type;
  3143. // These types can be variably-modified. All these modifications
  3144. // preserve structure except as noted by comments.
  3145. // TODO: if we ever care about optimizing VLAs, there are no-op
  3146. // optimizations available here.
  3147. case Type::Pointer:
  3148. result = getPointerType(getVariableArrayDecayedType(
  3149. cast<PointerType>(ty)->getPointeeType()));
  3150. break;
  3151. case Type::LValueReference: {
  3152. const auto *lv = cast<LValueReferenceType>(ty);
  3153. result = getLValueReferenceType(
  3154. getVariableArrayDecayedType(lv->getPointeeType()),
  3155. lv->isSpelledAsLValue());
  3156. break;
  3157. }
  3158. case Type::RValueReference: {
  3159. const auto *lv = cast<RValueReferenceType>(ty);
  3160. result = getRValueReferenceType(
  3161. getVariableArrayDecayedType(lv->getPointeeType()));
  3162. break;
  3163. }
  3164. case Type::Atomic: {
  3165. const auto *at = cast<AtomicType>(ty);
  3166. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  3167. break;
  3168. }
  3169. case Type::ConstantArray: {
  3170. const auto *cat = cast<ConstantArrayType>(ty);
  3171. result = getConstantArrayType(
  3172. getVariableArrayDecayedType(cat->getElementType()),
  3173. cat->getSize(),
  3174. cat->getSizeExpr(),
  3175. cat->getSizeModifier(),
  3176. cat->getIndexTypeCVRQualifiers());
  3177. break;
  3178. }
  3179. case Type::DependentSizedArray: {
  3180. const auto *dat = cast<DependentSizedArrayType>(ty);
  3181. result = getDependentSizedArrayType(
  3182. getVariableArrayDecayedType(dat->getElementType()),
  3183. dat->getSizeExpr(),
  3184. dat->getSizeModifier(),
  3185. dat->getIndexTypeCVRQualifiers(),
  3186. dat->getBracketsRange());
  3187. break;
  3188. }
  3189. // Turn incomplete types into [*] types.
  3190. case Type::IncompleteArray: {
  3191. const auto *iat = cast<IncompleteArrayType>(ty);
  3192. result = getVariableArrayType(
  3193. getVariableArrayDecayedType(iat->getElementType()),
  3194. /*size*/ nullptr,
  3195. ArrayType::Normal,
  3196. iat->getIndexTypeCVRQualifiers(),
  3197. SourceRange());
  3198. break;
  3199. }
  3200. // Turn VLA types into [*] types.
  3201. case Type::VariableArray: {
  3202. const auto *vat = cast<VariableArrayType>(ty);
  3203. result = getVariableArrayType(
  3204. getVariableArrayDecayedType(vat->getElementType()),
  3205. /*size*/ nullptr,
  3206. ArrayType::Star,
  3207. vat->getIndexTypeCVRQualifiers(),
  3208. vat->getBracketsRange());
  3209. break;
  3210. }
  3211. }
  3212. // Apply the top-level qualifiers from the original.
  3213. return getQualifiedType(result, split.Quals);
  3214. }
  3215. /// getVariableArrayType - Returns a non-unique reference to the type for a
  3216. /// variable array of the specified element type.
  3217. QualType ASTContext::getVariableArrayType(QualType EltTy,
  3218. Expr *NumElts,
  3219. ArrayType::ArraySizeModifier ASM,
  3220. unsigned IndexTypeQuals,
  3221. SourceRange Brackets) const {
  3222. // Since we don't unique expressions, it isn't possible to unique VLA's
  3223. // that have an expression provided for their size.
  3224. QualType Canon;
  3225. // Be sure to pull qualifiers off the element type.
  3226. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  3227. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  3228. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  3229. IndexTypeQuals, Brackets);
  3230. Canon = getQualifiedType(Canon, canonSplit.Quals);
  3231. }
  3232. auto *New = new (*this, TypeAlignment)
  3233. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  3234. VariableArrayTypes.push_back(New);
  3235. Types.push_back(New);
  3236. return QualType(New, 0);
  3237. }
  3238. /// getDependentSizedArrayType - Returns a non-unique reference to
  3239. /// the type for a dependently-sized array of the specified element
  3240. /// type.
  3241. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  3242. Expr *numElements,
  3243. ArrayType::ArraySizeModifier ASM,
  3244. unsigned elementTypeQuals,
  3245. SourceRange brackets) const {
  3246. assert((!numElements || numElements->isTypeDependent() ||
  3247. numElements->isValueDependent()) &&
  3248. "Size must be type- or value-dependent!");
  3249. // Dependently-sized array types that do not have a specified number
  3250. // of elements will have their sizes deduced from a dependent
  3251. // initializer. We do no canonicalization here at all, which is okay
  3252. // because they can't be used in most locations.
  3253. if (!numElements) {
  3254. auto *newType
  3255. = new (*this, TypeAlignment)
  3256. DependentSizedArrayType(*this, elementType, QualType(),
  3257. numElements, ASM, elementTypeQuals,
  3258. brackets);
  3259. Types.push_back(newType);
  3260. return QualType(newType, 0);
  3261. }
  3262. // Otherwise, we actually build a new type every time, but we
  3263. // also build a canonical type.
  3264. SplitQualType canonElementType = getCanonicalType(elementType).split();
  3265. void *insertPos = nullptr;
  3266. llvm::FoldingSetNodeID ID;
  3267. DependentSizedArrayType::Profile(ID, *this,
  3268. QualType(canonElementType.Ty, 0),
  3269. ASM, elementTypeQuals, numElements);
  3270. // Look for an existing type with these properties.
  3271. DependentSizedArrayType *canonTy =
  3272. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  3273. // If we don't have one, build one.
  3274. if (!canonTy) {
  3275. canonTy = new (*this, TypeAlignment)
  3276. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  3277. QualType(), numElements, ASM, elementTypeQuals,
  3278. brackets);
  3279. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  3280. Types.push_back(canonTy);
  3281. }
  3282. // Apply qualifiers from the element type to the array.
  3283. QualType canon = getQualifiedType(QualType(canonTy,0),
  3284. canonElementType.Quals);
  3285. // If we didn't need extra canonicalization for the element type or the size
  3286. // expression, then just use that as our result.
  3287. if (QualType(canonElementType.Ty, 0) == elementType &&
  3288. canonTy->getSizeExpr() == numElements)
  3289. return canon;
  3290. // Otherwise, we need to build a type which follows the spelling
  3291. // of the element type.
  3292. auto *sugaredType
  3293. = new (*this, TypeAlignment)
  3294. DependentSizedArrayType(*this, elementType, canon, numElements,
  3295. ASM, elementTypeQuals, brackets);
  3296. Types.push_back(sugaredType);
  3297. return QualType(sugaredType, 0);
  3298. }
  3299. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  3300. ArrayType::ArraySizeModifier ASM,
  3301. unsigned elementTypeQuals) const {
  3302. llvm::FoldingSetNodeID ID;
  3303. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  3304. void *insertPos = nullptr;
  3305. if (IncompleteArrayType *iat =
  3306. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  3307. return QualType(iat, 0);
  3308. // If the element type isn't canonical, this won't be a canonical type
  3309. // either, so fill in the canonical type field. We also have to pull
  3310. // qualifiers off the element type.
  3311. QualType canon;
  3312. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  3313. SplitQualType canonSplit = getCanonicalType(elementType).split();
  3314. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  3315. ASM, elementTypeQuals);
  3316. canon = getQualifiedType(canon, canonSplit.Quals);
  3317. // Get the new insert position for the node we care about.
  3318. IncompleteArrayType *existing =
  3319. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  3320. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  3321. }
  3322. auto *newType = new (*this, TypeAlignment)
  3323. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  3324. IncompleteArrayTypes.InsertNode(newType, insertPos);
  3325. Types.push_back(newType);
  3326. return QualType(newType, 0);
  3327. }
  3328. ASTContext::BuiltinVectorTypeInfo
  3329. ASTContext::getBuiltinVectorTypeInfo(const BuiltinType *Ty) const {
  3330. #define SVE_INT_ELTTY(BITS, ELTS, SIGNED, NUMVECTORS) \
  3331. {getIntTypeForBitwidth(BITS, SIGNED), llvm::ElementCount::getScalable(ELTS), \
  3332. NUMVECTORS};
  3333. #define SVE_ELTTY(ELTTY, ELTS, NUMVECTORS) \
  3334. {ELTTY, llvm::ElementCount::getScalable(ELTS), NUMVECTORS};
  3335. switch (Ty->getKind()) {
  3336. default:
  3337. llvm_unreachable("Unsupported builtin vector type");
  3338. case BuiltinType::SveInt8:
  3339. return SVE_INT_ELTTY(8, 16, true, 1);
  3340. case BuiltinType::SveUint8:
  3341. return SVE_INT_ELTTY(8, 16, false, 1);
  3342. case BuiltinType::SveInt8x2:
  3343. return SVE_INT_ELTTY(8, 16, true, 2);
  3344. case BuiltinType::SveUint8x2:
  3345. return SVE_INT_ELTTY(8, 16, false, 2);
  3346. case BuiltinType::SveInt8x3:
  3347. return SVE_INT_ELTTY(8, 16, true, 3);
  3348. case BuiltinType::SveUint8x3:
  3349. return SVE_INT_ELTTY(8, 16, false, 3);
  3350. case BuiltinType::SveInt8x4:
  3351. return SVE_INT_ELTTY(8, 16, true, 4);
  3352. case BuiltinType::SveUint8x4:
  3353. return SVE_INT_ELTTY(8, 16, false, 4);
  3354. case BuiltinType::SveInt16:
  3355. return SVE_INT_ELTTY(16, 8, true, 1);
  3356. case BuiltinType::SveUint16:
  3357. return SVE_INT_ELTTY(16, 8, false, 1);
  3358. case BuiltinType::SveInt16x2:
  3359. return SVE_INT_ELTTY(16, 8, true, 2);
  3360. case BuiltinType::SveUint16x2:
  3361. return SVE_INT_ELTTY(16, 8, false, 2);
  3362. case BuiltinType::SveInt16x3:
  3363. return SVE_INT_ELTTY(16, 8, true, 3);
  3364. case BuiltinType::SveUint16x3:
  3365. return SVE_INT_ELTTY(16, 8, false, 3);
  3366. case BuiltinType::SveInt16x4:
  3367. return SVE_INT_ELTTY(16, 8, true, 4);
  3368. case BuiltinType::SveUint16x4:
  3369. return SVE_INT_ELTTY(16, 8, false, 4);
  3370. case BuiltinType::SveInt32:
  3371. return SVE_INT_ELTTY(32, 4, true, 1);
  3372. case BuiltinType::SveUint32:
  3373. return SVE_INT_ELTTY(32, 4, false, 1);
  3374. case BuiltinType::SveInt32x2:
  3375. return SVE_INT_ELTTY(32, 4, true, 2);
  3376. case BuiltinType::SveUint32x2:
  3377. return SVE_INT_ELTTY(32, 4, false, 2);
  3378. case BuiltinType::SveInt32x3:
  3379. return SVE_INT_ELTTY(32, 4, true, 3);
  3380. case BuiltinType::SveUint32x3:
  3381. return SVE_INT_ELTTY(32, 4, false, 3);
  3382. case BuiltinType::SveInt32x4:
  3383. return SVE_INT_ELTTY(32, 4, true, 4);
  3384. case BuiltinType::SveUint32x4:
  3385. return SVE_INT_ELTTY(32, 4, false, 4);
  3386. case BuiltinType::SveInt64:
  3387. return SVE_INT_ELTTY(64, 2, true, 1);
  3388. case BuiltinType::SveUint64:
  3389. return SVE_INT_ELTTY(64, 2, false, 1);
  3390. case BuiltinType::SveInt64x2:
  3391. return SVE_INT_ELTTY(64, 2, true, 2);
  3392. case BuiltinType::SveUint64x2:
  3393. return SVE_INT_ELTTY(64, 2, false, 2);
  3394. case BuiltinType::SveInt64x3:
  3395. return SVE_INT_ELTTY(64, 2, true, 3);
  3396. case BuiltinType::SveUint64x3:
  3397. return SVE_INT_ELTTY(64, 2, false, 3);
  3398. case BuiltinType::SveInt64x4:
  3399. return SVE_INT_ELTTY(64, 2, true, 4);
  3400. case BuiltinType::SveUint64x4:
  3401. return SVE_INT_ELTTY(64, 2, false, 4);
  3402. case BuiltinType::SveBool:
  3403. return SVE_ELTTY(BoolTy, 16, 1);
  3404. case BuiltinType::SveFloat16:
  3405. return SVE_ELTTY(HalfTy, 8, 1);
  3406. case BuiltinType::SveFloat16x2:
  3407. return SVE_ELTTY(HalfTy, 8, 2);
  3408. case BuiltinType::SveFloat16x3:
  3409. return SVE_ELTTY(HalfTy, 8, 3);
  3410. case BuiltinType::SveFloat16x4:
  3411. return SVE_ELTTY(HalfTy, 8, 4);
  3412. case BuiltinType::SveFloat32:
  3413. return SVE_ELTTY(FloatTy, 4, 1);
  3414. case BuiltinType::SveFloat32x2:
  3415. return SVE_ELTTY(FloatTy, 4, 2);
  3416. case BuiltinType::SveFloat32x3:
  3417. return SVE_ELTTY(FloatTy, 4, 3);
  3418. case BuiltinType::SveFloat32x4:
  3419. return SVE_ELTTY(FloatTy, 4, 4);
  3420. case BuiltinType::SveFloat64:
  3421. return SVE_ELTTY(DoubleTy, 2, 1);
  3422. case BuiltinType::SveFloat64x2:
  3423. return SVE_ELTTY(DoubleTy, 2, 2);
  3424. case BuiltinType::SveFloat64x3:
  3425. return SVE_ELTTY(DoubleTy, 2, 3);
  3426. case BuiltinType::SveFloat64x4:
  3427. return SVE_ELTTY(DoubleTy, 2, 4);
  3428. case BuiltinType::SveBFloat16:
  3429. return SVE_ELTTY(BFloat16Ty, 8, 1);
  3430. case BuiltinType::SveBFloat16x2:
  3431. return SVE_ELTTY(BFloat16Ty, 8, 2);
  3432. case BuiltinType::SveBFloat16x3:
  3433. return SVE_ELTTY(BFloat16Ty, 8, 3);
  3434. case BuiltinType::SveBFloat16x4:
  3435. return SVE_ELTTY(BFloat16Ty, 8, 4);
  3436. #define RVV_VECTOR_TYPE_INT(Name, Id, SingletonId, NumEls, ElBits, NF, \
  3437. IsSigned) \
  3438. case BuiltinType::Id: \
  3439. return {getIntTypeForBitwidth(ElBits, IsSigned), \
  3440. llvm::ElementCount::getScalable(NumEls), NF};
  3441. #define RVV_VECTOR_TYPE_FLOAT(Name, Id, SingletonId, NumEls, ElBits, NF) \
  3442. case BuiltinType::Id: \
  3443. return {ElBits == 16 ? Float16Ty : (ElBits == 32 ? FloatTy : DoubleTy), \
  3444. llvm::ElementCount::getScalable(NumEls), NF};
  3445. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
  3446. case BuiltinType::Id: \
  3447. return {BoolTy, llvm::ElementCount::getScalable(NumEls), 1};
  3448. #include "clang/Basic/RISCVVTypes.def"
  3449. }
  3450. }
  3451. /// getScalableVectorType - Return the unique reference to a scalable vector
  3452. /// type of the specified element type and size. VectorType must be a built-in
  3453. /// type.
  3454. QualType ASTContext::getScalableVectorType(QualType EltTy,
  3455. unsigned NumElts) const {
  3456. if (Target->hasAArch64SVETypes()) {
  3457. uint64_t EltTySize = getTypeSize(EltTy);
  3458. #define SVE_VECTOR_TYPE(Name, MangledName, Id, SingletonId, NumEls, ElBits, \
  3459. IsSigned, IsFP, IsBF) \
  3460. if (!EltTy->isBooleanType() && \
  3461. ((EltTy->hasIntegerRepresentation() && \
  3462. EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
  3463. (EltTy->hasFloatingRepresentation() && !EltTy->isBFloat16Type() && \
  3464. IsFP && !IsBF) || \
  3465. (EltTy->hasFloatingRepresentation() && EltTy->isBFloat16Type() && \
  3466. IsBF && !IsFP)) && \
  3467. EltTySize == ElBits && NumElts == NumEls) { \
  3468. return SingletonId; \
  3469. }
  3470. #define SVE_PREDICATE_TYPE(Name, MangledName, Id, SingletonId, NumEls) \
  3471. if (EltTy->isBooleanType() && NumElts == NumEls) \
  3472. return SingletonId;
  3473. #include "clang/Basic/AArch64SVEACLETypes.def"
  3474. } else if (Target->hasRISCVVTypes()) {
  3475. uint64_t EltTySize = getTypeSize(EltTy);
  3476. #define RVV_VECTOR_TYPE(Name, Id, SingletonId, NumEls, ElBits, NF, IsSigned, \
  3477. IsFP) \
  3478. if (!EltTy->isBooleanType() && \
  3479. ((EltTy->hasIntegerRepresentation() && \
  3480. EltTy->hasSignedIntegerRepresentation() == IsSigned) || \
  3481. (EltTy->hasFloatingRepresentation() && IsFP)) && \
  3482. EltTySize == ElBits && NumElts == NumEls) \
  3483. return SingletonId;
  3484. #define RVV_PREDICATE_TYPE(Name, Id, SingletonId, NumEls) \
  3485. if (EltTy->isBooleanType() && NumElts == NumEls) \
  3486. return SingletonId;
  3487. #include "clang/Basic/RISCVVTypes.def"
  3488. }
  3489. return QualType();
  3490. }
  3491. /// getVectorType - Return the unique reference to a vector type of
  3492. /// the specified element type and size. VectorType must be a built-in type.
  3493. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  3494. VectorType::VectorKind VecKind) const {
  3495. assert(vecType->isBuiltinType());
  3496. // Check if we've already instantiated a vector of this type.
  3497. llvm::FoldingSetNodeID ID;
  3498. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  3499. void *InsertPos = nullptr;
  3500. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3501. return QualType(VTP, 0);
  3502. // If the element type isn't canonical, this won't be a canonical type either,
  3503. // so fill in the canonical type field.
  3504. QualType Canonical;
  3505. if (!vecType.isCanonical()) {
  3506. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  3507. // Get the new insert position for the node we care about.
  3508. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3509. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3510. }
  3511. auto *New = new (*this, TypeAlignment)
  3512. VectorType(vecType, NumElts, Canonical, VecKind);
  3513. VectorTypes.InsertNode(New, InsertPos);
  3514. Types.push_back(New);
  3515. return QualType(New, 0);
  3516. }
  3517. QualType
  3518. ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
  3519. SourceLocation AttrLoc,
  3520. VectorType::VectorKind VecKind) const {
  3521. llvm::FoldingSetNodeID ID;
  3522. DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
  3523. VecKind);
  3524. void *InsertPos = nullptr;
  3525. DependentVectorType *Canon =
  3526. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3527. DependentVectorType *New;
  3528. if (Canon) {
  3529. New = new (*this, TypeAlignment) DependentVectorType(
  3530. *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
  3531. } else {
  3532. QualType CanonVecTy = getCanonicalType(VecType);
  3533. if (CanonVecTy == VecType) {
  3534. New = new (*this, TypeAlignment) DependentVectorType(
  3535. *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
  3536. DependentVectorType *CanonCheck =
  3537. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3538. assert(!CanonCheck &&
  3539. "Dependent-sized vector_size canonical type broken");
  3540. (void)CanonCheck;
  3541. DependentVectorTypes.InsertNode(New, InsertPos);
  3542. } else {
  3543. QualType CanonTy = getDependentVectorType(CanonVecTy, SizeExpr,
  3544. SourceLocation(), VecKind);
  3545. New = new (*this, TypeAlignment) DependentVectorType(
  3546. *this, VecType, CanonTy, SizeExpr, AttrLoc, VecKind);
  3547. }
  3548. }
  3549. Types.push_back(New);
  3550. return QualType(New, 0);
  3551. }
  3552. /// getExtVectorType - Return the unique reference to an extended vector type of
  3553. /// the specified element type and size. VectorType must be a built-in type.
  3554. QualType
  3555. ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
  3556. assert(vecType->isBuiltinType() || vecType->isDependentType());
  3557. // Check if we've already instantiated a vector of this type.
  3558. llvm::FoldingSetNodeID ID;
  3559. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  3560. VectorType::GenericVector);
  3561. void *InsertPos = nullptr;
  3562. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3563. return QualType(VTP, 0);
  3564. // If the element type isn't canonical, this won't be a canonical type either,
  3565. // so fill in the canonical type field.
  3566. QualType Canonical;
  3567. if (!vecType.isCanonical()) {
  3568. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  3569. // Get the new insert position for the node we care about.
  3570. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3571. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3572. }
  3573. auto *New = new (*this, TypeAlignment)
  3574. ExtVectorType(vecType, NumElts, Canonical);
  3575. VectorTypes.InsertNode(New, InsertPos);
  3576. Types.push_back(New);
  3577. return QualType(New, 0);
  3578. }
  3579. QualType
  3580. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  3581. Expr *SizeExpr,
  3582. SourceLocation AttrLoc) const {
  3583. llvm::FoldingSetNodeID ID;
  3584. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  3585. SizeExpr);
  3586. void *InsertPos = nullptr;
  3587. DependentSizedExtVectorType *Canon
  3588. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3589. DependentSizedExtVectorType *New;
  3590. if (Canon) {
  3591. // We already have a canonical version of this array type; use it as
  3592. // the canonical type for a newly-built type.
  3593. New = new (*this, TypeAlignment)
  3594. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  3595. SizeExpr, AttrLoc);
  3596. } else {
  3597. QualType CanonVecTy = getCanonicalType(vecType);
  3598. if (CanonVecTy == vecType) {
  3599. New = new (*this, TypeAlignment)
  3600. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  3601. AttrLoc);
  3602. DependentSizedExtVectorType *CanonCheck
  3603. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3604. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  3605. (void)CanonCheck;
  3606. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  3607. } else {
  3608. QualType CanonExtTy = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  3609. SourceLocation());
  3610. New = new (*this, TypeAlignment) DependentSizedExtVectorType(
  3611. *this, vecType, CanonExtTy, SizeExpr, AttrLoc);
  3612. }
  3613. }
  3614. Types.push_back(New);
  3615. return QualType(New, 0);
  3616. }
  3617. QualType ASTContext::getConstantMatrixType(QualType ElementTy, unsigned NumRows,
  3618. unsigned NumColumns) const {
  3619. llvm::FoldingSetNodeID ID;
  3620. ConstantMatrixType::Profile(ID, ElementTy, NumRows, NumColumns,
  3621. Type::ConstantMatrix);
  3622. assert(MatrixType::isValidElementType(ElementTy) &&
  3623. "need a valid element type");
  3624. assert(ConstantMatrixType::isDimensionValid(NumRows) &&
  3625. ConstantMatrixType::isDimensionValid(NumColumns) &&
  3626. "need valid matrix dimensions");
  3627. void *InsertPos = nullptr;
  3628. if (ConstantMatrixType *MTP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos))
  3629. return QualType(MTP, 0);
  3630. QualType Canonical;
  3631. if (!ElementTy.isCanonical()) {
  3632. Canonical =
  3633. getConstantMatrixType(getCanonicalType(ElementTy), NumRows, NumColumns);
  3634. ConstantMatrixType *NewIP = MatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3635. assert(!NewIP && "Matrix type shouldn't already exist in the map");
  3636. (void)NewIP;
  3637. }
  3638. auto *New = new (*this, TypeAlignment)
  3639. ConstantMatrixType(ElementTy, NumRows, NumColumns, Canonical);
  3640. MatrixTypes.InsertNode(New, InsertPos);
  3641. Types.push_back(New);
  3642. return QualType(New, 0);
  3643. }
  3644. QualType ASTContext::getDependentSizedMatrixType(QualType ElementTy,
  3645. Expr *RowExpr,
  3646. Expr *ColumnExpr,
  3647. SourceLocation AttrLoc) const {
  3648. QualType CanonElementTy = getCanonicalType(ElementTy);
  3649. llvm::FoldingSetNodeID ID;
  3650. DependentSizedMatrixType::Profile(ID, *this, CanonElementTy, RowExpr,
  3651. ColumnExpr);
  3652. void *InsertPos = nullptr;
  3653. DependentSizedMatrixType *Canon =
  3654. DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3655. if (!Canon) {
  3656. Canon = new (*this, TypeAlignment) DependentSizedMatrixType(
  3657. *this, CanonElementTy, QualType(), RowExpr, ColumnExpr, AttrLoc);
  3658. #ifndef NDEBUG
  3659. DependentSizedMatrixType *CanonCheck =
  3660. DependentSizedMatrixTypes.FindNodeOrInsertPos(ID, InsertPos);
  3661. assert(!CanonCheck && "Dependent-sized matrix canonical type broken");
  3662. #endif
  3663. DependentSizedMatrixTypes.InsertNode(Canon, InsertPos);
  3664. Types.push_back(Canon);
  3665. }
  3666. // Already have a canonical version of the matrix type
  3667. //
  3668. // If it exactly matches the requested type, use it directly.
  3669. if (Canon->getElementType() == ElementTy && Canon->getRowExpr() == RowExpr &&
  3670. Canon->getRowExpr() == ColumnExpr)
  3671. return QualType(Canon, 0);
  3672. // Use Canon as the canonical type for newly-built type.
  3673. DependentSizedMatrixType *New = new (*this, TypeAlignment)
  3674. DependentSizedMatrixType(*this, ElementTy, QualType(Canon, 0), RowExpr,
  3675. ColumnExpr, AttrLoc);
  3676. Types.push_back(New);
  3677. return QualType(New, 0);
  3678. }
  3679. QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
  3680. Expr *AddrSpaceExpr,
  3681. SourceLocation AttrLoc) const {
  3682. assert(AddrSpaceExpr->isInstantiationDependent());
  3683. QualType canonPointeeType = getCanonicalType(PointeeType);
  3684. void *insertPos = nullptr;
  3685. llvm::FoldingSetNodeID ID;
  3686. DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
  3687. AddrSpaceExpr);
  3688. DependentAddressSpaceType *canonTy =
  3689. DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
  3690. if (!canonTy) {
  3691. canonTy = new (*this, TypeAlignment)
  3692. DependentAddressSpaceType(*this, canonPointeeType,
  3693. QualType(), AddrSpaceExpr, AttrLoc);
  3694. DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
  3695. Types.push_back(canonTy);
  3696. }
  3697. if (canonPointeeType == PointeeType &&
  3698. canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
  3699. return QualType(canonTy, 0);
  3700. auto *sugaredType
  3701. = new (*this, TypeAlignment)
  3702. DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
  3703. AddrSpaceExpr, AttrLoc);
  3704. Types.push_back(sugaredType);
  3705. return QualType(sugaredType, 0);
  3706. }
  3707. /// Determine whether \p T is canonical as the result type of a function.
  3708. static bool isCanonicalResultType(QualType T) {
  3709. return T.isCanonical() &&
  3710. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  3711. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  3712. }
  3713. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  3714. QualType
  3715. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  3716. const FunctionType::ExtInfo &Info) const {
  3717. // Unique functions, to guarantee there is only one function of a particular
  3718. // structure.
  3719. llvm::FoldingSetNodeID ID;
  3720. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  3721. void *InsertPos = nullptr;
  3722. if (FunctionNoProtoType *FT =
  3723. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3724. return QualType(FT, 0);
  3725. QualType Canonical;
  3726. if (!isCanonicalResultType(ResultTy)) {
  3727. Canonical =
  3728. getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
  3729. // Get the new insert position for the node we care about.
  3730. FunctionNoProtoType *NewIP =
  3731. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3732. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3733. }
  3734. auto *New = new (*this, TypeAlignment)
  3735. FunctionNoProtoType(ResultTy, Canonical, Info);
  3736. Types.push_back(New);
  3737. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  3738. return QualType(New, 0);
  3739. }
  3740. CanQualType
  3741. ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
  3742. CanQualType CanResultType = getCanonicalType(ResultType);
  3743. // Canonical result types do not have ARC lifetime qualifiers.
  3744. if (CanResultType.getQualifiers().hasObjCLifetime()) {
  3745. Qualifiers Qs = CanResultType.getQualifiers();
  3746. Qs.removeObjCLifetime();
  3747. return CanQualType::CreateUnsafe(
  3748. getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
  3749. }
  3750. return CanResultType;
  3751. }
  3752. static bool isCanonicalExceptionSpecification(
  3753. const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
  3754. if (ESI.Type == EST_None)
  3755. return true;
  3756. if (!NoexceptInType)
  3757. return false;
  3758. // C++17 onwards: exception specification is part of the type, as a simple
  3759. // boolean "can this function type throw".
  3760. if (ESI.Type == EST_BasicNoexcept)
  3761. return true;
  3762. // A noexcept(expr) specification is (possibly) canonical if expr is
  3763. // value-dependent.
  3764. if (ESI.Type == EST_DependentNoexcept)
  3765. return true;
  3766. // A dynamic exception specification is canonical if it only contains pack
  3767. // expansions (so we can't tell whether it's non-throwing) and all its
  3768. // contained types are canonical.
  3769. if (ESI.Type == EST_Dynamic) {
  3770. bool AnyPackExpansions = false;
  3771. for (QualType ET : ESI.Exceptions) {
  3772. if (!ET.isCanonical())
  3773. return false;
  3774. if (ET->getAs<PackExpansionType>())
  3775. AnyPackExpansions = true;
  3776. }
  3777. return AnyPackExpansions;
  3778. }
  3779. return false;
  3780. }
  3781. QualType ASTContext::getFunctionTypeInternal(
  3782. QualType ResultTy, ArrayRef<QualType> ArgArray,
  3783. const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
  3784. size_t NumArgs = ArgArray.size();
  3785. // Unique functions, to guarantee there is only one function of a particular
  3786. // structure.
  3787. llvm::FoldingSetNodeID ID;
  3788. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
  3789. *this, true);
  3790. QualType Canonical;
  3791. bool Unique = false;
  3792. void *InsertPos = nullptr;
  3793. if (FunctionProtoType *FPT =
  3794. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
  3795. QualType Existing = QualType(FPT, 0);
  3796. // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
  3797. // it so long as our exception specification doesn't contain a dependent
  3798. // noexcept expression, or we're just looking for a canonical type.
  3799. // Otherwise, we're going to need to create a type
  3800. // sugar node to hold the concrete expression.
  3801. if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
  3802. EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
  3803. return Existing;
  3804. // We need a new type sugar node for this one, to hold the new noexcept
  3805. // expression. We do no canonicalization here, but that's OK since we don't
  3806. // expect to see the same noexcept expression much more than once.
  3807. Canonical = getCanonicalType(Existing);
  3808. Unique = true;
  3809. }
  3810. bool NoexceptInType = getLangOpts().CPlusPlus17;
  3811. bool IsCanonicalExceptionSpec =
  3812. isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
  3813. // Determine whether the type being created is already canonical or not.
  3814. bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
  3815. isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
  3816. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  3817. if (!ArgArray[i].isCanonicalAsParam())
  3818. isCanonical = false;
  3819. if (OnlyWantCanonical)
  3820. assert(isCanonical &&
  3821. "given non-canonical parameters constructing canonical type");
  3822. // If this type isn't canonical, get the canonical version of it if we don't
  3823. // already have it. The exception spec is only partially part of the
  3824. // canonical type, and only in C++17 onwards.
  3825. if (!isCanonical && Canonical.isNull()) {
  3826. SmallVector<QualType, 16> CanonicalArgs;
  3827. CanonicalArgs.reserve(NumArgs);
  3828. for (unsigned i = 0; i != NumArgs; ++i)
  3829. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  3830. llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
  3831. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  3832. CanonicalEPI.HasTrailingReturn = false;
  3833. if (IsCanonicalExceptionSpec) {
  3834. // Exception spec is already OK.
  3835. } else if (NoexceptInType) {
  3836. switch (EPI.ExceptionSpec.Type) {
  3837. case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
  3838. // We don't know yet. It shouldn't matter what we pick here; no-one
  3839. // should ever look at this.
  3840. LLVM_FALLTHROUGH;
  3841. case EST_None: case EST_MSAny: case EST_NoexceptFalse:
  3842. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3843. break;
  3844. // A dynamic exception specification is almost always "not noexcept",
  3845. // with the exception that a pack expansion might expand to no types.
  3846. case EST_Dynamic: {
  3847. bool AnyPacks = false;
  3848. for (QualType ET : EPI.ExceptionSpec.Exceptions) {
  3849. if (ET->getAs<PackExpansionType>())
  3850. AnyPacks = true;
  3851. ExceptionTypeStorage.push_back(getCanonicalType(ET));
  3852. }
  3853. if (!AnyPacks)
  3854. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3855. else {
  3856. CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
  3857. CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
  3858. }
  3859. break;
  3860. }
  3861. case EST_DynamicNone:
  3862. case EST_BasicNoexcept:
  3863. case EST_NoexceptTrue:
  3864. case EST_NoThrow:
  3865. CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
  3866. break;
  3867. case EST_DependentNoexcept:
  3868. llvm_unreachable("dependent noexcept is already canonical");
  3869. }
  3870. } else {
  3871. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  3872. }
  3873. // Adjust the canonical function result type.
  3874. CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
  3875. Canonical =
  3876. getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
  3877. // Get the new insert position for the node we care about.
  3878. FunctionProtoType *NewIP =
  3879. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3880. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3881. }
  3882. // Compute the needed size to hold this FunctionProtoType and the
  3883. // various trailing objects.
  3884. auto ESH = FunctionProtoType::getExceptionSpecSize(
  3885. EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
  3886. size_t Size = FunctionProtoType::totalSizeToAlloc<
  3887. QualType, SourceLocation, FunctionType::FunctionTypeExtraBitfields,
  3888. FunctionType::ExceptionType, Expr *, FunctionDecl *,
  3889. FunctionProtoType::ExtParameterInfo, Qualifiers>(
  3890. NumArgs, EPI.Variadic,
  3891. FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
  3892. ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
  3893. EPI.ExtParameterInfos ? NumArgs : 0,
  3894. EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
  3895. auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
  3896. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  3897. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
  3898. Types.push_back(FTP);
  3899. if (!Unique)
  3900. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  3901. return QualType(FTP, 0);
  3902. }
  3903. QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
  3904. llvm::FoldingSetNodeID ID;
  3905. PipeType::Profile(ID, T, ReadOnly);
  3906. void *InsertPos = nullptr;
  3907. if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
  3908. return QualType(PT, 0);
  3909. // If the pipe element type isn't canonical, this won't be a canonical type
  3910. // either, so fill in the canonical type field.
  3911. QualType Canonical;
  3912. if (!T.isCanonical()) {
  3913. Canonical = getPipeType(getCanonicalType(T), ReadOnly);
  3914. // Get the new insert position for the node we care about.
  3915. PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3916. assert(!NewIP && "Shouldn't be in the map!");
  3917. (void)NewIP;
  3918. }
  3919. auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
  3920. Types.push_back(New);
  3921. PipeTypes.InsertNode(New, InsertPos);
  3922. return QualType(New, 0);
  3923. }
  3924. QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
  3925. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  3926. return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
  3927. : Ty;
  3928. }
  3929. QualType ASTContext::getReadPipeType(QualType T) const {
  3930. return getPipeType(T, true);
  3931. }
  3932. QualType ASTContext::getWritePipeType(QualType T) const {
  3933. return getPipeType(T, false);
  3934. }
  3935. QualType ASTContext::getBitIntType(bool IsUnsigned, unsigned NumBits) const {
  3936. llvm::FoldingSetNodeID ID;
  3937. BitIntType::Profile(ID, IsUnsigned, NumBits);
  3938. void *InsertPos = nullptr;
  3939. if (BitIntType *EIT = BitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
  3940. return QualType(EIT, 0);
  3941. auto *New = new (*this, TypeAlignment) BitIntType(IsUnsigned, NumBits);
  3942. BitIntTypes.InsertNode(New, InsertPos);
  3943. Types.push_back(New);
  3944. return QualType(New, 0);
  3945. }
  3946. QualType ASTContext::getDependentBitIntType(bool IsUnsigned,
  3947. Expr *NumBitsExpr) const {
  3948. assert(NumBitsExpr->isInstantiationDependent() && "Only good for dependent");
  3949. llvm::FoldingSetNodeID ID;
  3950. DependentBitIntType::Profile(ID, *this, IsUnsigned, NumBitsExpr);
  3951. void *InsertPos = nullptr;
  3952. if (DependentBitIntType *Existing =
  3953. DependentBitIntTypes.FindNodeOrInsertPos(ID, InsertPos))
  3954. return QualType(Existing, 0);
  3955. auto *New = new (*this, TypeAlignment)
  3956. DependentBitIntType(*this, IsUnsigned, NumBitsExpr);
  3957. DependentBitIntTypes.InsertNode(New, InsertPos);
  3958. Types.push_back(New);
  3959. return QualType(New, 0);
  3960. }
  3961. #ifndef NDEBUG
  3962. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  3963. if (!isa<CXXRecordDecl>(D)) return false;
  3964. const auto *RD = cast<CXXRecordDecl>(D);
  3965. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  3966. return true;
  3967. if (RD->getDescribedClassTemplate() &&
  3968. !isa<ClassTemplateSpecializationDecl>(RD))
  3969. return true;
  3970. return false;
  3971. }
  3972. #endif
  3973. /// getInjectedClassNameType - Return the unique reference to the
  3974. /// injected class name type for the specified templated declaration.
  3975. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  3976. QualType TST) const {
  3977. assert(NeedsInjectedClassNameType(Decl));
  3978. if (Decl->TypeForDecl) {
  3979. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3980. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  3981. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  3982. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  3983. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3984. } else {
  3985. Type *newType =
  3986. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  3987. Decl->TypeForDecl = newType;
  3988. Types.push_back(newType);
  3989. }
  3990. return QualType(Decl->TypeForDecl, 0);
  3991. }
  3992. /// getTypeDeclType - Return the unique reference to the type for the
  3993. /// specified type declaration.
  3994. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  3995. assert(Decl && "Passed null for Decl param");
  3996. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  3997. if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  3998. return getTypedefType(Typedef);
  3999. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  4000. "Template type parameter types are always available.");
  4001. if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
  4002. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  4003. assert(!NeedsInjectedClassNameType(Record));
  4004. return getRecordType(Record);
  4005. } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
  4006. assert(Enum->isFirstDecl() && "enum has previous declaration");
  4007. return getEnumType(Enum);
  4008. } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  4009. return getUnresolvedUsingType(Using);
  4010. } else
  4011. llvm_unreachable("TypeDecl without a type?");
  4012. return QualType(Decl->TypeForDecl, 0);
  4013. }
  4014. /// getTypedefType - Return the unique reference to the type for the
  4015. /// specified typedef name decl.
  4016. QualType ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  4017. QualType Underlying) const {
  4018. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  4019. if (Underlying.isNull())
  4020. Underlying = Decl->getUnderlyingType();
  4021. QualType Canonical = getCanonicalType(Underlying);
  4022. auto *newType = new (*this, TypeAlignment)
  4023. TypedefType(Type::Typedef, Decl, Underlying, Canonical);
  4024. Decl->TypeForDecl = newType;
  4025. Types.push_back(newType);
  4026. return QualType(newType, 0);
  4027. }
  4028. QualType ASTContext::getUsingType(const UsingShadowDecl *Found,
  4029. QualType Underlying) const {
  4030. llvm::FoldingSetNodeID ID;
  4031. UsingType::Profile(ID, Found);
  4032. void *InsertPos = nullptr;
  4033. UsingType *T = UsingTypes.FindNodeOrInsertPos(ID, InsertPos);
  4034. if (T)
  4035. return QualType(T, 0);
  4036. assert(!Underlying.hasLocalQualifiers());
  4037. assert(Underlying == getTypeDeclType(cast<TypeDecl>(Found->getTargetDecl())));
  4038. QualType Canon = Underlying.getCanonicalType();
  4039. UsingType *NewType =
  4040. new (*this, TypeAlignment) UsingType(Found, Underlying, Canon);
  4041. Types.push_back(NewType);
  4042. UsingTypes.InsertNode(NewType, InsertPos);
  4043. return QualType(NewType, 0);
  4044. }
  4045. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  4046. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  4047. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  4048. if (PrevDecl->TypeForDecl)
  4049. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  4050. auto *newType = new (*this, TypeAlignment) RecordType(Decl);
  4051. Decl->TypeForDecl = newType;
  4052. Types.push_back(newType);
  4053. return QualType(newType, 0);
  4054. }
  4055. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  4056. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  4057. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  4058. if (PrevDecl->TypeForDecl)
  4059. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  4060. auto *newType = new (*this, TypeAlignment) EnumType(Decl);
  4061. Decl->TypeForDecl = newType;
  4062. Types.push_back(newType);
  4063. return QualType(newType, 0);
  4064. }
  4065. QualType ASTContext::getUnresolvedUsingType(
  4066. const UnresolvedUsingTypenameDecl *Decl) const {
  4067. if (Decl->TypeForDecl)
  4068. return QualType(Decl->TypeForDecl, 0);
  4069. if (const UnresolvedUsingTypenameDecl *CanonicalDecl =
  4070. Decl->getCanonicalDecl())
  4071. if (CanonicalDecl->TypeForDecl)
  4072. return QualType(Decl->TypeForDecl = CanonicalDecl->TypeForDecl, 0);
  4073. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Decl);
  4074. Decl->TypeForDecl = newType;
  4075. Types.push_back(newType);
  4076. return QualType(newType, 0);
  4077. }
  4078. QualType ASTContext::getAttributedType(attr::Kind attrKind,
  4079. QualType modifiedType,
  4080. QualType equivalentType) {
  4081. llvm::FoldingSetNodeID id;
  4082. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  4083. void *insertPos = nullptr;
  4084. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  4085. if (type) return QualType(type, 0);
  4086. QualType canon = getCanonicalType(equivalentType);
  4087. type = new (*this, TypeAlignment)
  4088. AttributedType(canon, attrKind, modifiedType, equivalentType);
  4089. Types.push_back(type);
  4090. AttributedTypes.InsertNode(type, insertPos);
  4091. return QualType(type, 0);
  4092. }
  4093. /// Retrieve a substitution-result type.
  4094. QualType
  4095. ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
  4096. QualType Replacement) const {
  4097. assert(Replacement.isCanonical()
  4098. && "replacement types must always be canonical");
  4099. llvm::FoldingSetNodeID ID;
  4100. SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
  4101. void *InsertPos = nullptr;
  4102. SubstTemplateTypeParmType *SubstParm
  4103. = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4104. if (!SubstParm) {
  4105. SubstParm = new (*this, TypeAlignment)
  4106. SubstTemplateTypeParmType(Parm, Replacement);
  4107. Types.push_back(SubstParm);
  4108. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  4109. }
  4110. return QualType(SubstParm, 0);
  4111. }
  4112. /// Retrieve a
  4113. QualType ASTContext::getSubstTemplateTypeParmPackType(
  4114. const TemplateTypeParmType *Parm,
  4115. const TemplateArgument &ArgPack) {
  4116. #ifndef NDEBUG
  4117. for (const auto &P : ArgPack.pack_elements()) {
  4118. assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
  4119. assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
  4120. }
  4121. #endif
  4122. llvm::FoldingSetNodeID ID;
  4123. SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
  4124. void *InsertPos = nullptr;
  4125. if (SubstTemplateTypeParmPackType *SubstParm
  4126. = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  4127. return QualType(SubstParm, 0);
  4128. QualType Canon;
  4129. if (!Parm->isCanonicalUnqualified()) {
  4130. Canon = getCanonicalType(QualType(Parm, 0));
  4131. Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
  4132. ArgPack);
  4133. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  4134. }
  4135. auto *SubstParm
  4136. = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
  4137. ArgPack);
  4138. Types.push_back(SubstParm);
  4139. SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
  4140. return QualType(SubstParm, 0);
  4141. }
  4142. /// Retrieve the template type parameter type for a template
  4143. /// parameter or parameter pack with the given depth, index, and (optionally)
  4144. /// name.
  4145. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  4146. bool ParameterPack,
  4147. TemplateTypeParmDecl *TTPDecl) const {
  4148. llvm::FoldingSetNodeID ID;
  4149. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  4150. void *InsertPos = nullptr;
  4151. TemplateTypeParmType *TypeParm
  4152. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4153. if (TypeParm)
  4154. return QualType(TypeParm, 0);
  4155. if (TTPDecl) {
  4156. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  4157. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  4158. TemplateTypeParmType *TypeCheck
  4159. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  4160. assert(!TypeCheck && "Template type parameter canonical type broken");
  4161. (void)TypeCheck;
  4162. } else
  4163. TypeParm = new (*this, TypeAlignment)
  4164. TemplateTypeParmType(Depth, Index, ParameterPack);
  4165. Types.push_back(TypeParm);
  4166. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  4167. return QualType(TypeParm, 0);
  4168. }
  4169. TypeSourceInfo *
  4170. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  4171. SourceLocation NameLoc,
  4172. const TemplateArgumentListInfo &Args,
  4173. QualType Underlying) const {
  4174. assert(!Name.getAsDependentTemplateName() &&
  4175. "No dependent template names here!");
  4176. QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
  4177. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  4178. TemplateSpecializationTypeLoc TL =
  4179. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  4180. TL.setTemplateKeywordLoc(SourceLocation());
  4181. TL.setTemplateNameLoc(NameLoc);
  4182. TL.setLAngleLoc(Args.getLAngleLoc());
  4183. TL.setRAngleLoc(Args.getRAngleLoc());
  4184. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  4185. TL.setArgLocInfo(i, Args[i].getLocInfo());
  4186. return DI;
  4187. }
  4188. QualType
  4189. ASTContext::getTemplateSpecializationType(TemplateName Template,
  4190. const TemplateArgumentListInfo &Args,
  4191. QualType Underlying) const {
  4192. assert(!Template.getAsDependentTemplateName() &&
  4193. "No dependent template names here!");
  4194. SmallVector<TemplateArgument, 4> ArgVec;
  4195. ArgVec.reserve(Args.size());
  4196. for (const TemplateArgumentLoc &Arg : Args.arguments())
  4197. ArgVec.push_back(Arg.getArgument());
  4198. return getTemplateSpecializationType(Template, ArgVec, Underlying);
  4199. }
  4200. #ifndef NDEBUG
  4201. static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
  4202. for (const TemplateArgument &Arg : Args)
  4203. if (Arg.isPackExpansion())
  4204. return true;
  4205. return true;
  4206. }
  4207. #endif
  4208. QualType
  4209. ASTContext::getTemplateSpecializationType(TemplateName Template,
  4210. ArrayRef<TemplateArgument> Args,
  4211. QualType Underlying) const {
  4212. assert(!Template.getAsDependentTemplateName() &&
  4213. "No dependent template names here!");
  4214. // Look through qualified template names.
  4215. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  4216. Template = TemplateName(QTN->getTemplateDecl());
  4217. bool IsTypeAlias =
  4218. Template.getAsTemplateDecl() &&
  4219. isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
  4220. QualType CanonType;
  4221. if (!Underlying.isNull())
  4222. CanonType = getCanonicalType(Underlying);
  4223. else {
  4224. // We can get here with an alias template when the specialization contains
  4225. // a pack expansion that does not match up with a parameter pack.
  4226. assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
  4227. "Caller must compute aliased type");
  4228. IsTypeAlias = false;
  4229. CanonType = getCanonicalTemplateSpecializationType(Template, Args);
  4230. }
  4231. // Allocate the (non-canonical) template specialization type, but don't
  4232. // try to unique it: these types typically have location information that
  4233. // we don't unique and don't want to lose.
  4234. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  4235. sizeof(TemplateArgument) * Args.size() +
  4236. (IsTypeAlias? sizeof(QualType) : 0),
  4237. TypeAlignment);
  4238. auto *Spec
  4239. = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
  4240. IsTypeAlias ? Underlying : QualType());
  4241. Types.push_back(Spec);
  4242. return QualType(Spec, 0);
  4243. }
  4244. static bool
  4245. getCanonicalTemplateArguments(const ASTContext &C,
  4246. ArrayRef<TemplateArgument> OrigArgs,
  4247. SmallVectorImpl<TemplateArgument> &CanonArgs) {
  4248. bool AnyNonCanonArgs = false;
  4249. unsigned NumArgs = OrigArgs.size();
  4250. CanonArgs.resize(NumArgs);
  4251. for (unsigned I = 0; I != NumArgs; ++I) {
  4252. const TemplateArgument &OrigArg = OrigArgs[I];
  4253. TemplateArgument &CanonArg = CanonArgs[I];
  4254. CanonArg = C.getCanonicalTemplateArgument(OrigArg);
  4255. if (!CanonArg.structurallyEquals(OrigArg))
  4256. AnyNonCanonArgs = true;
  4257. }
  4258. return AnyNonCanonArgs;
  4259. }
  4260. QualType ASTContext::getCanonicalTemplateSpecializationType(
  4261. TemplateName Template, ArrayRef<TemplateArgument> Args) const {
  4262. assert(!Template.getAsDependentTemplateName() &&
  4263. "No dependent template names here!");
  4264. // Look through qualified template names.
  4265. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  4266. Template = TemplateName(QTN->getTemplateDecl());
  4267. // Build the canonical template specialization type.
  4268. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  4269. SmallVector<TemplateArgument, 4> CanonArgs;
  4270. ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
  4271. // Determine whether this canonical template specialization type already
  4272. // exists.
  4273. llvm::FoldingSetNodeID ID;
  4274. TemplateSpecializationType::Profile(ID, CanonTemplate,
  4275. CanonArgs, *this);
  4276. void *InsertPos = nullptr;
  4277. TemplateSpecializationType *Spec
  4278. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4279. if (!Spec) {
  4280. // Allocate a new canonical template specialization type.
  4281. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  4282. sizeof(TemplateArgument) * CanonArgs.size()),
  4283. TypeAlignment);
  4284. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  4285. CanonArgs,
  4286. QualType(), QualType());
  4287. Types.push_back(Spec);
  4288. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  4289. }
  4290. assert(Spec->isDependentType() &&
  4291. "Non-dependent template-id type must have a canonical type");
  4292. return QualType(Spec, 0);
  4293. }
  4294. QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  4295. NestedNameSpecifier *NNS,
  4296. QualType NamedType,
  4297. TagDecl *OwnedTagDecl) const {
  4298. llvm::FoldingSetNodeID ID;
  4299. ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
  4300. void *InsertPos = nullptr;
  4301. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  4302. if (T)
  4303. return QualType(T, 0);
  4304. QualType Canon = NamedType;
  4305. if (!Canon.isCanonical()) {
  4306. Canon = getCanonicalType(NamedType);
  4307. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  4308. assert(!CheckT && "Elaborated canonical type broken");
  4309. (void)CheckT;
  4310. }
  4311. void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
  4312. TypeAlignment);
  4313. T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
  4314. Types.push_back(T);
  4315. ElaboratedTypes.InsertNode(T, InsertPos);
  4316. return QualType(T, 0);
  4317. }
  4318. QualType
  4319. ASTContext::getParenType(QualType InnerType) const {
  4320. llvm::FoldingSetNodeID ID;
  4321. ParenType::Profile(ID, InnerType);
  4322. void *InsertPos = nullptr;
  4323. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  4324. if (T)
  4325. return QualType(T, 0);
  4326. QualType Canon = InnerType;
  4327. if (!Canon.isCanonical()) {
  4328. Canon = getCanonicalType(InnerType);
  4329. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  4330. assert(!CheckT && "Paren canonical type broken");
  4331. (void)CheckT;
  4332. }
  4333. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  4334. Types.push_back(T);
  4335. ParenTypes.InsertNode(T, InsertPos);
  4336. return QualType(T, 0);
  4337. }
  4338. QualType
  4339. ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
  4340. const IdentifierInfo *MacroII) const {
  4341. QualType Canon = UnderlyingTy;
  4342. if (!Canon.isCanonical())
  4343. Canon = getCanonicalType(UnderlyingTy);
  4344. auto *newType = new (*this, TypeAlignment)
  4345. MacroQualifiedType(UnderlyingTy, Canon, MacroII);
  4346. Types.push_back(newType);
  4347. return QualType(newType, 0);
  4348. }
  4349. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  4350. NestedNameSpecifier *NNS,
  4351. const IdentifierInfo *Name,
  4352. QualType Canon) const {
  4353. if (Canon.isNull()) {
  4354. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  4355. if (CanonNNS != NNS)
  4356. Canon = getDependentNameType(Keyword, CanonNNS, Name);
  4357. }
  4358. llvm::FoldingSetNodeID ID;
  4359. DependentNameType::Profile(ID, Keyword, NNS, Name);
  4360. void *InsertPos = nullptr;
  4361. DependentNameType *T
  4362. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  4363. if (T)
  4364. return QualType(T, 0);
  4365. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  4366. Types.push_back(T);
  4367. DependentNameTypes.InsertNode(T, InsertPos);
  4368. return QualType(T, 0);
  4369. }
  4370. QualType
  4371. ASTContext::getDependentTemplateSpecializationType(
  4372. ElaboratedTypeKeyword Keyword,
  4373. NestedNameSpecifier *NNS,
  4374. const IdentifierInfo *Name,
  4375. const TemplateArgumentListInfo &Args) const {
  4376. // TODO: avoid this copy
  4377. SmallVector<TemplateArgument, 16> ArgCopy;
  4378. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  4379. ArgCopy.push_back(Args[I].getArgument());
  4380. return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
  4381. }
  4382. QualType
  4383. ASTContext::getDependentTemplateSpecializationType(
  4384. ElaboratedTypeKeyword Keyword,
  4385. NestedNameSpecifier *NNS,
  4386. const IdentifierInfo *Name,
  4387. ArrayRef<TemplateArgument> Args) const {
  4388. assert((!NNS || NNS->isDependent()) &&
  4389. "nested-name-specifier must be dependent");
  4390. llvm::FoldingSetNodeID ID;
  4391. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  4392. Name, Args);
  4393. void *InsertPos = nullptr;
  4394. DependentTemplateSpecializationType *T
  4395. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4396. if (T)
  4397. return QualType(T, 0);
  4398. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  4399. ElaboratedTypeKeyword CanonKeyword = Keyword;
  4400. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  4401. SmallVector<TemplateArgument, 16> CanonArgs;
  4402. bool AnyNonCanonArgs =
  4403. ::getCanonicalTemplateArguments(*this, Args, CanonArgs);
  4404. QualType Canon;
  4405. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  4406. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  4407. Name,
  4408. CanonArgs);
  4409. // Find the insert position again.
  4410. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  4411. }
  4412. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  4413. sizeof(TemplateArgument) * Args.size()),
  4414. TypeAlignment);
  4415. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  4416. Name, Args, Canon);
  4417. Types.push_back(T);
  4418. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  4419. return QualType(T, 0);
  4420. }
  4421. TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
  4422. TemplateArgument Arg;
  4423. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  4424. QualType ArgType = getTypeDeclType(TTP);
  4425. if (TTP->isParameterPack())
  4426. ArgType = getPackExpansionType(ArgType, None);
  4427. Arg = TemplateArgument(ArgType);
  4428. } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  4429. QualType T =
  4430. NTTP->getType().getNonPackExpansionType().getNonLValueExprType(*this);
  4431. // For class NTTPs, ensure we include the 'const' so the type matches that
  4432. // of a real template argument.
  4433. // FIXME: It would be more faithful to model this as something like an
  4434. // lvalue-to-rvalue conversion applied to a const-qualified lvalue.
  4435. if (T->isRecordType())
  4436. T.addConst();
  4437. Expr *E = new (*this) DeclRefExpr(
  4438. *this, NTTP, /*enclosing*/ false, T,
  4439. Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
  4440. if (NTTP->isParameterPack())
  4441. E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
  4442. None);
  4443. Arg = TemplateArgument(E);
  4444. } else {
  4445. auto *TTP = cast<TemplateTemplateParmDecl>(Param);
  4446. if (TTP->isParameterPack())
  4447. Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
  4448. else
  4449. Arg = TemplateArgument(TemplateName(TTP));
  4450. }
  4451. if (Param->isTemplateParameterPack())
  4452. Arg = TemplateArgument::CreatePackCopy(*this, Arg);
  4453. return Arg;
  4454. }
  4455. void
  4456. ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
  4457. SmallVectorImpl<TemplateArgument> &Args) {
  4458. Args.reserve(Args.size() + Params->size());
  4459. for (NamedDecl *Param : *Params)
  4460. Args.push_back(getInjectedTemplateArg(Param));
  4461. }
  4462. QualType ASTContext::getPackExpansionType(QualType Pattern,
  4463. Optional<unsigned> NumExpansions,
  4464. bool ExpectPackInType) {
  4465. assert((!ExpectPackInType || Pattern->containsUnexpandedParameterPack()) &&
  4466. "Pack expansions must expand one or more parameter packs");
  4467. llvm::FoldingSetNodeID ID;
  4468. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  4469. void *InsertPos = nullptr;
  4470. PackExpansionType *T = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  4471. if (T)
  4472. return QualType(T, 0);
  4473. QualType Canon;
  4474. if (!Pattern.isCanonical()) {
  4475. Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions,
  4476. /*ExpectPackInType=*/false);
  4477. // Find the insert position again, in case we inserted an element into
  4478. // PackExpansionTypes and invalidated our insert position.
  4479. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  4480. }
  4481. T = new (*this, TypeAlignment)
  4482. PackExpansionType(Pattern, Canon, NumExpansions);
  4483. Types.push_back(T);
  4484. PackExpansionTypes.InsertNode(T, InsertPos);
  4485. return QualType(T, 0);
  4486. }
  4487. /// CmpProtocolNames - Comparison predicate for sorting protocols
  4488. /// alphabetically.
  4489. static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
  4490. ObjCProtocolDecl *const *RHS) {
  4491. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  4492. }
  4493. static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
  4494. if (Protocols.empty()) return true;
  4495. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  4496. return false;
  4497. for (unsigned i = 1; i != Protocols.size(); ++i)
  4498. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  4499. Protocols[i]->getCanonicalDecl() != Protocols[i])
  4500. return false;
  4501. return true;
  4502. }
  4503. static void
  4504. SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
  4505. // Sort protocols, keyed by name.
  4506. llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
  4507. // Canonicalize.
  4508. for (ObjCProtocolDecl *&P : Protocols)
  4509. P = P->getCanonicalDecl();
  4510. // Remove duplicates.
  4511. auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
  4512. Protocols.erase(ProtocolsEnd, Protocols.end());
  4513. }
  4514. QualType ASTContext::getObjCObjectType(QualType BaseType,
  4515. ObjCProtocolDecl * const *Protocols,
  4516. unsigned NumProtocols) const {
  4517. return getObjCObjectType(BaseType, {},
  4518. llvm::makeArrayRef(Protocols, NumProtocols),
  4519. /*isKindOf=*/false);
  4520. }
  4521. QualType ASTContext::getObjCObjectType(
  4522. QualType baseType,
  4523. ArrayRef<QualType> typeArgs,
  4524. ArrayRef<ObjCProtocolDecl *> protocols,
  4525. bool isKindOf) const {
  4526. // If the base type is an interface and there aren't any protocols or
  4527. // type arguments to add, then the interface type will do just fine.
  4528. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  4529. isa<ObjCInterfaceType>(baseType))
  4530. return baseType;
  4531. // Look in the folding set for an existing type.
  4532. llvm::FoldingSetNodeID ID;
  4533. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  4534. void *InsertPos = nullptr;
  4535. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  4536. return QualType(QT, 0);
  4537. // Determine the type arguments to be used for canonicalization,
  4538. // which may be explicitly specified here or written on the base
  4539. // type.
  4540. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  4541. if (effectiveTypeArgs.empty()) {
  4542. if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
  4543. effectiveTypeArgs = baseObject->getTypeArgs();
  4544. }
  4545. // Build the canonical type, which has the canonical base type and a
  4546. // sorted-and-uniqued list of protocols and the type arguments
  4547. // canonicalized.
  4548. QualType canonical;
  4549. bool typeArgsAreCanonical = llvm::all_of(
  4550. effectiveTypeArgs, [&](QualType type) { return type.isCanonical(); });
  4551. bool protocolsSorted = areSortedAndUniqued(protocols);
  4552. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  4553. // Determine the canonical type arguments.
  4554. ArrayRef<QualType> canonTypeArgs;
  4555. SmallVector<QualType, 4> canonTypeArgsVec;
  4556. if (!typeArgsAreCanonical) {
  4557. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  4558. for (auto typeArg : effectiveTypeArgs)
  4559. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  4560. canonTypeArgs = canonTypeArgsVec;
  4561. } else {
  4562. canonTypeArgs = effectiveTypeArgs;
  4563. }
  4564. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  4565. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  4566. if (!protocolsSorted) {
  4567. canonProtocolsVec.append(protocols.begin(), protocols.end());
  4568. SortAndUniqueProtocols(canonProtocolsVec);
  4569. canonProtocols = canonProtocolsVec;
  4570. } else {
  4571. canonProtocols = protocols;
  4572. }
  4573. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  4574. canonProtocols, isKindOf);
  4575. // Regenerate InsertPos.
  4576. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  4577. }
  4578. unsigned size = sizeof(ObjCObjectTypeImpl);
  4579. size += typeArgs.size() * sizeof(QualType);
  4580. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4581. void *mem = Allocate(size, TypeAlignment);
  4582. auto *T =
  4583. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  4584. isKindOf);
  4585. Types.push_back(T);
  4586. ObjCObjectTypes.InsertNode(T, InsertPos);
  4587. return QualType(T, 0);
  4588. }
  4589. /// Apply Objective-C protocol qualifiers to the given type.
  4590. /// If this is for the canonical type of a type parameter, we can apply
  4591. /// protocol qualifiers on the ObjCObjectPointerType.
  4592. QualType
  4593. ASTContext::applyObjCProtocolQualifiers(QualType type,
  4594. ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
  4595. bool allowOnPointerType) const {
  4596. hasError = false;
  4597. if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
  4598. return getObjCTypeParamType(objT->getDecl(), protocols);
  4599. }
  4600. // Apply protocol qualifiers to ObjCObjectPointerType.
  4601. if (allowOnPointerType) {
  4602. if (const auto *objPtr =
  4603. dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
  4604. const ObjCObjectType *objT = objPtr->getObjectType();
  4605. // Merge protocol lists and construct ObjCObjectType.
  4606. SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
  4607. protocolsVec.append(objT->qual_begin(),
  4608. objT->qual_end());
  4609. protocolsVec.append(protocols.begin(), protocols.end());
  4610. ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
  4611. type = getObjCObjectType(
  4612. objT->getBaseType(),
  4613. objT->getTypeArgsAsWritten(),
  4614. protocols,
  4615. objT->isKindOfTypeAsWritten());
  4616. return getObjCObjectPointerType(type);
  4617. }
  4618. }
  4619. // Apply protocol qualifiers to ObjCObjectType.
  4620. if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
  4621. // FIXME: Check for protocols to which the class type is already
  4622. // known to conform.
  4623. return getObjCObjectType(objT->getBaseType(),
  4624. objT->getTypeArgsAsWritten(),
  4625. protocols,
  4626. objT->isKindOfTypeAsWritten());
  4627. }
  4628. // If the canonical type is ObjCObjectType, ...
  4629. if (type->isObjCObjectType()) {
  4630. // Silently overwrite any existing protocol qualifiers.
  4631. // TODO: determine whether that's the right thing to do.
  4632. // FIXME: Check for protocols to which the class type is already
  4633. // known to conform.
  4634. return getObjCObjectType(type, {}, protocols, false);
  4635. }
  4636. // id<protocol-list>
  4637. if (type->isObjCIdType()) {
  4638. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4639. type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
  4640. objPtr->isKindOfType());
  4641. return getObjCObjectPointerType(type);
  4642. }
  4643. // Class<protocol-list>
  4644. if (type->isObjCClassType()) {
  4645. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4646. type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
  4647. objPtr->isKindOfType());
  4648. return getObjCObjectPointerType(type);
  4649. }
  4650. hasError = true;
  4651. return type;
  4652. }
  4653. QualType
  4654. ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  4655. ArrayRef<ObjCProtocolDecl *> protocols) const {
  4656. // Look in the folding set for an existing type.
  4657. llvm::FoldingSetNodeID ID;
  4658. ObjCTypeParamType::Profile(ID, Decl, Decl->getUnderlyingType(), protocols);
  4659. void *InsertPos = nullptr;
  4660. if (ObjCTypeParamType *TypeParam =
  4661. ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
  4662. return QualType(TypeParam, 0);
  4663. // We canonicalize to the underlying type.
  4664. QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
  4665. if (!protocols.empty()) {
  4666. // Apply the protocol qualifers.
  4667. bool hasError;
  4668. Canonical = getCanonicalType(applyObjCProtocolQualifiers(
  4669. Canonical, protocols, hasError, true /*allowOnPointerType*/));
  4670. assert(!hasError && "Error when apply protocol qualifier to bound type");
  4671. }
  4672. unsigned size = sizeof(ObjCTypeParamType);
  4673. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4674. void *mem = Allocate(size, TypeAlignment);
  4675. auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
  4676. Types.push_back(newType);
  4677. ObjCTypeParamTypes.InsertNode(newType, InsertPos);
  4678. return QualType(newType, 0);
  4679. }
  4680. void ASTContext::adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
  4681. ObjCTypeParamDecl *New) const {
  4682. New->setTypeSourceInfo(getTrivialTypeSourceInfo(Orig->getUnderlyingType()));
  4683. // Update TypeForDecl after updating TypeSourceInfo.
  4684. auto NewTypeParamTy = cast<ObjCTypeParamType>(New->getTypeForDecl());
  4685. SmallVector<ObjCProtocolDecl *, 8> protocols;
  4686. protocols.append(NewTypeParamTy->qual_begin(), NewTypeParamTy->qual_end());
  4687. QualType UpdatedTy = getObjCTypeParamType(New, protocols);
  4688. New->setTypeForDecl(UpdatedTy.getTypePtr());
  4689. }
  4690. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  4691. /// protocol list adopt all protocols in QT's qualified-id protocol
  4692. /// list.
  4693. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  4694. ObjCInterfaceDecl *IC) {
  4695. if (!QT->isObjCQualifiedIdType())
  4696. return false;
  4697. if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
  4698. // If both the right and left sides have qualifiers.
  4699. for (auto *Proto : OPT->quals()) {
  4700. if (!IC->ClassImplementsProtocol(Proto, false))
  4701. return false;
  4702. }
  4703. return true;
  4704. }
  4705. return false;
  4706. }
  4707. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  4708. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  4709. /// of protocols.
  4710. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  4711. ObjCInterfaceDecl *IDecl) {
  4712. if (!QT->isObjCQualifiedIdType())
  4713. return false;
  4714. const auto *OPT = QT->getAs<ObjCObjectPointerType>();
  4715. if (!OPT)
  4716. return false;
  4717. if (!IDecl->hasDefinition())
  4718. return false;
  4719. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  4720. CollectInheritedProtocols(IDecl, InheritedProtocols);
  4721. if (InheritedProtocols.empty())
  4722. return false;
  4723. // Check that if every protocol in list of id<plist> conforms to a protocol
  4724. // of IDecl's, then bridge casting is ok.
  4725. bool Conforms = false;
  4726. for (auto *Proto : OPT->quals()) {
  4727. Conforms = false;
  4728. for (auto *PI : InheritedProtocols) {
  4729. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  4730. Conforms = true;
  4731. break;
  4732. }
  4733. }
  4734. if (!Conforms)
  4735. break;
  4736. }
  4737. if (Conforms)
  4738. return true;
  4739. for (auto *PI : InheritedProtocols) {
  4740. // If both the right and left sides have qualifiers.
  4741. bool Adopts = false;
  4742. for (auto *Proto : OPT->quals()) {
  4743. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  4744. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  4745. break;
  4746. }
  4747. if (!Adopts)
  4748. return false;
  4749. }
  4750. return true;
  4751. }
  4752. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  4753. /// the given object type.
  4754. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  4755. llvm::FoldingSetNodeID ID;
  4756. ObjCObjectPointerType::Profile(ID, ObjectT);
  4757. void *InsertPos = nullptr;
  4758. if (ObjCObjectPointerType *QT =
  4759. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  4760. return QualType(QT, 0);
  4761. // Find the canonical object type.
  4762. QualType Canonical;
  4763. if (!ObjectT.isCanonical()) {
  4764. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  4765. // Regenerate InsertPos.
  4766. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  4767. }
  4768. // No match.
  4769. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  4770. auto *QType =
  4771. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  4772. Types.push_back(QType);
  4773. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  4774. return QualType(QType, 0);
  4775. }
  4776. /// getObjCInterfaceType - Return the unique reference to the type for the
  4777. /// specified ObjC interface decl. The list of protocols is optional.
  4778. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  4779. ObjCInterfaceDecl *PrevDecl) const {
  4780. if (Decl->TypeForDecl)
  4781. return QualType(Decl->TypeForDecl, 0);
  4782. if (PrevDecl) {
  4783. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  4784. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  4785. return QualType(PrevDecl->TypeForDecl, 0);
  4786. }
  4787. // Prefer the definition, if there is one.
  4788. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  4789. Decl = Def;
  4790. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  4791. auto *T = new (Mem) ObjCInterfaceType(Decl);
  4792. Decl->TypeForDecl = T;
  4793. Types.push_back(T);
  4794. return QualType(T, 0);
  4795. }
  4796. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  4797. /// TypeOfExprType AST's (since expression's are never shared). For example,
  4798. /// multiple declarations that refer to "typeof(x)" all contain different
  4799. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  4800. /// on canonical type's (which are always unique).
  4801. QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
  4802. TypeOfExprType *toe;
  4803. if (tofExpr->isTypeDependent()) {
  4804. llvm::FoldingSetNodeID ID;
  4805. DependentTypeOfExprType::Profile(ID, *this, tofExpr);
  4806. void *InsertPos = nullptr;
  4807. DependentTypeOfExprType *Canon
  4808. = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  4809. if (Canon) {
  4810. // We already have a "canonical" version of an identical, dependent
  4811. // typeof(expr) type. Use that as our canonical type.
  4812. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
  4813. QualType((TypeOfExprType*)Canon, 0));
  4814. } else {
  4815. // Build a new, canonical typeof(expr) type.
  4816. Canon
  4817. = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
  4818. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  4819. toe = Canon;
  4820. }
  4821. } else {
  4822. QualType Canonical = getCanonicalType(tofExpr->getType());
  4823. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
  4824. }
  4825. Types.push_back(toe);
  4826. return QualType(toe, 0);
  4827. }
  4828. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  4829. /// TypeOfType nodes. The only motivation to unique these nodes would be
  4830. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  4831. /// an issue. This doesn't affect the type checker, since it operates
  4832. /// on canonical types (which are always unique).
  4833. QualType ASTContext::getTypeOfType(QualType tofType) const {
  4834. QualType Canonical = getCanonicalType(tofType);
  4835. auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
  4836. Types.push_back(tot);
  4837. return QualType(tot, 0);
  4838. }
  4839. /// getReferenceQualifiedType - Given an expr, will return the type for
  4840. /// that expression, as in [dcl.type.simple]p4 but without taking id-expressions
  4841. /// and class member access into account.
  4842. QualType ASTContext::getReferenceQualifiedType(const Expr *E) const {
  4843. // C++11 [dcl.type.simple]p4:
  4844. // [...]
  4845. QualType T = E->getType();
  4846. switch (E->getValueKind()) {
  4847. // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
  4848. // type of e;
  4849. case VK_XValue:
  4850. return getRValueReferenceType(T);
  4851. // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
  4852. // type of e;
  4853. case VK_LValue:
  4854. return getLValueReferenceType(T);
  4855. // - otherwise, decltype(e) is the type of e.
  4856. case VK_PRValue:
  4857. return T;
  4858. }
  4859. llvm_unreachable("Unknown value kind");
  4860. }
  4861. /// Unlike many "get<Type>" functions, we don't unique DecltypeType
  4862. /// nodes. This would never be helpful, since each such type has its own
  4863. /// expression, and would not give a significant memory saving, since there
  4864. /// is an Expr tree under each such type.
  4865. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  4866. DecltypeType *dt;
  4867. // C++11 [temp.type]p2:
  4868. // If an expression e involves a template parameter, decltype(e) denotes a
  4869. // unique dependent type. Two such decltype-specifiers refer to the same
  4870. // type only if their expressions are equivalent (14.5.6.1).
  4871. if (e->isInstantiationDependent()) {
  4872. llvm::FoldingSetNodeID ID;
  4873. DependentDecltypeType::Profile(ID, *this, e);
  4874. void *InsertPos = nullptr;
  4875. DependentDecltypeType *Canon
  4876. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  4877. if (!Canon) {
  4878. // Build a new, canonical decltype(expr) type.
  4879. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  4880. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  4881. }
  4882. dt = new (*this, TypeAlignment)
  4883. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  4884. } else {
  4885. dt = new (*this, TypeAlignment)
  4886. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  4887. }
  4888. Types.push_back(dt);
  4889. return QualType(dt, 0);
  4890. }
  4891. /// getUnaryTransformationType - We don't unique these, since the memory
  4892. /// savings are minimal and these are rare.
  4893. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  4894. QualType UnderlyingType,
  4895. UnaryTransformType::UTTKind Kind)
  4896. const {
  4897. UnaryTransformType *ut = nullptr;
  4898. if (BaseType->isDependentType()) {
  4899. // Look in the folding set for an existing type.
  4900. llvm::FoldingSetNodeID ID;
  4901. DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
  4902. void *InsertPos = nullptr;
  4903. DependentUnaryTransformType *Canon
  4904. = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
  4905. if (!Canon) {
  4906. // Build a new, canonical __underlying_type(type) type.
  4907. Canon = new (*this, TypeAlignment)
  4908. DependentUnaryTransformType(*this, getCanonicalType(BaseType),
  4909. Kind);
  4910. DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
  4911. }
  4912. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4913. QualType(), Kind,
  4914. QualType(Canon, 0));
  4915. } else {
  4916. QualType CanonType = getCanonicalType(UnderlyingType);
  4917. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4918. UnderlyingType, Kind,
  4919. CanonType);
  4920. }
  4921. Types.push_back(ut);
  4922. return QualType(ut, 0);
  4923. }
  4924. QualType ASTContext::getAutoTypeInternal(
  4925. QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent,
  4926. bool IsPack, ConceptDecl *TypeConstraintConcept,
  4927. ArrayRef<TemplateArgument> TypeConstraintArgs, bool IsCanon) const {
  4928. if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto &&
  4929. !TypeConstraintConcept && !IsDependent)
  4930. return getAutoDeductType();
  4931. // Look in the folding set for an existing type.
  4932. void *InsertPos = nullptr;
  4933. llvm::FoldingSetNodeID ID;
  4934. AutoType::Profile(ID, *this, DeducedType, Keyword, IsDependent,
  4935. TypeConstraintConcept, TypeConstraintArgs);
  4936. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  4937. return QualType(AT, 0);
  4938. QualType Canon;
  4939. if (!IsCanon) {
  4940. if (DeducedType.isNull()) {
  4941. SmallVector<TemplateArgument, 4> CanonArgs;
  4942. bool AnyNonCanonArgs =
  4943. ::getCanonicalTemplateArguments(*this, TypeConstraintArgs, CanonArgs);
  4944. if (AnyNonCanonArgs) {
  4945. Canon = getAutoTypeInternal(QualType(), Keyword, IsDependent, IsPack,
  4946. TypeConstraintConcept, CanonArgs, true);
  4947. // Find the insert position again.
  4948. AutoTypes.FindNodeOrInsertPos(ID, InsertPos);
  4949. }
  4950. } else {
  4951. Canon = DeducedType.getCanonicalType();
  4952. }
  4953. }
  4954. void *Mem = Allocate(sizeof(AutoType) +
  4955. sizeof(TemplateArgument) * TypeConstraintArgs.size(),
  4956. TypeAlignment);
  4957. auto *AT = new (Mem) AutoType(
  4958. DeducedType, Keyword,
  4959. (IsDependent ? TypeDependence::DependentInstantiation
  4960. : TypeDependence::None) |
  4961. (IsPack ? TypeDependence::UnexpandedPack : TypeDependence::None),
  4962. Canon, TypeConstraintConcept, TypeConstraintArgs);
  4963. Types.push_back(AT);
  4964. AutoTypes.InsertNode(AT, InsertPos);
  4965. return QualType(AT, 0);
  4966. }
  4967. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  4968. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  4969. /// canonical deduced-but-dependent 'auto' type.
  4970. QualType
  4971. ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
  4972. bool IsDependent, bool IsPack,
  4973. ConceptDecl *TypeConstraintConcept,
  4974. ArrayRef<TemplateArgument> TypeConstraintArgs) const {
  4975. assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
  4976. assert((!IsDependent || DeducedType.isNull()) &&
  4977. "A dependent auto should be undeduced");
  4978. return getAutoTypeInternal(DeducedType, Keyword, IsDependent, IsPack,
  4979. TypeConstraintConcept, TypeConstraintArgs);
  4980. }
  4981. /// Return the uniqued reference to the deduced template specialization type
  4982. /// which has been deduced to the given type, or to the canonical undeduced
  4983. /// such type, or the canonical deduced-but-dependent such type.
  4984. QualType ASTContext::getDeducedTemplateSpecializationType(
  4985. TemplateName Template, QualType DeducedType, bool IsDependent) const {
  4986. // Look in the folding set for an existing type.
  4987. void *InsertPos = nullptr;
  4988. llvm::FoldingSetNodeID ID;
  4989. DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
  4990. IsDependent);
  4991. if (DeducedTemplateSpecializationType *DTST =
  4992. DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
  4993. return QualType(DTST, 0);
  4994. auto *DTST = new (*this, TypeAlignment)
  4995. DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
  4996. llvm::FoldingSetNodeID TempID;
  4997. DTST->Profile(TempID);
  4998. assert(ID == TempID && "ID does not match");
  4999. Types.push_back(DTST);
  5000. DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
  5001. return QualType(DTST, 0);
  5002. }
  5003. /// getAtomicType - Return the uniqued reference to the atomic type for
  5004. /// the given value type.
  5005. QualType ASTContext::getAtomicType(QualType T) const {
  5006. // Unique pointers, to guarantee there is only one pointer of a particular
  5007. // structure.
  5008. llvm::FoldingSetNodeID ID;
  5009. AtomicType::Profile(ID, T);
  5010. void *InsertPos = nullptr;
  5011. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  5012. return QualType(AT, 0);
  5013. // If the atomic value type isn't canonical, this won't be a canonical type
  5014. // either, so fill in the canonical type field.
  5015. QualType Canonical;
  5016. if (!T.isCanonical()) {
  5017. Canonical = getAtomicType(getCanonicalType(T));
  5018. // Get the new insert position for the node we care about.
  5019. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  5020. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  5021. }
  5022. auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  5023. Types.push_back(New);
  5024. AtomicTypes.InsertNode(New, InsertPos);
  5025. return QualType(New, 0);
  5026. }
  5027. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  5028. QualType ASTContext::getAutoDeductType() const {
  5029. if (AutoDeductTy.isNull())
  5030. AutoDeductTy = QualType(new (*this, TypeAlignment)
  5031. AutoType(QualType(), AutoTypeKeyword::Auto,
  5032. TypeDependence::None, QualType(),
  5033. /*concept*/ nullptr, /*args*/ {}),
  5034. 0);
  5035. return AutoDeductTy;
  5036. }
  5037. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  5038. QualType ASTContext::getAutoRRefDeductType() const {
  5039. if (AutoRRefDeductTy.isNull())
  5040. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  5041. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  5042. return AutoRRefDeductTy;
  5043. }
  5044. /// getTagDeclType - Return the unique reference to the type for the
  5045. /// specified TagDecl (struct/union/class/enum) decl.
  5046. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  5047. assert(Decl);
  5048. // FIXME: What is the design on getTagDeclType when it requires casting
  5049. // away const? mutable?
  5050. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  5051. }
  5052. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  5053. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  5054. /// needs to agree with the definition in <stddef.h>.
  5055. CanQualType ASTContext::getSizeType() const {
  5056. return getFromTargetType(Target->getSizeType());
  5057. }
  5058. /// Return the unique signed counterpart of the integer type
  5059. /// corresponding to size_t.
  5060. CanQualType ASTContext::getSignedSizeType() const {
  5061. return getFromTargetType(Target->getSignedSizeType());
  5062. }
  5063. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  5064. CanQualType ASTContext::getIntMaxType() const {
  5065. return getFromTargetType(Target->getIntMaxType());
  5066. }
  5067. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  5068. CanQualType ASTContext::getUIntMaxType() const {
  5069. return getFromTargetType(Target->getUIntMaxType());
  5070. }
  5071. /// getSignedWCharType - Return the type of "signed wchar_t".
  5072. /// Used when in C++, as a GCC extension.
  5073. QualType ASTContext::getSignedWCharType() const {
  5074. // FIXME: derive from "Target" ?
  5075. return WCharTy;
  5076. }
  5077. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  5078. /// Used when in C++, as a GCC extension.
  5079. QualType ASTContext::getUnsignedWCharType() const {
  5080. // FIXME: derive from "Target" ?
  5081. return UnsignedIntTy;
  5082. }
  5083. QualType ASTContext::getIntPtrType() const {
  5084. return getFromTargetType(Target->getIntPtrType());
  5085. }
  5086. QualType ASTContext::getUIntPtrType() const {
  5087. return getCorrespondingUnsignedType(getIntPtrType());
  5088. }
  5089. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  5090. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  5091. QualType ASTContext::getPointerDiffType() const {
  5092. return getFromTargetType(Target->getPtrDiffType(0));
  5093. }
  5094. /// Return the unique unsigned counterpart of "ptrdiff_t"
  5095. /// integer type. The standard (C11 7.21.6.1p7) refers to this type
  5096. /// in the definition of %tu format specifier.
  5097. QualType ASTContext::getUnsignedPointerDiffType() const {
  5098. return getFromTargetType(Target->getUnsignedPtrDiffType(0));
  5099. }
  5100. /// Return the unique type for "pid_t" defined in
  5101. /// <sys/types.h>. We need this to compute the correct type for vfork().
  5102. QualType ASTContext::getProcessIDType() const {
  5103. return getFromTargetType(Target->getProcessIDType());
  5104. }
  5105. //===----------------------------------------------------------------------===//
  5106. // Type Operators
  5107. //===----------------------------------------------------------------------===//
  5108. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  5109. // Push qualifiers into arrays, and then discard any remaining
  5110. // qualifiers.
  5111. T = getCanonicalType(T);
  5112. T = getVariableArrayDecayedType(T);
  5113. const Type *Ty = T.getTypePtr();
  5114. QualType Result;
  5115. if (isa<ArrayType>(Ty)) {
  5116. Result = getArrayDecayedType(QualType(Ty,0));
  5117. } else if (isa<FunctionType>(Ty)) {
  5118. Result = getPointerType(QualType(Ty, 0));
  5119. } else {
  5120. Result = QualType(Ty, 0);
  5121. }
  5122. return CanQualType::CreateUnsafe(Result);
  5123. }
  5124. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  5125. Qualifiers &quals) {
  5126. SplitQualType splitType = type.getSplitUnqualifiedType();
  5127. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  5128. // the unqualified desugared type and then drops it on the floor.
  5129. // We then have to strip that sugar back off with
  5130. // getUnqualifiedDesugaredType(), which is silly.
  5131. const auto *AT =
  5132. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  5133. // If we don't have an array, just use the results in splitType.
  5134. if (!AT) {
  5135. quals = splitType.Quals;
  5136. return QualType(splitType.Ty, 0);
  5137. }
  5138. // Otherwise, recurse on the array's element type.
  5139. QualType elementType = AT->getElementType();
  5140. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  5141. // If that didn't change the element type, AT has no qualifiers, so we
  5142. // can just use the results in splitType.
  5143. if (elementType == unqualElementType) {
  5144. assert(quals.empty()); // from the recursive call
  5145. quals = splitType.Quals;
  5146. return QualType(splitType.Ty, 0);
  5147. }
  5148. // Otherwise, add in the qualifiers from the outermost type, then
  5149. // build the type back up.
  5150. quals.addConsistentQualifiers(splitType.Quals);
  5151. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  5152. return getConstantArrayType(unqualElementType, CAT->getSize(),
  5153. CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
  5154. }
  5155. if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  5156. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  5157. }
  5158. if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
  5159. return getVariableArrayType(unqualElementType,
  5160. VAT->getSizeExpr(),
  5161. VAT->getSizeModifier(),
  5162. VAT->getIndexTypeCVRQualifiers(),
  5163. VAT->getBracketsRange());
  5164. }
  5165. const auto *DSAT = cast<DependentSizedArrayType>(AT);
  5166. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  5167. DSAT->getSizeModifier(), 0,
  5168. SourceRange());
  5169. }
  5170. /// Attempt to unwrap two types that may both be array types with the same bound
  5171. /// (or both be array types of unknown bound) for the purpose of comparing the
  5172. /// cv-decomposition of two types per C++ [conv.qual].
  5173. ///
  5174. /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
  5175. /// C++20 [conv.qual], if permitted by the current language mode.
  5176. void ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
  5177. bool AllowPiMismatch) {
  5178. while (true) {
  5179. auto *AT1 = getAsArrayType(T1);
  5180. if (!AT1)
  5181. return;
  5182. auto *AT2 = getAsArrayType(T2);
  5183. if (!AT2)
  5184. return;
  5185. // If we don't have two array types with the same constant bound nor two
  5186. // incomplete array types, we've unwrapped everything we can.
  5187. // C++20 also permits one type to be a constant array type and the other
  5188. // to be an incomplete array type.
  5189. // FIXME: Consider also unwrapping array of unknown bound and VLA.
  5190. if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
  5191. auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
  5192. if (!((CAT2 && CAT1->getSize() == CAT2->getSize()) ||
  5193. (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
  5194. isa<IncompleteArrayType>(AT2))))
  5195. return;
  5196. } else if (isa<IncompleteArrayType>(AT1)) {
  5197. if (!(isa<IncompleteArrayType>(AT2) ||
  5198. (AllowPiMismatch && getLangOpts().CPlusPlus20 &&
  5199. isa<ConstantArrayType>(AT2))))
  5200. return;
  5201. } else {
  5202. return;
  5203. }
  5204. T1 = AT1->getElementType();
  5205. T2 = AT2->getElementType();
  5206. }
  5207. }
  5208. /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
  5209. ///
  5210. /// If T1 and T2 are both pointer types of the same kind, or both array types
  5211. /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
  5212. /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
  5213. ///
  5214. /// This function will typically be called in a loop that successively
  5215. /// "unwraps" pointer and pointer-to-member types to compare them at each
  5216. /// level.
  5217. ///
  5218. /// \param AllowPiMismatch Allow the Pi1 and Pi2 to differ as described in
  5219. /// C++20 [conv.qual], if permitted by the current language mode.
  5220. ///
  5221. /// \return \c true if a pointer type was unwrapped, \c false if we reached a
  5222. /// pair of types that can't be unwrapped further.
  5223. bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2,
  5224. bool AllowPiMismatch) {
  5225. UnwrapSimilarArrayTypes(T1, T2, AllowPiMismatch);
  5226. const auto *T1PtrType = T1->getAs<PointerType>();
  5227. const auto *T2PtrType = T2->getAs<PointerType>();
  5228. if (T1PtrType && T2PtrType) {
  5229. T1 = T1PtrType->getPointeeType();
  5230. T2 = T2PtrType->getPointeeType();
  5231. return true;
  5232. }
  5233. const auto *T1MPType = T1->getAs<MemberPointerType>();
  5234. const auto *T2MPType = T2->getAs<MemberPointerType>();
  5235. if (T1MPType && T2MPType &&
  5236. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  5237. QualType(T2MPType->getClass(), 0))) {
  5238. T1 = T1MPType->getPointeeType();
  5239. T2 = T2MPType->getPointeeType();
  5240. return true;
  5241. }
  5242. if (getLangOpts().ObjC) {
  5243. const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
  5244. const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
  5245. if (T1OPType && T2OPType) {
  5246. T1 = T1OPType->getPointeeType();
  5247. T2 = T2OPType->getPointeeType();
  5248. return true;
  5249. }
  5250. }
  5251. // FIXME: Block pointers, too?
  5252. return false;
  5253. }
  5254. bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
  5255. while (true) {
  5256. Qualifiers Quals;
  5257. T1 = getUnqualifiedArrayType(T1, Quals);
  5258. T2 = getUnqualifiedArrayType(T2, Quals);
  5259. if (hasSameType(T1, T2))
  5260. return true;
  5261. if (!UnwrapSimilarTypes(T1, T2))
  5262. return false;
  5263. }
  5264. }
  5265. bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
  5266. while (true) {
  5267. Qualifiers Quals1, Quals2;
  5268. T1 = getUnqualifiedArrayType(T1, Quals1);
  5269. T2 = getUnqualifiedArrayType(T2, Quals2);
  5270. Quals1.removeCVRQualifiers();
  5271. Quals2.removeCVRQualifiers();
  5272. if (Quals1 != Quals2)
  5273. return false;
  5274. if (hasSameType(T1, T2))
  5275. return true;
  5276. if (!UnwrapSimilarTypes(T1, T2, /*AllowPiMismatch*/ false))
  5277. return false;
  5278. }
  5279. }
  5280. DeclarationNameInfo
  5281. ASTContext::getNameForTemplate(TemplateName Name,
  5282. SourceLocation NameLoc) const {
  5283. switch (Name.getKind()) {
  5284. case TemplateName::QualifiedTemplate:
  5285. case TemplateName::Template:
  5286. // DNInfo work in progress: CHECKME: what about DNLoc?
  5287. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  5288. NameLoc);
  5289. case TemplateName::OverloadedTemplate: {
  5290. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  5291. // DNInfo work in progress: CHECKME: what about DNLoc?
  5292. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  5293. }
  5294. case TemplateName::AssumedTemplate: {
  5295. AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
  5296. return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
  5297. }
  5298. case TemplateName::DependentTemplate: {
  5299. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  5300. DeclarationName DName;
  5301. if (DTN->isIdentifier()) {
  5302. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  5303. return DeclarationNameInfo(DName, NameLoc);
  5304. } else {
  5305. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  5306. // DNInfo work in progress: FIXME: source locations?
  5307. DeclarationNameLoc DNLoc =
  5308. DeclarationNameLoc::makeCXXOperatorNameLoc(SourceRange());
  5309. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  5310. }
  5311. }
  5312. case TemplateName::SubstTemplateTemplateParm: {
  5313. SubstTemplateTemplateParmStorage *subst
  5314. = Name.getAsSubstTemplateTemplateParm();
  5315. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  5316. NameLoc);
  5317. }
  5318. case TemplateName::SubstTemplateTemplateParmPack: {
  5319. SubstTemplateTemplateParmPackStorage *subst
  5320. = Name.getAsSubstTemplateTemplateParmPack();
  5321. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  5322. NameLoc);
  5323. }
  5324. }
  5325. llvm_unreachable("bad template name kind!");
  5326. }
  5327. TemplateName
  5328. ASTContext::getCanonicalTemplateName(const TemplateName &Name) const {
  5329. switch (Name.getKind()) {
  5330. case TemplateName::QualifiedTemplate:
  5331. case TemplateName::Template: {
  5332. TemplateDecl *Template = Name.getAsTemplateDecl();
  5333. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
  5334. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  5335. // The canonical template name is the canonical template declaration.
  5336. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  5337. }
  5338. case TemplateName::OverloadedTemplate:
  5339. case TemplateName::AssumedTemplate:
  5340. llvm_unreachable("cannot canonicalize unresolved template");
  5341. case TemplateName::DependentTemplate: {
  5342. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  5343. assert(DTN && "Non-dependent template names must refer to template decls.");
  5344. return DTN->CanonicalTemplateName;
  5345. }
  5346. case TemplateName::SubstTemplateTemplateParm: {
  5347. SubstTemplateTemplateParmStorage *subst
  5348. = Name.getAsSubstTemplateTemplateParm();
  5349. return getCanonicalTemplateName(subst->getReplacement());
  5350. }
  5351. case TemplateName::SubstTemplateTemplateParmPack: {
  5352. SubstTemplateTemplateParmPackStorage *subst
  5353. = Name.getAsSubstTemplateTemplateParmPack();
  5354. TemplateTemplateParmDecl *canonParameter
  5355. = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
  5356. TemplateArgument canonArgPack
  5357. = getCanonicalTemplateArgument(subst->getArgumentPack());
  5358. return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
  5359. }
  5360. }
  5361. llvm_unreachable("bad template name!");
  5362. }
  5363. bool ASTContext::hasSameTemplateName(const TemplateName &X,
  5364. const TemplateName &Y) const {
  5365. return getCanonicalTemplateName(X).getAsVoidPointer() ==
  5366. getCanonicalTemplateName(Y).getAsVoidPointer();
  5367. }
  5368. bool ASTContext::isSameTemplateParameter(const NamedDecl *X,
  5369. const NamedDecl *Y) {
  5370. if (X->getKind() != Y->getKind())
  5371. return false;
  5372. if (auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
  5373. auto *TY = cast<TemplateTypeParmDecl>(Y);
  5374. if (TX->isParameterPack() != TY->isParameterPack())
  5375. return false;
  5376. if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
  5377. return false;
  5378. const TypeConstraint *TXTC = TX->getTypeConstraint();
  5379. const TypeConstraint *TYTC = TY->getTypeConstraint();
  5380. if (!TXTC != !TYTC)
  5381. return false;
  5382. if (TXTC && TYTC) {
  5383. auto *NCX = TXTC->getNamedConcept();
  5384. auto *NCY = TYTC->getNamedConcept();
  5385. if (!NCX || !NCY || !isSameEntity(NCX, NCY))
  5386. return false;
  5387. if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
  5388. return false;
  5389. if (TXTC->hasExplicitTemplateArgs()) {
  5390. auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
  5391. auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
  5392. if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
  5393. return false;
  5394. llvm::FoldingSetNodeID XID, YID;
  5395. for (auto &ArgLoc : TXTCArgs->arguments())
  5396. ArgLoc.getArgument().Profile(XID, X->getASTContext());
  5397. for (auto &ArgLoc : TYTCArgs->arguments())
  5398. ArgLoc.getArgument().Profile(YID, Y->getASTContext());
  5399. if (XID != YID)
  5400. return false;
  5401. }
  5402. }
  5403. return true;
  5404. }
  5405. if (auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
  5406. auto *TY = cast<NonTypeTemplateParmDecl>(Y);
  5407. return TX->isParameterPack() == TY->isParameterPack() &&
  5408. TX->getASTContext().hasSameType(TX->getType(), TY->getType());
  5409. }
  5410. auto *TX = cast<TemplateTemplateParmDecl>(X);
  5411. auto *TY = cast<TemplateTemplateParmDecl>(Y);
  5412. return TX->isParameterPack() == TY->isParameterPack() &&
  5413. isSameTemplateParameterList(TX->getTemplateParameters(),
  5414. TY->getTemplateParameters());
  5415. }
  5416. bool ASTContext::isSameTemplateParameterList(const TemplateParameterList *X,
  5417. const TemplateParameterList *Y) {
  5418. if (X->size() != Y->size())
  5419. return false;
  5420. for (unsigned I = 0, N = X->size(); I != N; ++I)
  5421. if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
  5422. return false;
  5423. const Expr *XRC = X->getRequiresClause();
  5424. const Expr *YRC = Y->getRequiresClause();
  5425. if (!XRC != !YRC)
  5426. return false;
  5427. if (XRC) {
  5428. llvm::FoldingSetNodeID XRCID, YRCID;
  5429. XRC->Profile(XRCID, *this, /*Canonical=*/true);
  5430. YRC->Profile(YRCID, *this, /*Canonical=*/true);
  5431. if (XRCID != YRCID)
  5432. return false;
  5433. }
  5434. return true;
  5435. }
  5436. static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
  5437. if (auto *NS = X->getAsNamespace())
  5438. return NS;
  5439. if (auto *NAS = X->getAsNamespaceAlias())
  5440. return NAS->getNamespace();
  5441. return nullptr;
  5442. }
  5443. static bool isSameQualifier(const NestedNameSpecifier *X,
  5444. const NestedNameSpecifier *Y) {
  5445. if (auto *NSX = getNamespace(X)) {
  5446. auto *NSY = getNamespace(Y);
  5447. if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
  5448. return false;
  5449. } else if (X->getKind() != Y->getKind())
  5450. return false;
  5451. // FIXME: For namespaces and types, we're permitted to check that the entity
  5452. // is named via the same tokens. We should probably do so.
  5453. switch (X->getKind()) {
  5454. case NestedNameSpecifier::Identifier:
  5455. if (X->getAsIdentifier() != Y->getAsIdentifier())
  5456. return false;
  5457. break;
  5458. case NestedNameSpecifier::Namespace:
  5459. case NestedNameSpecifier::NamespaceAlias:
  5460. // We've already checked that we named the same namespace.
  5461. break;
  5462. case NestedNameSpecifier::TypeSpec:
  5463. case NestedNameSpecifier::TypeSpecWithTemplate:
  5464. if (X->getAsType()->getCanonicalTypeInternal() !=
  5465. Y->getAsType()->getCanonicalTypeInternal())
  5466. return false;
  5467. break;
  5468. case NestedNameSpecifier::Global:
  5469. case NestedNameSpecifier::Super:
  5470. return true;
  5471. }
  5472. // Recurse into earlier portion of NNS, if any.
  5473. auto *PX = X->getPrefix();
  5474. auto *PY = Y->getPrefix();
  5475. if (PX && PY)
  5476. return isSameQualifier(PX, PY);
  5477. return !PX && !PY;
  5478. }
  5479. /// Determine whether the attributes we can overload on are identical for A and
  5480. /// B. Will ignore any overloadable attrs represented in the type of A and B.
  5481. static bool hasSameOverloadableAttrs(const FunctionDecl *A,
  5482. const FunctionDecl *B) {
  5483. // Note that pass_object_size attributes are represented in the function's
  5484. // ExtParameterInfo, so we don't need to check them here.
  5485. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  5486. auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
  5487. auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
  5488. for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
  5489. Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
  5490. Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
  5491. // Return false if the number of enable_if attributes is different.
  5492. if (!Cand1A || !Cand2A)
  5493. return false;
  5494. Cand1ID.clear();
  5495. Cand2ID.clear();
  5496. (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
  5497. (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
  5498. // Return false if any of the enable_if expressions of A and B are
  5499. // different.
  5500. if (Cand1ID != Cand2ID)
  5501. return false;
  5502. }
  5503. return true;
  5504. }
  5505. bool ASTContext::isSameEntity(const NamedDecl *X, const NamedDecl *Y) {
  5506. if (X == Y)
  5507. return true;
  5508. if (X->getDeclName() != Y->getDeclName())
  5509. return false;
  5510. // Must be in the same context.
  5511. //
  5512. // Note that we can't use DeclContext::Equals here, because the DeclContexts
  5513. // could be two different declarations of the same function. (We will fix the
  5514. // semantic DC to refer to the primary definition after merging.)
  5515. if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
  5516. cast<Decl>(Y->getDeclContext()->getRedeclContext())))
  5517. return false;
  5518. // Two typedefs refer to the same entity if they have the same underlying
  5519. // type.
  5520. if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
  5521. if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
  5522. return hasSameType(TypedefX->getUnderlyingType(),
  5523. TypedefY->getUnderlyingType());
  5524. // Must have the same kind.
  5525. if (X->getKind() != Y->getKind())
  5526. return false;
  5527. // Objective-C classes and protocols with the same name always match.
  5528. if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
  5529. return true;
  5530. if (isa<ClassTemplateSpecializationDecl>(X)) {
  5531. // No need to handle these here: we merge them when adding them to the
  5532. // template.
  5533. return false;
  5534. }
  5535. // Compatible tags match.
  5536. if (const auto *TagX = dyn_cast<TagDecl>(X)) {
  5537. const auto *TagY = cast<TagDecl>(Y);
  5538. return (TagX->getTagKind() == TagY->getTagKind()) ||
  5539. ((TagX->getTagKind() == TTK_Struct ||
  5540. TagX->getTagKind() == TTK_Class ||
  5541. TagX->getTagKind() == TTK_Interface) &&
  5542. (TagY->getTagKind() == TTK_Struct ||
  5543. TagY->getTagKind() == TTK_Class ||
  5544. TagY->getTagKind() == TTK_Interface));
  5545. }
  5546. // Functions with the same type and linkage match.
  5547. // FIXME: This needs to cope with merging of prototyped/non-prototyped
  5548. // functions, etc.
  5549. if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
  5550. const auto *FuncY = cast<FunctionDecl>(Y);
  5551. if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
  5552. const auto *CtorY = cast<CXXConstructorDecl>(Y);
  5553. if (CtorX->getInheritedConstructor() &&
  5554. !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
  5555. CtorY->getInheritedConstructor().getConstructor()))
  5556. return false;
  5557. }
  5558. if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
  5559. return false;
  5560. // Multiversioned functions with different feature strings are represented
  5561. // as separate declarations.
  5562. if (FuncX->isMultiVersion()) {
  5563. const auto *TAX = FuncX->getAttr<TargetAttr>();
  5564. const auto *TAY = FuncY->getAttr<TargetAttr>();
  5565. assert(TAX && TAY && "Multiversion Function without target attribute");
  5566. if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
  5567. return false;
  5568. }
  5569. const Expr *XRC = FuncX->getTrailingRequiresClause();
  5570. const Expr *YRC = FuncY->getTrailingRequiresClause();
  5571. if (!XRC != !YRC)
  5572. return false;
  5573. if (XRC) {
  5574. llvm::FoldingSetNodeID XRCID, YRCID;
  5575. XRC->Profile(XRCID, *this, /*Canonical=*/true);
  5576. YRC->Profile(YRCID, *this, /*Canonical=*/true);
  5577. if (XRCID != YRCID)
  5578. return false;
  5579. }
  5580. auto GetTypeAsWritten = [](const FunctionDecl *FD) {
  5581. // Map to the first declaration that we've already merged into this one.
  5582. // The TSI of redeclarations might not match (due to calling conventions
  5583. // being inherited onto the type but not the TSI), but the TSI type of
  5584. // the first declaration of the function should match across modules.
  5585. FD = FD->getCanonicalDecl();
  5586. return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
  5587. : FD->getType();
  5588. };
  5589. QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
  5590. if (!hasSameType(XT, YT)) {
  5591. // We can get functions with different types on the redecl chain in C++17
  5592. // if they have differing exception specifications and at least one of
  5593. // the excpetion specs is unresolved.
  5594. auto *XFPT = XT->getAs<FunctionProtoType>();
  5595. auto *YFPT = YT->getAs<FunctionProtoType>();
  5596. if (getLangOpts().CPlusPlus17 && XFPT && YFPT &&
  5597. (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
  5598. isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
  5599. // FIXME: We could make isSameEntity const after we make
  5600. // hasSameFunctionTypeIgnoringExceptionSpec const.
  5601. hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
  5602. return true;
  5603. return false;
  5604. }
  5605. return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
  5606. hasSameOverloadableAttrs(FuncX, FuncY);
  5607. }
  5608. // Variables with the same type and linkage match.
  5609. if (const auto *VarX = dyn_cast<VarDecl>(X)) {
  5610. const auto *VarY = cast<VarDecl>(Y);
  5611. if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
  5612. if (hasSameType(VarX->getType(), VarY->getType()))
  5613. return true;
  5614. // We can get decls with different types on the redecl chain. Eg.
  5615. // template <typename T> struct S { static T Var[]; }; // #1
  5616. // template <typename T> T S<T>::Var[sizeof(T)]; // #2
  5617. // Only? happens when completing an incomplete array type. In this case
  5618. // when comparing #1 and #2 we should go through their element type.
  5619. const ArrayType *VarXTy = getAsArrayType(VarX->getType());
  5620. const ArrayType *VarYTy = getAsArrayType(VarY->getType());
  5621. if (!VarXTy || !VarYTy)
  5622. return false;
  5623. if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
  5624. return hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
  5625. }
  5626. return false;
  5627. }
  5628. // Namespaces with the same name and inlinedness match.
  5629. if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
  5630. const auto *NamespaceY = cast<NamespaceDecl>(Y);
  5631. return NamespaceX->isInline() == NamespaceY->isInline();
  5632. }
  5633. // Identical template names and kinds match if their template parameter lists
  5634. // and patterns match.
  5635. if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
  5636. const auto *TemplateY = cast<TemplateDecl>(Y);
  5637. return isSameEntity(TemplateX->getTemplatedDecl(),
  5638. TemplateY->getTemplatedDecl()) &&
  5639. isSameTemplateParameterList(TemplateX->getTemplateParameters(),
  5640. TemplateY->getTemplateParameters());
  5641. }
  5642. // Fields with the same name and the same type match.
  5643. if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
  5644. const auto *FDY = cast<FieldDecl>(Y);
  5645. // FIXME: Also check the bitwidth is odr-equivalent, if any.
  5646. return hasSameType(FDX->getType(), FDY->getType());
  5647. }
  5648. // Indirect fields with the same target field match.
  5649. if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
  5650. const auto *IFDY = cast<IndirectFieldDecl>(Y);
  5651. return IFDX->getAnonField()->getCanonicalDecl() ==
  5652. IFDY->getAnonField()->getCanonicalDecl();
  5653. }
  5654. // Enumerators with the same name match.
  5655. if (isa<EnumConstantDecl>(X))
  5656. // FIXME: Also check the value is odr-equivalent.
  5657. return true;
  5658. // Using shadow declarations with the same target match.
  5659. if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
  5660. const auto *USY = cast<UsingShadowDecl>(Y);
  5661. return USX->getTargetDecl() == USY->getTargetDecl();
  5662. }
  5663. // Using declarations with the same qualifier match. (We already know that
  5664. // the name matches.)
  5665. if (const auto *UX = dyn_cast<UsingDecl>(X)) {
  5666. const auto *UY = cast<UsingDecl>(Y);
  5667. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  5668. UX->hasTypename() == UY->hasTypename() &&
  5669. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  5670. }
  5671. if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
  5672. const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
  5673. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  5674. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  5675. }
  5676. if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
  5677. return isSameQualifier(
  5678. UX->getQualifier(),
  5679. cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
  5680. }
  5681. // Using-pack declarations are only created by instantiation, and match if
  5682. // they're instantiated from matching UnresolvedUsing...Decls.
  5683. if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
  5684. return declaresSameEntity(
  5685. UX->getInstantiatedFromUsingDecl(),
  5686. cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
  5687. }
  5688. // Namespace alias definitions with the same target match.
  5689. if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
  5690. const auto *NAY = cast<NamespaceAliasDecl>(Y);
  5691. return NAX->getNamespace()->Equals(NAY->getNamespace());
  5692. }
  5693. return false;
  5694. }
  5695. TemplateArgument
  5696. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  5697. switch (Arg.getKind()) {
  5698. case TemplateArgument::Null:
  5699. return Arg;
  5700. case TemplateArgument::Expression:
  5701. return Arg;
  5702. case TemplateArgument::Declaration: {
  5703. auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  5704. return TemplateArgument(D, Arg.getParamTypeForDecl());
  5705. }
  5706. case TemplateArgument::NullPtr:
  5707. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  5708. /*isNullPtr*/true);
  5709. case TemplateArgument::Template:
  5710. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  5711. case TemplateArgument::TemplateExpansion:
  5712. return TemplateArgument(getCanonicalTemplateName(
  5713. Arg.getAsTemplateOrTemplatePattern()),
  5714. Arg.getNumTemplateExpansions());
  5715. case TemplateArgument::Integral:
  5716. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  5717. case TemplateArgument::Type:
  5718. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  5719. case TemplateArgument::Pack: {
  5720. if (Arg.pack_size() == 0)
  5721. return Arg;
  5722. auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
  5723. unsigned Idx = 0;
  5724. for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
  5725. AEnd = Arg.pack_end();
  5726. A != AEnd; (void)++A, ++Idx)
  5727. CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
  5728. return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
  5729. }
  5730. }
  5731. // Silence GCC warning
  5732. llvm_unreachable("Unhandled template argument kind");
  5733. }
  5734. NestedNameSpecifier *
  5735. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  5736. if (!NNS)
  5737. return nullptr;
  5738. switch (NNS->getKind()) {
  5739. case NestedNameSpecifier::Identifier:
  5740. // Canonicalize the prefix but keep the identifier the same.
  5741. return NestedNameSpecifier::Create(*this,
  5742. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  5743. NNS->getAsIdentifier());
  5744. case NestedNameSpecifier::Namespace:
  5745. // A namespace is canonical; build a nested-name-specifier with
  5746. // this namespace and no prefix.
  5747. return NestedNameSpecifier::Create(*this, nullptr,
  5748. NNS->getAsNamespace()->getOriginalNamespace());
  5749. case NestedNameSpecifier::NamespaceAlias:
  5750. // A namespace is canonical; build a nested-name-specifier with
  5751. // this namespace and no prefix.
  5752. return NestedNameSpecifier::Create(*this, nullptr,
  5753. NNS->getAsNamespaceAlias()->getNamespace()
  5754. ->getOriginalNamespace());
  5755. // The difference between TypeSpec and TypeSpecWithTemplate is that the
  5756. // latter will have the 'template' keyword when printed.
  5757. case NestedNameSpecifier::TypeSpec:
  5758. case NestedNameSpecifier::TypeSpecWithTemplate: {
  5759. const Type *T = getCanonicalType(NNS->getAsType());
  5760. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  5761. // break it apart into its prefix and identifier, then reconsititute those
  5762. // as the canonical nested-name-specifier. This is required to canonicalize
  5763. // a dependent nested-name-specifier involving typedefs of dependent-name
  5764. // types, e.g.,
  5765. // typedef typename T::type T1;
  5766. // typedef typename T1::type T2;
  5767. if (const auto *DNT = T->getAs<DependentNameType>())
  5768. return NestedNameSpecifier::Create(
  5769. *this, DNT->getQualifier(),
  5770. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  5771. if (const auto *DTST = T->getAs<DependentTemplateSpecializationType>())
  5772. return NestedNameSpecifier::Create(*this, DTST->getQualifier(), true,
  5773. const_cast<Type *>(T));
  5774. // TODO: Set 'Template' parameter to true for other template types.
  5775. return NestedNameSpecifier::Create(*this, nullptr, false,
  5776. const_cast<Type *>(T));
  5777. }
  5778. case NestedNameSpecifier::Global:
  5779. case NestedNameSpecifier::Super:
  5780. // The global specifier and __super specifer are canonical and unique.
  5781. return NNS;
  5782. }
  5783. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  5784. }
  5785. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  5786. // Handle the non-qualified case efficiently.
  5787. if (!T.hasLocalQualifiers()) {
  5788. // Handle the common positive case fast.
  5789. if (const auto *AT = dyn_cast<ArrayType>(T))
  5790. return AT;
  5791. }
  5792. // Handle the common negative case fast.
  5793. if (!isa<ArrayType>(T.getCanonicalType()))
  5794. return nullptr;
  5795. // Apply any qualifiers from the array type to the element type. This
  5796. // implements C99 6.7.3p8: "If the specification of an array type includes
  5797. // any type qualifiers, the element type is so qualified, not the array type."
  5798. // If we get here, we either have type qualifiers on the type, or we have
  5799. // sugar such as a typedef in the way. If we have type qualifiers on the type
  5800. // we must propagate them down into the element type.
  5801. SplitQualType split = T.getSplitDesugaredType();
  5802. Qualifiers qs = split.Quals;
  5803. // If we have a simple case, just return now.
  5804. const auto *ATy = dyn_cast<ArrayType>(split.Ty);
  5805. if (!ATy || qs.empty())
  5806. return ATy;
  5807. // Otherwise, we have an array and we have qualifiers on it. Push the
  5808. // qualifiers into the array element type and return a new array type.
  5809. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  5810. if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
  5811. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  5812. CAT->getSizeExpr(),
  5813. CAT->getSizeModifier(),
  5814. CAT->getIndexTypeCVRQualifiers()));
  5815. if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
  5816. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  5817. IAT->getSizeModifier(),
  5818. IAT->getIndexTypeCVRQualifiers()));
  5819. if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
  5820. return cast<ArrayType>(
  5821. getDependentSizedArrayType(NewEltTy,
  5822. DSAT->getSizeExpr(),
  5823. DSAT->getSizeModifier(),
  5824. DSAT->getIndexTypeCVRQualifiers(),
  5825. DSAT->getBracketsRange()));
  5826. const auto *VAT = cast<VariableArrayType>(ATy);
  5827. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  5828. VAT->getSizeExpr(),
  5829. VAT->getSizeModifier(),
  5830. VAT->getIndexTypeCVRQualifiers(),
  5831. VAT->getBracketsRange()));
  5832. }
  5833. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  5834. if (T->isArrayType() || T->isFunctionType())
  5835. return getDecayedType(T);
  5836. return T;
  5837. }
  5838. QualType ASTContext::getSignatureParameterType(QualType T) const {
  5839. T = getVariableArrayDecayedType(T);
  5840. T = getAdjustedParameterType(T);
  5841. return T.getUnqualifiedType();
  5842. }
  5843. QualType ASTContext::getExceptionObjectType(QualType T) const {
  5844. // C++ [except.throw]p3:
  5845. // A throw-expression initializes a temporary object, called the exception
  5846. // object, the type of which is determined by removing any top-level
  5847. // cv-qualifiers from the static type of the operand of throw and adjusting
  5848. // the type from "array of T" or "function returning T" to "pointer to T"
  5849. // or "pointer to function returning T", [...]
  5850. T = getVariableArrayDecayedType(T);
  5851. if (T->isArrayType() || T->isFunctionType())
  5852. T = getDecayedType(T);
  5853. return T.getUnqualifiedType();
  5854. }
  5855. /// getArrayDecayedType - Return the properly qualified result of decaying the
  5856. /// specified array type to a pointer. This operation is non-trivial when
  5857. /// handling typedefs etc. The canonical type of "T" must be an array type,
  5858. /// this returns a pointer to a properly qualified element of the array.
  5859. ///
  5860. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  5861. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  5862. // Get the element type with 'getAsArrayType' so that we don't lose any
  5863. // typedefs in the element type of the array. This also handles propagation
  5864. // of type qualifiers from the array type into the element type if present
  5865. // (C99 6.7.3p8).
  5866. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  5867. assert(PrettyArrayType && "Not an array type!");
  5868. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  5869. // int x[restrict 4] -> int *restrict
  5870. QualType Result = getQualifiedType(PtrTy,
  5871. PrettyArrayType->getIndexTypeQualifiers());
  5872. // int x[_Nullable] -> int * _Nullable
  5873. if (auto Nullability = Ty->getNullability(*this)) {
  5874. Result = const_cast<ASTContext *>(this)->getAttributedType(
  5875. AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
  5876. }
  5877. return Result;
  5878. }
  5879. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  5880. return getBaseElementType(array->getElementType());
  5881. }
  5882. QualType ASTContext::getBaseElementType(QualType type) const {
  5883. Qualifiers qs;
  5884. while (true) {
  5885. SplitQualType split = type.getSplitDesugaredType();
  5886. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  5887. if (!array) break;
  5888. type = array->getElementType();
  5889. qs.addConsistentQualifiers(split.Quals);
  5890. }
  5891. return getQualifiedType(type, qs);
  5892. }
  5893. /// getConstantArrayElementCount - Returns number of constant array elements.
  5894. uint64_t
  5895. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  5896. uint64_t ElementCount = 1;
  5897. do {
  5898. ElementCount *= CA->getSize().getZExtValue();
  5899. CA = dyn_cast_or_null<ConstantArrayType>(
  5900. CA->getElementType()->getAsArrayTypeUnsafe());
  5901. } while (CA);
  5902. return ElementCount;
  5903. }
  5904. /// getFloatingRank - Return a relative rank for floating point types.
  5905. /// This routine will assert if passed a built-in type that isn't a float.
  5906. static FloatingRank getFloatingRank(QualType T) {
  5907. if (const auto *CT = T->getAs<ComplexType>())
  5908. return getFloatingRank(CT->getElementType());
  5909. switch (T->castAs<BuiltinType>()->getKind()) {
  5910. default: llvm_unreachable("getFloatingRank(): not a floating type");
  5911. case BuiltinType::Float16: return Float16Rank;
  5912. case BuiltinType::Half: return HalfRank;
  5913. case BuiltinType::Float: return FloatRank;
  5914. case BuiltinType::Double: return DoubleRank;
  5915. case BuiltinType::LongDouble: return LongDoubleRank;
  5916. case BuiltinType::Float128: return Float128Rank;
  5917. case BuiltinType::BFloat16: return BFloat16Rank;
  5918. case BuiltinType::Ibm128: return Ibm128Rank;
  5919. }
  5920. }
  5921. /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
  5922. /// point or a complex type (based on typeDomain/typeSize).
  5923. /// 'typeDomain' is a real floating point or complex type.
  5924. /// 'typeSize' is a real floating point or complex type.
  5925. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
  5926. QualType Domain) const {
  5927. FloatingRank EltRank = getFloatingRank(Size);
  5928. if (Domain->isComplexType()) {
  5929. switch (EltRank) {
  5930. case BFloat16Rank: llvm_unreachable("Complex bfloat16 is not supported");
  5931. case Float16Rank:
  5932. case HalfRank: llvm_unreachable("Complex half is not supported");
  5933. case Ibm128Rank: return getComplexType(Ibm128Ty);
  5934. case FloatRank: return getComplexType(FloatTy);
  5935. case DoubleRank: return getComplexType(DoubleTy);
  5936. case LongDoubleRank: return getComplexType(LongDoubleTy);
  5937. case Float128Rank: return getComplexType(Float128Ty);
  5938. }
  5939. }
  5940. assert(Domain->isRealFloatingType() && "Unknown domain!");
  5941. switch (EltRank) {
  5942. case Float16Rank: return HalfTy;
  5943. case BFloat16Rank: return BFloat16Ty;
  5944. case HalfRank: return HalfTy;
  5945. case FloatRank: return FloatTy;
  5946. case DoubleRank: return DoubleTy;
  5947. case LongDoubleRank: return LongDoubleTy;
  5948. case Float128Rank: return Float128Ty;
  5949. case Ibm128Rank:
  5950. return Ibm128Ty;
  5951. }
  5952. llvm_unreachable("getFloatingRank(): illegal value for rank");
  5953. }
  5954. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  5955. /// point types, ignoring the domain of the type (i.e. 'double' ==
  5956. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  5957. /// LHS < RHS, return -1.
  5958. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  5959. FloatingRank LHSR = getFloatingRank(LHS);
  5960. FloatingRank RHSR = getFloatingRank(RHS);
  5961. if (LHSR == RHSR)
  5962. return 0;
  5963. if (LHSR > RHSR)
  5964. return 1;
  5965. return -1;
  5966. }
  5967. int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
  5968. if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
  5969. return 0;
  5970. return getFloatingTypeOrder(LHS, RHS);
  5971. }
  5972. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  5973. /// routine will assert if passed a built-in type that isn't an integer or enum,
  5974. /// or if it is not canonicalized.
  5975. unsigned ASTContext::getIntegerRank(const Type *T) const {
  5976. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  5977. // Results in this 'losing' to any type of the same size, but winning if
  5978. // larger.
  5979. if (const auto *EIT = dyn_cast<BitIntType>(T))
  5980. return 0 + (EIT->getNumBits() << 3);
  5981. switch (cast<BuiltinType>(T)->getKind()) {
  5982. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  5983. case BuiltinType::Bool:
  5984. return 1 + (getIntWidth(BoolTy) << 3);
  5985. case BuiltinType::Char_S:
  5986. case BuiltinType::Char_U:
  5987. case BuiltinType::SChar:
  5988. case BuiltinType::UChar:
  5989. return 2 + (getIntWidth(CharTy) << 3);
  5990. case BuiltinType::Short:
  5991. case BuiltinType::UShort:
  5992. return 3 + (getIntWidth(ShortTy) << 3);
  5993. case BuiltinType::Int:
  5994. case BuiltinType::UInt:
  5995. return 4 + (getIntWidth(IntTy) << 3);
  5996. case BuiltinType::Long:
  5997. case BuiltinType::ULong:
  5998. return 5 + (getIntWidth(LongTy) << 3);
  5999. case BuiltinType::LongLong:
  6000. case BuiltinType::ULongLong:
  6001. return 6 + (getIntWidth(LongLongTy) << 3);
  6002. case BuiltinType::Int128:
  6003. case BuiltinType::UInt128:
  6004. return 7 + (getIntWidth(Int128Ty) << 3);
  6005. }
  6006. }
  6007. /// Whether this is a promotable bitfield reference according
  6008. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  6009. ///
  6010. /// \returns the type this bit-field will promote to, or NULL if no
  6011. /// promotion occurs.
  6012. QualType ASTContext::isPromotableBitField(Expr *E) const {
  6013. if (E->isTypeDependent() || E->isValueDependent())
  6014. return {};
  6015. // C++ [conv.prom]p5:
  6016. // If the bit-field has an enumerated type, it is treated as any other
  6017. // value of that type for promotion purposes.
  6018. if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
  6019. return {};
  6020. // FIXME: We should not do this unless E->refersToBitField() is true. This
  6021. // matters in C where getSourceBitField() will find bit-fields for various
  6022. // cases where the source expression is not a bit-field designator.
  6023. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  6024. if (!Field)
  6025. return {};
  6026. QualType FT = Field->getType();
  6027. uint64_t BitWidth = Field->getBitWidthValue(*this);
  6028. uint64_t IntSize = getTypeSize(IntTy);
  6029. // C++ [conv.prom]p5:
  6030. // A prvalue for an integral bit-field can be converted to a prvalue of type
  6031. // int if int can represent all the values of the bit-field; otherwise, it
  6032. // can be converted to unsigned int if unsigned int can represent all the
  6033. // values of the bit-field. If the bit-field is larger yet, no integral
  6034. // promotion applies to it.
  6035. // C11 6.3.1.1/2:
  6036. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  6037. // If an int can represent all values of the original type (as restricted by
  6038. // the width, for a bit-field), the value is converted to an int; otherwise,
  6039. // it is converted to an unsigned int.
  6040. //
  6041. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  6042. // We perform that promotion here to match GCC and C++.
  6043. // FIXME: C does not permit promotion of an enum bit-field whose rank is
  6044. // greater than that of 'int'. We perform that promotion to match GCC.
  6045. if (BitWidth < IntSize)
  6046. return IntTy;
  6047. if (BitWidth == IntSize)
  6048. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  6049. // Bit-fields wider than int are not subject to promotions, and therefore act
  6050. // like the base type. GCC has some weird bugs in this area that we
  6051. // deliberately do not follow (GCC follows a pre-standard resolution to
  6052. // C's DR315 which treats bit-width as being part of the type, and this leaks
  6053. // into their semantics in some cases).
  6054. return {};
  6055. }
  6056. /// getPromotedIntegerType - Returns the type that Promotable will
  6057. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  6058. /// integer type.
  6059. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  6060. assert(!Promotable.isNull());
  6061. assert(Promotable->isPromotableIntegerType());
  6062. if (const auto *ET = Promotable->getAs<EnumType>())
  6063. return ET->getDecl()->getPromotionType();
  6064. if (const auto *BT = Promotable->getAs<BuiltinType>()) {
  6065. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  6066. // (3.9.1) can be converted to a prvalue of the first of the following
  6067. // types that can represent all the values of its underlying type:
  6068. // int, unsigned int, long int, unsigned long int, long long int, or
  6069. // unsigned long long int [...]
  6070. // FIXME: Is there some better way to compute this?
  6071. if (BT->getKind() == BuiltinType::WChar_S ||
  6072. BT->getKind() == BuiltinType::WChar_U ||
  6073. BT->getKind() == BuiltinType::Char8 ||
  6074. BT->getKind() == BuiltinType::Char16 ||
  6075. BT->getKind() == BuiltinType::Char32) {
  6076. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  6077. uint64_t FromSize = getTypeSize(BT);
  6078. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  6079. LongLongTy, UnsignedLongLongTy };
  6080. for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
  6081. uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
  6082. if (FromSize < ToSize ||
  6083. (FromSize == ToSize &&
  6084. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
  6085. return PromoteTypes[Idx];
  6086. }
  6087. llvm_unreachable("char type should fit into long long");
  6088. }
  6089. }
  6090. // At this point, we should have a signed or unsigned integer type.
  6091. if (Promotable->isSignedIntegerType())
  6092. return IntTy;
  6093. uint64_t PromotableSize = getIntWidth(Promotable);
  6094. uint64_t IntSize = getIntWidth(IntTy);
  6095. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  6096. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  6097. }
  6098. /// Recurses in pointer/array types until it finds an objc retainable
  6099. /// type and returns its ownership.
  6100. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  6101. while (!T.isNull()) {
  6102. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  6103. return T.getObjCLifetime();
  6104. if (T->isArrayType())
  6105. T = getBaseElementType(T);
  6106. else if (const auto *PT = T->getAs<PointerType>())
  6107. T = PT->getPointeeType();
  6108. else if (const auto *RT = T->getAs<ReferenceType>())
  6109. T = RT->getPointeeType();
  6110. else
  6111. break;
  6112. }
  6113. return Qualifiers::OCL_None;
  6114. }
  6115. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  6116. // Incomplete enum types are not treated as integer types.
  6117. // FIXME: In C++, enum types are never integer types.
  6118. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  6119. return ET->getDecl()->getIntegerType().getTypePtr();
  6120. return nullptr;
  6121. }
  6122. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  6123. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  6124. /// LHS < RHS, return -1.
  6125. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  6126. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  6127. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  6128. // Unwrap enums to their underlying type.
  6129. if (const auto *ET = dyn_cast<EnumType>(LHSC))
  6130. LHSC = getIntegerTypeForEnum(ET);
  6131. if (const auto *ET = dyn_cast<EnumType>(RHSC))
  6132. RHSC = getIntegerTypeForEnum(ET);
  6133. if (LHSC == RHSC) return 0;
  6134. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  6135. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  6136. unsigned LHSRank = getIntegerRank(LHSC);
  6137. unsigned RHSRank = getIntegerRank(RHSC);
  6138. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  6139. if (LHSRank == RHSRank) return 0;
  6140. return LHSRank > RHSRank ? 1 : -1;
  6141. }
  6142. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  6143. if (LHSUnsigned) {
  6144. // If the unsigned [LHS] type is larger, return it.
  6145. if (LHSRank >= RHSRank)
  6146. return 1;
  6147. // If the signed type can represent all values of the unsigned type, it
  6148. // wins. Because we are dealing with 2's complement and types that are
  6149. // powers of two larger than each other, this is always safe.
  6150. return -1;
  6151. }
  6152. // If the unsigned [RHS] type is larger, return it.
  6153. if (RHSRank >= LHSRank)
  6154. return -1;
  6155. // If the signed type can represent all values of the unsigned type, it
  6156. // wins. Because we are dealing with 2's complement and types that are
  6157. // powers of two larger than each other, this is always safe.
  6158. return 1;
  6159. }
  6160. TypedefDecl *ASTContext::getCFConstantStringDecl() const {
  6161. if (CFConstantStringTypeDecl)
  6162. return CFConstantStringTypeDecl;
  6163. assert(!CFConstantStringTagDecl &&
  6164. "tag and typedef should be initialized together");
  6165. CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
  6166. CFConstantStringTagDecl->startDefinition();
  6167. struct {
  6168. QualType Type;
  6169. const char *Name;
  6170. } Fields[5];
  6171. unsigned Count = 0;
  6172. /// Objective-C ABI
  6173. ///
  6174. /// typedef struct __NSConstantString_tag {
  6175. /// const int *isa;
  6176. /// int flags;
  6177. /// const char *str;
  6178. /// long length;
  6179. /// } __NSConstantString;
  6180. ///
  6181. /// Swift ABI (4.1, 4.2)
  6182. ///
  6183. /// typedef struct __NSConstantString_tag {
  6184. /// uintptr_t _cfisa;
  6185. /// uintptr_t _swift_rc;
  6186. /// _Atomic(uint64_t) _cfinfoa;
  6187. /// const char *_ptr;
  6188. /// uint32_t _length;
  6189. /// } __NSConstantString;
  6190. ///
  6191. /// Swift ABI (5.0)
  6192. ///
  6193. /// typedef struct __NSConstantString_tag {
  6194. /// uintptr_t _cfisa;
  6195. /// uintptr_t _swift_rc;
  6196. /// _Atomic(uint64_t) _cfinfoa;
  6197. /// const char *_ptr;
  6198. /// uintptr_t _length;
  6199. /// } __NSConstantString;
  6200. const auto CFRuntime = getLangOpts().CFRuntime;
  6201. if (static_cast<unsigned>(CFRuntime) <
  6202. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
  6203. Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
  6204. Fields[Count++] = { IntTy, "flags" };
  6205. Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
  6206. Fields[Count++] = { LongTy, "length" };
  6207. } else {
  6208. Fields[Count++] = { getUIntPtrType(), "_cfisa" };
  6209. Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
  6210. Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
  6211. Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
  6212. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  6213. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  6214. Fields[Count++] = { IntTy, "_ptr" };
  6215. else
  6216. Fields[Count++] = { getUIntPtrType(), "_ptr" };
  6217. }
  6218. // Create fields
  6219. for (unsigned i = 0; i < Count; ++i) {
  6220. FieldDecl *Field =
  6221. FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
  6222. SourceLocation(), &Idents.get(Fields[i].Name),
  6223. Fields[i].Type, /*TInfo=*/nullptr,
  6224. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  6225. Field->setAccess(AS_public);
  6226. CFConstantStringTagDecl->addDecl(Field);
  6227. }
  6228. CFConstantStringTagDecl->completeDefinition();
  6229. // This type is designed to be compatible with NSConstantString, but cannot
  6230. // use the same name, since NSConstantString is an interface.
  6231. auto tagType = getTagDeclType(CFConstantStringTagDecl);
  6232. CFConstantStringTypeDecl =
  6233. buildImplicitTypedef(tagType, "__NSConstantString");
  6234. return CFConstantStringTypeDecl;
  6235. }
  6236. RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
  6237. if (!CFConstantStringTagDecl)
  6238. getCFConstantStringDecl(); // Build the tag and the typedef.
  6239. return CFConstantStringTagDecl;
  6240. }
  6241. // getCFConstantStringType - Return the type used for constant CFStrings.
  6242. QualType ASTContext::getCFConstantStringType() const {
  6243. return getTypedefType(getCFConstantStringDecl());
  6244. }
  6245. QualType ASTContext::getObjCSuperType() const {
  6246. if (ObjCSuperType.isNull()) {
  6247. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  6248. getTranslationUnitDecl()->addDecl(ObjCSuperTypeDecl);
  6249. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  6250. }
  6251. return ObjCSuperType;
  6252. }
  6253. void ASTContext::setCFConstantStringType(QualType T) {
  6254. const auto *TD = T->castAs<TypedefType>();
  6255. CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
  6256. const auto *TagType =
  6257. CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
  6258. CFConstantStringTagDecl = TagType->getDecl();
  6259. }
  6260. QualType ASTContext::getBlockDescriptorType() const {
  6261. if (BlockDescriptorType)
  6262. return getTagDeclType(BlockDescriptorType);
  6263. RecordDecl *RD;
  6264. // FIXME: Needs the FlagAppleBlock bit.
  6265. RD = buildImplicitRecord("__block_descriptor");
  6266. RD->startDefinition();
  6267. QualType FieldTypes[] = {
  6268. UnsignedLongTy,
  6269. UnsignedLongTy,
  6270. };
  6271. static const char *const FieldNames[] = {
  6272. "reserved",
  6273. "Size"
  6274. };
  6275. for (size_t i = 0; i < 2; ++i) {
  6276. FieldDecl *Field = FieldDecl::Create(
  6277. *this, RD, SourceLocation(), SourceLocation(),
  6278. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  6279. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  6280. Field->setAccess(AS_public);
  6281. RD->addDecl(Field);
  6282. }
  6283. RD->completeDefinition();
  6284. BlockDescriptorType = RD;
  6285. return getTagDeclType(BlockDescriptorType);
  6286. }
  6287. QualType ASTContext::getBlockDescriptorExtendedType() const {
  6288. if (BlockDescriptorExtendedType)
  6289. return getTagDeclType(BlockDescriptorExtendedType);
  6290. RecordDecl *RD;
  6291. // FIXME: Needs the FlagAppleBlock bit.
  6292. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  6293. RD->startDefinition();
  6294. QualType FieldTypes[] = {
  6295. UnsignedLongTy,
  6296. UnsignedLongTy,
  6297. getPointerType(VoidPtrTy),
  6298. getPointerType(VoidPtrTy)
  6299. };
  6300. static const char *const FieldNames[] = {
  6301. "reserved",
  6302. "Size",
  6303. "CopyFuncPtr",
  6304. "DestroyFuncPtr"
  6305. };
  6306. for (size_t i = 0; i < 4; ++i) {
  6307. FieldDecl *Field = FieldDecl::Create(
  6308. *this, RD, SourceLocation(), SourceLocation(),
  6309. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  6310. /*BitWidth=*/nullptr,
  6311. /*Mutable=*/false, ICIS_NoInit);
  6312. Field->setAccess(AS_public);
  6313. RD->addDecl(Field);
  6314. }
  6315. RD->completeDefinition();
  6316. BlockDescriptorExtendedType = RD;
  6317. return getTagDeclType(BlockDescriptorExtendedType);
  6318. }
  6319. OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
  6320. const auto *BT = dyn_cast<BuiltinType>(T);
  6321. if (!BT) {
  6322. if (isa<PipeType>(T))
  6323. return OCLTK_Pipe;
  6324. return OCLTK_Default;
  6325. }
  6326. switch (BT->getKind()) {
  6327. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6328. case BuiltinType::Id: \
  6329. return OCLTK_Image;
  6330. #include "clang/Basic/OpenCLImageTypes.def"
  6331. case BuiltinType::OCLClkEvent:
  6332. return OCLTK_ClkEvent;
  6333. case BuiltinType::OCLEvent:
  6334. return OCLTK_Event;
  6335. case BuiltinType::OCLQueue:
  6336. return OCLTK_Queue;
  6337. case BuiltinType::OCLReserveID:
  6338. return OCLTK_ReserveID;
  6339. case BuiltinType::OCLSampler:
  6340. return OCLTK_Sampler;
  6341. default:
  6342. return OCLTK_Default;
  6343. }
  6344. }
  6345. LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
  6346. return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
  6347. }
  6348. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  6349. /// requires copy/dispose. Note that this must match the logic
  6350. /// in buildByrefHelpers.
  6351. bool ASTContext::BlockRequiresCopying(QualType Ty,
  6352. const VarDecl *D) {
  6353. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  6354. const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
  6355. if (!copyExpr && record->hasTrivialDestructor()) return false;
  6356. return true;
  6357. }
  6358. // The block needs copy/destroy helpers if Ty is non-trivial to destructively
  6359. // move or destroy.
  6360. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
  6361. return true;
  6362. if (!Ty->isObjCRetainableType()) return false;
  6363. Qualifiers qs = Ty.getQualifiers();
  6364. // If we have lifetime, that dominates.
  6365. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  6366. switch (lifetime) {
  6367. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  6368. // These are just bits as far as the runtime is concerned.
  6369. case Qualifiers::OCL_ExplicitNone:
  6370. case Qualifiers::OCL_Autoreleasing:
  6371. return false;
  6372. // These cases should have been taken care of when checking the type's
  6373. // non-triviality.
  6374. case Qualifiers::OCL_Weak:
  6375. case Qualifiers::OCL_Strong:
  6376. llvm_unreachable("impossible");
  6377. }
  6378. llvm_unreachable("fell out of lifetime switch!");
  6379. }
  6380. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  6381. Ty->isObjCObjectPointerType());
  6382. }
  6383. bool ASTContext::getByrefLifetime(QualType Ty,
  6384. Qualifiers::ObjCLifetime &LifeTime,
  6385. bool &HasByrefExtendedLayout) const {
  6386. if (!getLangOpts().ObjC ||
  6387. getLangOpts().getGC() != LangOptions::NonGC)
  6388. return false;
  6389. HasByrefExtendedLayout = false;
  6390. if (Ty->isRecordType()) {
  6391. HasByrefExtendedLayout = true;
  6392. LifeTime = Qualifiers::OCL_None;
  6393. } else if ((LifeTime = Ty.getObjCLifetime())) {
  6394. // Honor the ARC qualifiers.
  6395. } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
  6396. // The MRR rule.
  6397. LifeTime = Qualifiers::OCL_ExplicitNone;
  6398. } else {
  6399. LifeTime = Qualifiers::OCL_None;
  6400. }
  6401. return true;
  6402. }
  6403. CanQualType ASTContext::getNSUIntegerType() const {
  6404. assert(Target && "Expected target to be initialized");
  6405. const llvm::Triple &T = Target->getTriple();
  6406. // Windows is LLP64 rather than LP64
  6407. if (T.isOSWindows() && T.isArch64Bit())
  6408. return UnsignedLongLongTy;
  6409. return UnsignedLongTy;
  6410. }
  6411. CanQualType ASTContext::getNSIntegerType() const {
  6412. assert(Target && "Expected target to be initialized");
  6413. const llvm::Triple &T = Target->getTriple();
  6414. // Windows is LLP64 rather than LP64
  6415. if (T.isOSWindows() && T.isArch64Bit())
  6416. return LongLongTy;
  6417. return LongTy;
  6418. }
  6419. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  6420. if (!ObjCInstanceTypeDecl)
  6421. ObjCInstanceTypeDecl =
  6422. buildImplicitTypedef(getObjCIdType(), "instancetype");
  6423. return ObjCInstanceTypeDecl;
  6424. }
  6425. // This returns true if a type has been typedefed to BOOL:
  6426. // typedef <type> BOOL;
  6427. static bool isTypeTypedefedAsBOOL(QualType T) {
  6428. if (const auto *TT = dyn_cast<TypedefType>(T))
  6429. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  6430. return II->isStr("BOOL");
  6431. return false;
  6432. }
  6433. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  6434. /// purpose.
  6435. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  6436. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  6437. return CharUnits::Zero();
  6438. CharUnits sz = getTypeSizeInChars(type);
  6439. // Make all integer and enum types at least as large as an int
  6440. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  6441. sz = std::max(sz, getTypeSizeInChars(IntTy));
  6442. // Treat arrays as pointers, since that's how they're passed in.
  6443. else if (type->isArrayType())
  6444. sz = getTypeSizeInChars(VoidPtrTy);
  6445. return sz;
  6446. }
  6447. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  6448. return getTargetInfo().getCXXABI().isMicrosoft() &&
  6449. VD->isStaticDataMember() &&
  6450. VD->getType()->isIntegralOrEnumerationType() &&
  6451. !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
  6452. }
  6453. ASTContext::InlineVariableDefinitionKind
  6454. ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
  6455. if (!VD->isInline())
  6456. return InlineVariableDefinitionKind::None;
  6457. // In almost all cases, it's a weak definition.
  6458. auto *First = VD->getFirstDecl();
  6459. if (First->isInlineSpecified() || !First->isStaticDataMember())
  6460. return InlineVariableDefinitionKind::Weak;
  6461. // If there's a file-context declaration in this translation unit, it's a
  6462. // non-discardable definition.
  6463. for (auto *D : VD->redecls())
  6464. if (D->getLexicalDeclContext()->isFileContext() &&
  6465. !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
  6466. return InlineVariableDefinitionKind::Strong;
  6467. // If we've not seen one yet, we don't know.
  6468. return InlineVariableDefinitionKind::WeakUnknown;
  6469. }
  6470. static std::string charUnitsToString(const CharUnits &CU) {
  6471. return llvm::itostr(CU.getQuantity());
  6472. }
  6473. /// getObjCEncodingForBlock - Return the encoded type for this block
  6474. /// declaration.
  6475. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  6476. std::string S;
  6477. const BlockDecl *Decl = Expr->getBlockDecl();
  6478. QualType BlockTy =
  6479. Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
  6480. QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
  6481. // Encode result type.
  6482. if (getLangOpts().EncodeExtendedBlockSig)
  6483. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
  6484. true /*Extended*/);
  6485. else
  6486. getObjCEncodingForType(BlockReturnTy, S);
  6487. // Compute size of all parameters.
  6488. // Start with computing size of a pointer in number of bytes.
  6489. // FIXME: There might(should) be a better way of doing this computation!
  6490. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  6491. CharUnits ParmOffset = PtrSize;
  6492. for (auto PI : Decl->parameters()) {
  6493. QualType PType = PI->getType();
  6494. CharUnits sz = getObjCEncodingTypeSize(PType);
  6495. if (sz.isZero())
  6496. continue;
  6497. assert(sz.isPositive() && "BlockExpr - Incomplete param type");
  6498. ParmOffset += sz;
  6499. }
  6500. // Size of the argument frame
  6501. S += charUnitsToString(ParmOffset);
  6502. // Block pointer and offset.
  6503. S += "@?0";
  6504. // Argument types.
  6505. ParmOffset = PtrSize;
  6506. for (auto PVDecl : Decl->parameters()) {
  6507. QualType PType = PVDecl->getOriginalType();
  6508. if (const auto *AT =
  6509. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6510. // Use array's original type only if it has known number of
  6511. // elements.
  6512. if (!isa<ConstantArrayType>(AT))
  6513. PType = PVDecl->getType();
  6514. } else if (PType->isFunctionType())
  6515. PType = PVDecl->getType();
  6516. if (getLangOpts().EncodeExtendedBlockSig)
  6517. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  6518. S, true /*Extended*/);
  6519. else
  6520. getObjCEncodingForType(PType, S);
  6521. S += charUnitsToString(ParmOffset);
  6522. ParmOffset += getObjCEncodingTypeSize(PType);
  6523. }
  6524. return S;
  6525. }
  6526. std::string
  6527. ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
  6528. std::string S;
  6529. // Encode result type.
  6530. getObjCEncodingForType(Decl->getReturnType(), S);
  6531. CharUnits ParmOffset;
  6532. // Compute size of all parameters.
  6533. for (auto PI : Decl->parameters()) {
  6534. QualType PType = PI->getType();
  6535. CharUnits sz = getObjCEncodingTypeSize(PType);
  6536. if (sz.isZero())
  6537. continue;
  6538. assert(sz.isPositive() &&
  6539. "getObjCEncodingForFunctionDecl - Incomplete param type");
  6540. ParmOffset += sz;
  6541. }
  6542. S += charUnitsToString(ParmOffset);
  6543. ParmOffset = CharUnits::Zero();
  6544. // Argument types.
  6545. for (auto PVDecl : Decl->parameters()) {
  6546. QualType PType = PVDecl->getOriginalType();
  6547. if (const auto *AT =
  6548. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6549. // Use array's original type only if it has known number of
  6550. // elements.
  6551. if (!isa<ConstantArrayType>(AT))
  6552. PType = PVDecl->getType();
  6553. } else if (PType->isFunctionType())
  6554. PType = PVDecl->getType();
  6555. getObjCEncodingForType(PType, S);
  6556. S += charUnitsToString(ParmOffset);
  6557. ParmOffset += getObjCEncodingTypeSize(PType);
  6558. }
  6559. return S;
  6560. }
  6561. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  6562. /// method parameter or return type. If Extended, include class names and
  6563. /// block object types.
  6564. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  6565. QualType T, std::string& S,
  6566. bool Extended) const {
  6567. // Encode type qualifier, 'in', 'inout', etc. for the parameter.
  6568. getObjCEncodingForTypeQualifier(QT, S);
  6569. // Encode parameter type.
  6570. ObjCEncOptions Options = ObjCEncOptions()
  6571. .setExpandPointedToStructures()
  6572. .setExpandStructures()
  6573. .setIsOutermostType();
  6574. if (Extended)
  6575. Options.setEncodeBlockParameters().setEncodeClassNames();
  6576. getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
  6577. }
  6578. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  6579. /// declaration.
  6580. std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  6581. bool Extended) const {
  6582. // FIXME: This is not very efficient.
  6583. // Encode return type.
  6584. std::string S;
  6585. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  6586. Decl->getReturnType(), S, Extended);
  6587. // Compute size of all parameters.
  6588. // Start with computing size of a pointer in number of bytes.
  6589. // FIXME: There might(should) be a better way of doing this computation!
  6590. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  6591. // The first two arguments (self and _cmd) are pointers; account for
  6592. // their size.
  6593. CharUnits ParmOffset = 2 * PtrSize;
  6594. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  6595. E = Decl->sel_param_end(); PI != E; ++PI) {
  6596. QualType PType = (*PI)->getType();
  6597. CharUnits sz = getObjCEncodingTypeSize(PType);
  6598. if (sz.isZero())
  6599. continue;
  6600. assert(sz.isPositive() &&
  6601. "getObjCEncodingForMethodDecl - Incomplete param type");
  6602. ParmOffset += sz;
  6603. }
  6604. S += charUnitsToString(ParmOffset);
  6605. S += "@0:";
  6606. S += charUnitsToString(PtrSize);
  6607. // Argument types.
  6608. ParmOffset = 2 * PtrSize;
  6609. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  6610. E = Decl->sel_param_end(); PI != E; ++PI) {
  6611. const ParmVarDecl *PVDecl = *PI;
  6612. QualType PType = PVDecl->getOriginalType();
  6613. if (const auto *AT =
  6614. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  6615. // Use array's original type only if it has known number of
  6616. // elements.
  6617. if (!isa<ConstantArrayType>(AT))
  6618. PType = PVDecl->getType();
  6619. } else if (PType->isFunctionType())
  6620. PType = PVDecl->getType();
  6621. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  6622. PType, S, Extended);
  6623. S += charUnitsToString(ParmOffset);
  6624. ParmOffset += getObjCEncodingTypeSize(PType);
  6625. }
  6626. return S;
  6627. }
  6628. ObjCPropertyImplDecl *
  6629. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  6630. const ObjCPropertyDecl *PD,
  6631. const Decl *Container) const {
  6632. if (!Container)
  6633. return nullptr;
  6634. if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
  6635. for (auto *PID : CID->property_impls())
  6636. if (PID->getPropertyDecl() == PD)
  6637. return PID;
  6638. } else {
  6639. const auto *OID = cast<ObjCImplementationDecl>(Container);
  6640. for (auto *PID : OID->property_impls())
  6641. if (PID->getPropertyDecl() == PD)
  6642. return PID;
  6643. }
  6644. return nullptr;
  6645. }
  6646. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  6647. /// property declaration. If non-NULL, Container must be either an
  6648. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  6649. /// NULL when getting encodings for protocol properties.
  6650. /// Property attributes are stored as a comma-delimited C string. The simple
  6651. /// attributes readonly and bycopy are encoded as single characters. The
  6652. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  6653. /// encoded as single characters, followed by an identifier. Property types
  6654. /// are also encoded as a parametrized attribute. The characters used to encode
  6655. /// these attributes are defined by the following enumeration:
  6656. /// @code
  6657. /// enum PropertyAttributes {
  6658. /// kPropertyReadOnly = 'R', // property is read-only.
  6659. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  6660. /// kPropertyByref = '&', // property is a reference to the value last assigned
  6661. /// kPropertyDynamic = 'D', // property is dynamic
  6662. /// kPropertyGetter = 'G', // followed by getter selector name
  6663. /// kPropertySetter = 'S', // followed by setter selector name
  6664. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  6665. /// kPropertyType = 'T' // followed by old-style type encoding.
  6666. /// kPropertyWeak = 'W' // 'weak' property
  6667. /// kPropertyStrong = 'P' // property GC'able
  6668. /// kPropertyNonAtomic = 'N' // property non-atomic
  6669. /// };
  6670. /// @endcode
  6671. std::string
  6672. ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  6673. const Decl *Container) const {
  6674. // Collect information from the property implementation decl(s).
  6675. bool Dynamic = false;
  6676. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  6677. if (ObjCPropertyImplDecl *PropertyImpDecl =
  6678. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  6679. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  6680. Dynamic = true;
  6681. else
  6682. SynthesizePID = PropertyImpDecl;
  6683. }
  6684. // FIXME: This is not very efficient.
  6685. std::string S = "T";
  6686. // Encode result type.
  6687. // GCC has some special rules regarding encoding of properties which
  6688. // closely resembles encoding of ivars.
  6689. getObjCEncodingForPropertyType(PD->getType(), S);
  6690. if (PD->isReadOnly()) {
  6691. S += ",R";
  6692. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy)
  6693. S += ",C";
  6694. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain)
  6695. S += ",&";
  6696. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak)
  6697. S += ",W";
  6698. } else {
  6699. switch (PD->getSetterKind()) {
  6700. case ObjCPropertyDecl::Assign: break;
  6701. case ObjCPropertyDecl::Copy: S += ",C"; break;
  6702. case ObjCPropertyDecl::Retain: S += ",&"; break;
  6703. case ObjCPropertyDecl::Weak: S += ",W"; break;
  6704. }
  6705. }
  6706. // It really isn't clear at all what this means, since properties
  6707. // are "dynamic by default".
  6708. if (Dynamic)
  6709. S += ",D";
  6710. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_nonatomic)
  6711. S += ",N";
  6712. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
  6713. S += ",G";
  6714. S += PD->getGetterName().getAsString();
  6715. }
  6716. if (PD->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
  6717. S += ",S";
  6718. S += PD->getSetterName().getAsString();
  6719. }
  6720. if (SynthesizePID) {
  6721. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  6722. S += ",V";
  6723. S += OID->getNameAsString();
  6724. }
  6725. // FIXME: OBJCGC: weak & strong
  6726. return S;
  6727. }
  6728. /// getLegacyIntegralTypeEncoding -
  6729. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  6730. /// 'l' or 'L' , but not always. For typedefs, we need to use
  6731. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  6732. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  6733. if (isa<TypedefType>(PointeeTy.getTypePtr())) {
  6734. if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
  6735. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  6736. PointeeTy = UnsignedIntTy;
  6737. else
  6738. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  6739. PointeeTy = IntTy;
  6740. }
  6741. }
  6742. }
  6743. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  6744. const FieldDecl *Field,
  6745. QualType *NotEncodedT) const {
  6746. // We follow the behavior of gcc, expanding structures which are
  6747. // directly pointed to, and expanding embedded structures. Note that
  6748. // these rules are sufficient to prevent recursive encoding of the
  6749. // same type.
  6750. getObjCEncodingForTypeImpl(T, S,
  6751. ObjCEncOptions()
  6752. .setExpandPointedToStructures()
  6753. .setExpandStructures()
  6754. .setIsOutermostType(),
  6755. Field, NotEncodedT);
  6756. }
  6757. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  6758. std::string& S) const {
  6759. // Encode result type.
  6760. // GCC has some special rules regarding encoding of properties which
  6761. // closely resembles encoding of ivars.
  6762. getObjCEncodingForTypeImpl(T, S,
  6763. ObjCEncOptions()
  6764. .setExpandPointedToStructures()
  6765. .setExpandStructures()
  6766. .setIsOutermostType()
  6767. .setEncodingProperty(),
  6768. /*Field=*/nullptr);
  6769. }
  6770. static char getObjCEncodingForPrimitiveType(const ASTContext *C,
  6771. const BuiltinType *BT) {
  6772. BuiltinType::Kind kind = BT->getKind();
  6773. switch (kind) {
  6774. case BuiltinType::Void: return 'v';
  6775. case BuiltinType::Bool: return 'B';
  6776. case BuiltinType::Char8:
  6777. case BuiltinType::Char_U:
  6778. case BuiltinType::UChar: return 'C';
  6779. case BuiltinType::Char16:
  6780. case BuiltinType::UShort: return 'S';
  6781. case BuiltinType::Char32:
  6782. case BuiltinType::UInt: return 'I';
  6783. case BuiltinType::ULong:
  6784. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  6785. case BuiltinType::UInt128: return 'T';
  6786. case BuiltinType::ULongLong: return 'Q';
  6787. case BuiltinType::Char_S:
  6788. case BuiltinType::SChar: return 'c';
  6789. case BuiltinType::Short: return 's';
  6790. case BuiltinType::WChar_S:
  6791. case BuiltinType::WChar_U:
  6792. case BuiltinType::Int: return 'i';
  6793. case BuiltinType::Long:
  6794. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  6795. case BuiltinType::LongLong: return 'q';
  6796. case BuiltinType::Int128: return 't';
  6797. case BuiltinType::Float: return 'f';
  6798. case BuiltinType::Double: return 'd';
  6799. case BuiltinType::LongDouble: return 'D';
  6800. case BuiltinType::NullPtr: return '*'; // like char*
  6801. case BuiltinType::BFloat16:
  6802. case BuiltinType::Float16:
  6803. case BuiltinType::Float128:
  6804. case BuiltinType::Ibm128:
  6805. case BuiltinType::Half:
  6806. case BuiltinType::ShortAccum:
  6807. case BuiltinType::Accum:
  6808. case BuiltinType::LongAccum:
  6809. case BuiltinType::UShortAccum:
  6810. case BuiltinType::UAccum:
  6811. case BuiltinType::ULongAccum:
  6812. case BuiltinType::ShortFract:
  6813. case BuiltinType::Fract:
  6814. case BuiltinType::LongFract:
  6815. case BuiltinType::UShortFract:
  6816. case BuiltinType::UFract:
  6817. case BuiltinType::ULongFract:
  6818. case BuiltinType::SatShortAccum:
  6819. case BuiltinType::SatAccum:
  6820. case BuiltinType::SatLongAccum:
  6821. case BuiltinType::SatUShortAccum:
  6822. case BuiltinType::SatUAccum:
  6823. case BuiltinType::SatULongAccum:
  6824. case BuiltinType::SatShortFract:
  6825. case BuiltinType::SatFract:
  6826. case BuiltinType::SatLongFract:
  6827. case BuiltinType::SatUShortFract:
  6828. case BuiltinType::SatUFract:
  6829. case BuiltinType::SatULongFract:
  6830. // FIXME: potentially need @encodes for these!
  6831. return ' ';
  6832. #define SVE_TYPE(Name, Id, SingletonId) \
  6833. case BuiltinType::Id:
  6834. #include "clang/Basic/AArch64SVEACLETypes.def"
  6835. #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
  6836. #include "clang/Basic/RISCVVTypes.def"
  6837. {
  6838. DiagnosticsEngine &Diags = C->getDiagnostics();
  6839. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  6840. "cannot yet @encode type %0");
  6841. Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
  6842. return ' ';
  6843. }
  6844. case BuiltinType::ObjCId:
  6845. case BuiltinType::ObjCClass:
  6846. case BuiltinType::ObjCSel:
  6847. llvm_unreachable("@encoding ObjC primitive type");
  6848. // OpenCL and placeholder types don't need @encodings.
  6849. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6850. case BuiltinType::Id:
  6851. #include "clang/Basic/OpenCLImageTypes.def"
  6852. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  6853. case BuiltinType::Id:
  6854. #include "clang/Basic/OpenCLExtensionTypes.def"
  6855. case BuiltinType::OCLEvent:
  6856. case BuiltinType::OCLClkEvent:
  6857. case BuiltinType::OCLQueue:
  6858. case BuiltinType::OCLReserveID:
  6859. case BuiltinType::OCLSampler:
  6860. case BuiltinType::Dependent:
  6861. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  6862. case BuiltinType::Id:
  6863. #include "clang/Basic/PPCTypes.def"
  6864. #define BUILTIN_TYPE(KIND, ID)
  6865. #define PLACEHOLDER_TYPE(KIND, ID) \
  6866. case BuiltinType::KIND:
  6867. #include "clang/AST/BuiltinTypes.def"
  6868. llvm_unreachable("invalid builtin type for @encode");
  6869. }
  6870. llvm_unreachable("invalid BuiltinType::Kind value");
  6871. }
  6872. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  6873. EnumDecl *Enum = ET->getDecl();
  6874. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  6875. if (!Enum->isFixed())
  6876. return 'i';
  6877. // The encoding of a fixed enum type matches its fixed underlying type.
  6878. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  6879. return getObjCEncodingForPrimitiveType(C, BT);
  6880. }
  6881. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  6882. QualType T, const FieldDecl *FD) {
  6883. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  6884. S += 'b';
  6885. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  6886. // The GNU runtime requires more information; bitfields are encoded as b,
  6887. // then the offset (in bits) of the first element, then the type of the
  6888. // bitfield, then the size in bits. For example, in this structure:
  6889. //
  6890. // struct
  6891. // {
  6892. // int integer;
  6893. // int flags:2;
  6894. // };
  6895. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  6896. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  6897. // information is not especially sensible, but we're stuck with it for
  6898. // compatibility with GCC, although providing it breaks anything that
  6899. // actually uses runtime introspection and wants to work on both runtimes...
  6900. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  6901. uint64_t Offset;
  6902. if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
  6903. Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
  6904. IVD);
  6905. } else {
  6906. const RecordDecl *RD = FD->getParent();
  6907. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  6908. Offset = RL.getFieldOffset(FD->getFieldIndex());
  6909. }
  6910. S += llvm::utostr(Offset);
  6911. if (const auto *ET = T->getAs<EnumType>())
  6912. S += ObjCEncodingForEnumType(Ctx, ET);
  6913. else {
  6914. const auto *BT = T->castAs<BuiltinType>();
  6915. S += getObjCEncodingForPrimitiveType(Ctx, BT);
  6916. }
  6917. }
  6918. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  6919. }
  6920. // Helper function for determining whether the encoded type string would include
  6921. // a template specialization type.
  6922. static bool hasTemplateSpecializationInEncodedString(const Type *T,
  6923. bool VisitBasesAndFields) {
  6924. T = T->getBaseElementTypeUnsafe();
  6925. if (auto *PT = T->getAs<PointerType>())
  6926. return hasTemplateSpecializationInEncodedString(
  6927. PT->getPointeeType().getTypePtr(), false);
  6928. auto *CXXRD = T->getAsCXXRecordDecl();
  6929. if (!CXXRD)
  6930. return false;
  6931. if (isa<ClassTemplateSpecializationDecl>(CXXRD))
  6932. return true;
  6933. if (!CXXRD->hasDefinition() || !VisitBasesAndFields)
  6934. return false;
  6935. for (auto B : CXXRD->bases())
  6936. if (hasTemplateSpecializationInEncodedString(B.getType().getTypePtr(),
  6937. true))
  6938. return true;
  6939. for (auto *FD : CXXRD->fields())
  6940. if (hasTemplateSpecializationInEncodedString(FD->getType().getTypePtr(),
  6941. true))
  6942. return true;
  6943. return false;
  6944. }
  6945. // FIXME: Use SmallString for accumulating string.
  6946. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
  6947. const ObjCEncOptions Options,
  6948. const FieldDecl *FD,
  6949. QualType *NotEncodedT) const {
  6950. CanQualType CT = getCanonicalType(T);
  6951. switch (CT->getTypeClass()) {
  6952. case Type::Builtin:
  6953. case Type::Enum:
  6954. if (FD && FD->isBitField())
  6955. return EncodeBitField(this, S, T, FD);
  6956. if (const auto *BT = dyn_cast<BuiltinType>(CT))
  6957. S += getObjCEncodingForPrimitiveType(this, BT);
  6958. else
  6959. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  6960. return;
  6961. case Type::Complex:
  6962. S += 'j';
  6963. getObjCEncodingForTypeImpl(T->castAs<ComplexType>()->getElementType(), S,
  6964. ObjCEncOptions(),
  6965. /*Field=*/nullptr);
  6966. return;
  6967. case Type::Atomic:
  6968. S += 'A';
  6969. getObjCEncodingForTypeImpl(T->castAs<AtomicType>()->getValueType(), S,
  6970. ObjCEncOptions(),
  6971. /*Field=*/nullptr);
  6972. return;
  6973. // encoding for pointer or reference types.
  6974. case Type::Pointer:
  6975. case Type::LValueReference:
  6976. case Type::RValueReference: {
  6977. QualType PointeeTy;
  6978. if (isa<PointerType>(CT)) {
  6979. const auto *PT = T->castAs<PointerType>();
  6980. if (PT->isObjCSelType()) {
  6981. S += ':';
  6982. return;
  6983. }
  6984. PointeeTy = PT->getPointeeType();
  6985. } else {
  6986. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  6987. }
  6988. bool isReadOnly = false;
  6989. // For historical/compatibility reasons, the read-only qualifier of the
  6990. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  6991. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  6992. // Also, do not emit the 'r' for anything but the outermost type!
  6993. if (isa<TypedefType>(T.getTypePtr())) {
  6994. if (Options.IsOutermostType() && T.isConstQualified()) {
  6995. isReadOnly = true;
  6996. S += 'r';
  6997. }
  6998. } else if (Options.IsOutermostType()) {
  6999. QualType P = PointeeTy;
  7000. while (auto PT = P->getAs<PointerType>())
  7001. P = PT->getPointeeType();
  7002. if (P.isConstQualified()) {
  7003. isReadOnly = true;
  7004. S += 'r';
  7005. }
  7006. }
  7007. if (isReadOnly) {
  7008. // Another legacy compatibility encoding. Some ObjC qualifier and type
  7009. // combinations need to be rearranged.
  7010. // Rewrite "in const" from "nr" to "rn"
  7011. if (StringRef(S).endswith("nr"))
  7012. S.replace(S.end()-2, S.end(), "rn");
  7013. }
  7014. if (PointeeTy->isCharType()) {
  7015. // char pointer types should be encoded as '*' unless it is a
  7016. // type that has been typedef'd to 'BOOL'.
  7017. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  7018. S += '*';
  7019. return;
  7020. }
  7021. } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
  7022. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  7023. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  7024. S += '#';
  7025. return;
  7026. }
  7027. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  7028. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  7029. S += '@';
  7030. return;
  7031. }
  7032. // If the encoded string for the class includes template names, just emit
  7033. // "^v" for pointers to the class.
  7034. if (getLangOpts().CPlusPlus &&
  7035. (!getLangOpts().EncodeCXXClassTemplateSpec &&
  7036. hasTemplateSpecializationInEncodedString(
  7037. RTy, Options.ExpandPointedToStructures()))) {
  7038. S += "^v";
  7039. return;
  7040. }
  7041. // fall through...
  7042. }
  7043. S += '^';
  7044. getLegacyIntegralTypeEncoding(PointeeTy);
  7045. ObjCEncOptions NewOptions;
  7046. if (Options.ExpandPointedToStructures())
  7047. NewOptions.setExpandStructures();
  7048. getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
  7049. /*Field=*/nullptr, NotEncodedT);
  7050. return;
  7051. }
  7052. case Type::ConstantArray:
  7053. case Type::IncompleteArray:
  7054. case Type::VariableArray: {
  7055. const auto *AT = cast<ArrayType>(CT);
  7056. if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
  7057. // Incomplete arrays are encoded as a pointer to the array element.
  7058. S += '^';
  7059. getObjCEncodingForTypeImpl(
  7060. AT->getElementType(), S,
  7061. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
  7062. } else {
  7063. S += '[';
  7064. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  7065. S += llvm::utostr(CAT->getSize().getZExtValue());
  7066. else {
  7067. //Variable length arrays are encoded as a regular array with 0 elements.
  7068. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  7069. "Unknown array type!");
  7070. S += '0';
  7071. }
  7072. getObjCEncodingForTypeImpl(
  7073. AT->getElementType(), S,
  7074. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
  7075. NotEncodedT);
  7076. S += ']';
  7077. }
  7078. return;
  7079. }
  7080. case Type::FunctionNoProto:
  7081. case Type::FunctionProto:
  7082. S += '?';
  7083. return;
  7084. case Type::Record: {
  7085. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  7086. S += RDecl->isUnion() ? '(' : '{';
  7087. // Anonymous structures print as '?'
  7088. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  7089. S += II->getName();
  7090. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  7091. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  7092. llvm::raw_string_ostream OS(S);
  7093. printTemplateArgumentList(OS, TemplateArgs.asArray(),
  7094. getPrintingPolicy());
  7095. }
  7096. } else {
  7097. S += '?';
  7098. }
  7099. if (Options.ExpandStructures()) {
  7100. S += '=';
  7101. if (!RDecl->isUnion()) {
  7102. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  7103. } else {
  7104. for (const auto *Field : RDecl->fields()) {
  7105. if (FD) {
  7106. S += '"';
  7107. S += Field->getNameAsString();
  7108. S += '"';
  7109. }
  7110. // Special case bit-fields.
  7111. if (Field->isBitField()) {
  7112. getObjCEncodingForTypeImpl(Field->getType(), S,
  7113. ObjCEncOptions().setExpandStructures(),
  7114. Field);
  7115. } else {
  7116. QualType qt = Field->getType();
  7117. getLegacyIntegralTypeEncoding(qt);
  7118. getObjCEncodingForTypeImpl(
  7119. qt, S,
  7120. ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
  7121. NotEncodedT);
  7122. }
  7123. }
  7124. }
  7125. }
  7126. S += RDecl->isUnion() ? ')' : '}';
  7127. return;
  7128. }
  7129. case Type::BlockPointer: {
  7130. const auto *BT = T->castAs<BlockPointerType>();
  7131. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  7132. if (Options.EncodeBlockParameters()) {
  7133. const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
  7134. S += '<';
  7135. // Block return type
  7136. getObjCEncodingForTypeImpl(FT->getReturnType(), S,
  7137. Options.forComponentType(), FD, NotEncodedT);
  7138. // Block self
  7139. S += "@?";
  7140. // Block parameters
  7141. if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
  7142. for (const auto &I : FPT->param_types())
  7143. getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
  7144. NotEncodedT);
  7145. }
  7146. S += '>';
  7147. }
  7148. return;
  7149. }
  7150. case Type::ObjCObject: {
  7151. // hack to match legacy encoding of *id and *Class
  7152. QualType Ty = getObjCObjectPointerType(CT);
  7153. if (Ty->isObjCIdType()) {
  7154. S += "{objc_object=}";
  7155. return;
  7156. }
  7157. else if (Ty->isObjCClassType()) {
  7158. S += "{objc_class=}";
  7159. return;
  7160. }
  7161. // TODO: Double check to make sure this intentionally falls through.
  7162. LLVM_FALLTHROUGH;
  7163. }
  7164. case Type::ObjCInterface: {
  7165. // Ignore protocol qualifiers when mangling at this level.
  7166. // @encode(class_name)
  7167. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  7168. S += '{';
  7169. S += OI->getObjCRuntimeNameAsString();
  7170. if (Options.ExpandStructures()) {
  7171. S += '=';
  7172. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  7173. DeepCollectObjCIvars(OI, true, Ivars);
  7174. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  7175. const FieldDecl *Field = Ivars[i];
  7176. if (Field->isBitField())
  7177. getObjCEncodingForTypeImpl(Field->getType(), S,
  7178. ObjCEncOptions().setExpandStructures(),
  7179. Field);
  7180. else
  7181. getObjCEncodingForTypeImpl(Field->getType(), S,
  7182. ObjCEncOptions().setExpandStructures(), FD,
  7183. NotEncodedT);
  7184. }
  7185. }
  7186. S += '}';
  7187. return;
  7188. }
  7189. case Type::ObjCObjectPointer: {
  7190. const auto *OPT = T->castAs<ObjCObjectPointerType>();
  7191. if (OPT->isObjCIdType()) {
  7192. S += '@';
  7193. return;
  7194. }
  7195. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  7196. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  7197. // Since this is a binary compatibility issue, need to consult with
  7198. // runtime folks. Fortunately, this is a *very* obscure construct.
  7199. S += '#';
  7200. return;
  7201. }
  7202. if (OPT->isObjCQualifiedIdType()) {
  7203. getObjCEncodingForTypeImpl(
  7204. getObjCIdType(), S,
  7205. Options.keepingOnly(ObjCEncOptions()
  7206. .setExpandPointedToStructures()
  7207. .setExpandStructures()),
  7208. FD);
  7209. if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
  7210. // Note that we do extended encoding of protocol qualifier list
  7211. // Only when doing ivar or property encoding.
  7212. S += '"';
  7213. for (const auto *I : OPT->quals()) {
  7214. S += '<';
  7215. S += I->getObjCRuntimeNameAsString();
  7216. S += '>';
  7217. }
  7218. S += '"';
  7219. }
  7220. return;
  7221. }
  7222. S += '@';
  7223. if (OPT->getInterfaceDecl() &&
  7224. (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
  7225. S += '"';
  7226. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  7227. for (const auto *I : OPT->quals()) {
  7228. S += '<';
  7229. S += I->getObjCRuntimeNameAsString();
  7230. S += '>';
  7231. }
  7232. S += '"';
  7233. }
  7234. return;
  7235. }
  7236. // gcc just blithely ignores member pointers.
  7237. // FIXME: we should do better than that. 'M' is available.
  7238. case Type::MemberPointer:
  7239. // This matches gcc's encoding, even though technically it is insufficient.
  7240. //FIXME. We should do a better job than gcc.
  7241. case Type::Vector:
  7242. case Type::ExtVector:
  7243. // Until we have a coherent encoding of these three types, issue warning.
  7244. if (NotEncodedT)
  7245. *NotEncodedT = T;
  7246. return;
  7247. case Type::ConstantMatrix:
  7248. if (NotEncodedT)
  7249. *NotEncodedT = T;
  7250. return;
  7251. case Type::BitInt:
  7252. if (NotEncodedT)
  7253. *NotEncodedT = T;
  7254. return;
  7255. // We could see an undeduced auto type here during error recovery.
  7256. // Just ignore it.
  7257. case Type::Auto:
  7258. case Type::DeducedTemplateSpecialization:
  7259. return;
  7260. case Type::Pipe:
  7261. #define ABSTRACT_TYPE(KIND, BASE)
  7262. #define TYPE(KIND, BASE)
  7263. #define DEPENDENT_TYPE(KIND, BASE) \
  7264. case Type::KIND:
  7265. #define NON_CANONICAL_TYPE(KIND, BASE) \
  7266. case Type::KIND:
  7267. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  7268. case Type::KIND:
  7269. #include "clang/AST/TypeNodes.inc"
  7270. llvm_unreachable("@encode for dependent type!");
  7271. }
  7272. llvm_unreachable("bad type kind!");
  7273. }
  7274. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  7275. std::string &S,
  7276. const FieldDecl *FD,
  7277. bool includeVBases,
  7278. QualType *NotEncodedT) const {
  7279. assert(RDecl && "Expected non-null RecordDecl");
  7280. assert(!RDecl->isUnion() && "Should not be called for unions");
  7281. if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
  7282. return;
  7283. const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  7284. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  7285. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  7286. if (CXXRec) {
  7287. for (const auto &BI : CXXRec->bases()) {
  7288. if (!BI.isVirtual()) {
  7289. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  7290. if (base->isEmpty())
  7291. continue;
  7292. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  7293. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7294. std::make_pair(offs, base));
  7295. }
  7296. }
  7297. }
  7298. unsigned i = 0;
  7299. for (FieldDecl *Field : RDecl->fields()) {
  7300. if (!Field->isZeroLengthBitField(*this) && Field->isZeroSize(*this))
  7301. continue;
  7302. uint64_t offs = layout.getFieldOffset(i);
  7303. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7304. std::make_pair(offs, Field));
  7305. ++i;
  7306. }
  7307. if (CXXRec && includeVBases) {
  7308. for (const auto &BI : CXXRec->vbases()) {
  7309. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  7310. if (base->isEmpty())
  7311. continue;
  7312. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  7313. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  7314. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  7315. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  7316. std::make_pair(offs, base));
  7317. }
  7318. }
  7319. CharUnits size;
  7320. if (CXXRec) {
  7321. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  7322. } else {
  7323. size = layout.getSize();
  7324. }
  7325. #ifndef NDEBUG
  7326. uint64_t CurOffs = 0;
  7327. #endif
  7328. std::multimap<uint64_t, NamedDecl *>::iterator
  7329. CurLayObj = FieldOrBaseOffsets.begin();
  7330. if (CXXRec && CXXRec->isDynamicClass() &&
  7331. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  7332. if (FD) {
  7333. S += "\"_vptr$";
  7334. std::string recname = CXXRec->getNameAsString();
  7335. if (recname.empty()) recname = "?";
  7336. S += recname;
  7337. S += '"';
  7338. }
  7339. S += "^^?";
  7340. #ifndef NDEBUG
  7341. CurOffs += getTypeSize(VoidPtrTy);
  7342. #endif
  7343. }
  7344. if (!RDecl->hasFlexibleArrayMember()) {
  7345. // Mark the end of the structure.
  7346. uint64_t offs = toBits(size);
  7347. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  7348. std::make_pair(offs, nullptr));
  7349. }
  7350. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  7351. #ifndef NDEBUG
  7352. assert(CurOffs <= CurLayObj->first);
  7353. if (CurOffs < CurLayObj->first) {
  7354. uint64_t padding = CurLayObj->first - CurOffs;
  7355. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  7356. // packing/alignment of members is different that normal, in which case
  7357. // the encoding will be out-of-sync with the real layout.
  7358. // If the runtime switches to just consider the size of types without
  7359. // taking into account alignment, we could make padding explicit in the
  7360. // encoding (e.g. using arrays of chars). The encoding strings would be
  7361. // longer then though.
  7362. CurOffs += padding;
  7363. }
  7364. #endif
  7365. NamedDecl *dcl = CurLayObj->second;
  7366. if (!dcl)
  7367. break; // reached end of structure.
  7368. if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
  7369. // We expand the bases without their virtual bases since those are going
  7370. // in the initial structure. Note that this differs from gcc which
  7371. // expands virtual bases each time one is encountered in the hierarchy,
  7372. // making the encoding type bigger than it really is.
  7373. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  7374. NotEncodedT);
  7375. assert(!base->isEmpty());
  7376. #ifndef NDEBUG
  7377. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  7378. #endif
  7379. } else {
  7380. const auto *field = cast<FieldDecl>(dcl);
  7381. if (FD) {
  7382. S += '"';
  7383. S += field->getNameAsString();
  7384. S += '"';
  7385. }
  7386. if (field->isBitField()) {
  7387. EncodeBitField(this, S, field->getType(), field);
  7388. #ifndef NDEBUG
  7389. CurOffs += field->getBitWidthValue(*this);
  7390. #endif
  7391. } else {
  7392. QualType qt = field->getType();
  7393. getLegacyIntegralTypeEncoding(qt);
  7394. getObjCEncodingForTypeImpl(
  7395. qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
  7396. FD, NotEncodedT);
  7397. #ifndef NDEBUG
  7398. CurOffs += getTypeSize(field->getType());
  7399. #endif
  7400. }
  7401. }
  7402. }
  7403. }
  7404. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  7405. std::string& S) const {
  7406. if (QT & Decl::OBJC_TQ_In)
  7407. S += 'n';
  7408. if (QT & Decl::OBJC_TQ_Inout)
  7409. S += 'N';
  7410. if (QT & Decl::OBJC_TQ_Out)
  7411. S += 'o';
  7412. if (QT & Decl::OBJC_TQ_Bycopy)
  7413. S += 'O';
  7414. if (QT & Decl::OBJC_TQ_Byref)
  7415. S += 'R';
  7416. if (QT & Decl::OBJC_TQ_Oneway)
  7417. S += 'V';
  7418. }
  7419. TypedefDecl *ASTContext::getObjCIdDecl() const {
  7420. if (!ObjCIdDecl) {
  7421. QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
  7422. T = getObjCObjectPointerType(T);
  7423. ObjCIdDecl = buildImplicitTypedef(T, "id");
  7424. }
  7425. return ObjCIdDecl;
  7426. }
  7427. TypedefDecl *ASTContext::getObjCSelDecl() const {
  7428. if (!ObjCSelDecl) {
  7429. QualType T = getPointerType(ObjCBuiltinSelTy);
  7430. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  7431. }
  7432. return ObjCSelDecl;
  7433. }
  7434. TypedefDecl *ASTContext::getObjCClassDecl() const {
  7435. if (!ObjCClassDecl) {
  7436. QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
  7437. T = getObjCObjectPointerType(T);
  7438. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  7439. }
  7440. return ObjCClassDecl;
  7441. }
  7442. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  7443. if (!ObjCProtocolClassDecl) {
  7444. ObjCProtocolClassDecl
  7445. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  7446. SourceLocation(),
  7447. &Idents.get("Protocol"),
  7448. /*typeParamList=*/nullptr,
  7449. /*PrevDecl=*/nullptr,
  7450. SourceLocation(), true);
  7451. }
  7452. return ObjCProtocolClassDecl;
  7453. }
  7454. //===----------------------------------------------------------------------===//
  7455. // __builtin_va_list Construction Functions
  7456. //===----------------------------------------------------------------------===//
  7457. static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
  7458. StringRef Name) {
  7459. // typedef char* __builtin[_ms]_va_list;
  7460. QualType T = Context->getPointerType(Context->CharTy);
  7461. return Context->buildImplicitTypedef(T, Name);
  7462. }
  7463. static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
  7464. return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
  7465. }
  7466. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  7467. return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
  7468. }
  7469. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  7470. // typedef void* __builtin_va_list;
  7471. QualType T = Context->getPointerType(Context->VoidTy);
  7472. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  7473. }
  7474. static TypedefDecl *
  7475. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  7476. // struct __va_list
  7477. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  7478. if (Context->getLangOpts().CPlusPlus) {
  7479. // namespace std { struct __va_list {
  7480. auto *NS = NamespaceDecl::Create(
  7481. const_cast<ASTContext &>(*Context), Context->getTranslationUnitDecl(),
  7482. /*Inline*/ false, SourceLocation(), SourceLocation(),
  7483. &Context->Idents.get("std"),
  7484. /*PrevDecl*/ nullptr);
  7485. NS->setImplicit();
  7486. VaListTagDecl->setDeclContext(NS);
  7487. }
  7488. VaListTagDecl->startDefinition();
  7489. const size_t NumFields = 5;
  7490. QualType FieldTypes[NumFields];
  7491. const char *FieldNames[NumFields];
  7492. // void *__stack;
  7493. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  7494. FieldNames[0] = "__stack";
  7495. // void *__gr_top;
  7496. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  7497. FieldNames[1] = "__gr_top";
  7498. // void *__vr_top;
  7499. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7500. FieldNames[2] = "__vr_top";
  7501. // int __gr_offs;
  7502. FieldTypes[3] = Context->IntTy;
  7503. FieldNames[3] = "__gr_offs";
  7504. // int __vr_offs;
  7505. FieldTypes[4] = Context->IntTy;
  7506. FieldNames[4] = "__vr_offs";
  7507. // Create fields
  7508. for (unsigned i = 0; i < NumFields; ++i) {
  7509. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7510. VaListTagDecl,
  7511. SourceLocation(),
  7512. SourceLocation(),
  7513. &Context->Idents.get(FieldNames[i]),
  7514. FieldTypes[i], /*TInfo=*/nullptr,
  7515. /*BitWidth=*/nullptr,
  7516. /*Mutable=*/false,
  7517. ICIS_NoInit);
  7518. Field->setAccess(AS_public);
  7519. VaListTagDecl->addDecl(Field);
  7520. }
  7521. VaListTagDecl->completeDefinition();
  7522. Context->VaListTagDecl = VaListTagDecl;
  7523. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7524. // } __builtin_va_list;
  7525. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  7526. }
  7527. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  7528. // typedef struct __va_list_tag {
  7529. RecordDecl *VaListTagDecl;
  7530. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7531. VaListTagDecl->startDefinition();
  7532. const size_t NumFields = 5;
  7533. QualType FieldTypes[NumFields];
  7534. const char *FieldNames[NumFields];
  7535. // unsigned char gpr;
  7536. FieldTypes[0] = Context->UnsignedCharTy;
  7537. FieldNames[0] = "gpr";
  7538. // unsigned char fpr;
  7539. FieldTypes[1] = Context->UnsignedCharTy;
  7540. FieldNames[1] = "fpr";
  7541. // unsigned short reserved;
  7542. FieldTypes[2] = Context->UnsignedShortTy;
  7543. FieldNames[2] = "reserved";
  7544. // void* overflow_arg_area;
  7545. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7546. FieldNames[3] = "overflow_arg_area";
  7547. // void* reg_save_area;
  7548. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  7549. FieldNames[4] = "reg_save_area";
  7550. // Create fields
  7551. for (unsigned i = 0; i < NumFields; ++i) {
  7552. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  7553. SourceLocation(),
  7554. SourceLocation(),
  7555. &Context->Idents.get(FieldNames[i]),
  7556. FieldTypes[i], /*TInfo=*/nullptr,
  7557. /*BitWidth=*/nullptr,
  7558. /*Mutable=*/false,
  7559. ICIS_NoInit);
  7560. Field->setAccess(AS_public);
  7561. VaListTagDecl->addDecl(Field);
  7562. }
  7563. VaListTagDecl->completeDefinition();
  7564. Context->VaListTagDecl = VaListTagDecl;
  7565. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7566. // } __va_list_tag;
  7567. TypedefDecl *VaListTagTypedefDecl =
  7568. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  7569. QualType VaListTagTypedefType =
  7570. Context->getTypedefType(VaListTagTypedefDecl);
  7571. // typedef __va_list_tag __builtin_va_list[1];
  7572. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7573. QualType VaListTagArrayType
  7574. = Context->getConstantArrayType(VaListTagTypedefType,
  7575. Size, nullptr, ArrayType::Normal, 0);
  7576. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7577. }
  7578. static TypedefDecl *
  7579. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  7580. // struct __va_list_tag {
  7581. RecordDecl *VaListTagDecl;
  7582. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7583. VaListTagDecl->startDefinition();
  7584. const size_t NumFields = 4;
  7585. QualType FieldTypes[NumFields];
  7586. const char *FieldNames[NumFields];
  7587. // unsigned gp_offset;
  7588. FieldTypes[0] = Context->UnsignedIntTy;
  7589. FieldNames[0] = "gp_offset";
  7590. // unsigned fp_offset;
  7591. FieldTypes[1] = Context->UnsignedIntTy;
  7592. FieldNames[1] = "fp_offset";
  7593. // void* overflow_arg_area;
  7594. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7595. FieldNames[2] = "overflow_arg_area";
  7596. // void* reg_save_area;
  7597. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7598. FieldNames[3] = "reg_save_area";
  7599. // Create fields
  7600. for (unsigned i = 0; i < NumFields; ++i) {
  7601. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7602. VaListTagDecl,
  7603. SourceLocation(),
  7604. SourceLocation(),
  7605. &Context->Idents.get(FieldNames[i]),
  7606. FieldTypes[i], /*TInfo=*/nullptr,
  7607. /*BitWidth=*/nullptr,
  7608. /*Mutable=*/false,
  7609. ICIS_NoInit);
  7610. Field->setAccess(AS_public);
  7611. VaListTagDecl->addDecl(Field);
  7612. }
  7613. VaListTagDecl->completeDefinition();
  7614. Context->VaListTagDecl = VaListTagDecl;
  7615. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7616. // };
  7617. // typedef struct __va_list_tag __builtin_va_list[1];
  7618. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7619. QualType VaListTagArrayType = Context->getConstantArrayType(
  7620. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  7621. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7622. }
  7623. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  7624. // typedef int __builtin_va_list[4];
  7625. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  7626. QualType IntArrayType = Context->getConstantArrayType(
  7627. Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
  7628. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  7629. }
  7630. static TypedefDecl *
  7631. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  7632. // struct __va_list
  7633. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  7634. if (Context->getLangOpts().CPlusPlus) {
  7635. // namespace std { struct __va_list {
  7636. NamespaceDecl *NS;
  7637. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  7638. Context->getTranslationUnitDecl(),
  7639. /*Inline*/false, SourceLocation(),
  7640. SourceLocation(), &Context->Idents.get("std"),
  7641. /*PrevDecl*/ nullptr);
  7642. NS->setImplicit();
  7643. VaListDecl->setDeclContext(NS);
  7644. }
  7645. VaListDecl->startDefinition();
  7646. // void * __ap;
  7647. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7648. VaListDecl,
  7649. SourceLocation(),
  7650. SourceLocation(),
  7651. &Context->Idents.get("__ap"),
  7652. Context->getPointerType(Context->VoidTy),
  7653. /*TInfo=*/nullptr,
  7654. /*BitWidth=*/nullptr,
  7655. /*Mutable=*/false,
  7656. ICIS_NoInit);
  7657. Field->setAccess(AS_public);
  7658. VaListDecl->addDecl(Field);
  7659. // };
  7660. VaListDecl->completeDefinition();
  7661. Context->VaListTagDecl = VaListDecl;
  7662. // typedef struct __va_list __builtin_va_list;
  7663. QualType T = Context->getRecordType(VaListDecl);
  7664. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  7665. }
  7666. static TypedefDecl *
  7667. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  7668. // struct __va_list_tag {
  7669. RecordDecl *VaListTagDecl;
  7670. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7671. VaListTagDecl->startDefinition();
  7672. const size_t NumFields = 4;
  7673. QualType FieldTypes[NumFields];
  7674. const char *FieldNames[NumFields];
  7675. // long __gpr;
  7676. FieldTypes[0] = Context->LongTy;
  7677. FieldNames[0] = "__gpr";
  7678. // long __fpr;
  7679. FieldTypes[1] = Context->LongTy;
  7680. FieldNames[1] = "__fpr";
  7681. // void *__overflow_arg_area;
  7682. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7683. FieldNames[2] = "__overflow_arg_area";
  7684. // void *__reg_save_area;
  7685. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  7686. FieldNames[3] = "__reg_save_area";
  7687. // Create fields
  7688. for (unsigned i = 0; i < NumFields; ++i) {
  7689. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  7690. VaListTagDecl,
  7691. SourceLocation(),
  7692. SourceLocation(),
  7693. &Context->Idents.get(FieldNames[i]),
  7694. FieldTypes[i], /*TInfo=*/nullptr,
  7695. /*BitWidth=*/nullptr,
  7696. /*Mutable=*/false,
  7697. ICIS_NoInit);
  7698. Field->setAccess(AS_public);
  7699. VaListTagDecl->addDecl(Field);
  7700. }
  7701. VaListTagDecl->completeDefinition();
  7702. Context->VaListTagDecl = VaListTagDecl;
  7703. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7704. // };
  7705. // typedef __va_list_tag __builtin_va_list[1];
  7706. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7707. QualType VaListTagArrayType = Context->getConstantArrayType(
  7708. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  7709. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7710. }
  7711. static TypedefDecl *CreateHexagonBuiltinVaListDecl(const ASTContext *Context) {
  7712. // typedef struct __va_list_tag {
  7713. RecordDecl *VaListTagDecl;
  7714. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  7715. VaListTagDecl->startDefinition();
  7716. const size_t NumFields = 3;
  7717. QualType FieldTypes[NumFields];
  7718. const char *FieldNames[NumFields];
  7719. // void *CurrentSavedRegisterArea;
  7720. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  7721. FieldNames[0] = "__current_saved_reg_area_pointer";
  7722. // void *SavedRegAreaEnd;
  7723. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  7724. FieldNames[1] = "__saved_reg_area_end_pointer";
  7725. // void *OverflowArea;
  7726. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  7727. FieldNames[2] = "__overflow_area_pointer";
  7728. // Create fields
  7729. for (unsigned i = 0; i < NumFields; ++i) {
  7730. FieldDecl *Field = FieldDecl::Create(
  7731. const_cast<ASTContext &>(*Context), VaListTagDecl, SourceLocation(),
  7732. SourceLocation(), &Context->Idents.get(FieldNames[i]), FieldTypes[i],
  7733. /*TInfo=*/nullptr,
  7734. /*BitWidth=*/nullptr,
  7735. /*Mutable=*/false, ICIS_NoInit);
  7736. Field->setAccess(AS_public);
  7737. VaListTagDecl->addDecl(Field);
  7738. }
  7739. VaListTagDecl->completeDefinition();
  7740. Context->VaListTagDecl = VaListTagDecl;
  7741. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  7742. // } __va_list_tag;
  7743. TypedefDecl *VaListTagTypedefDecl =
  7744. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  7745. QualType VaListTagTypedefType = Context->getTypedefType(VaListTagTypedefDecl);
  7746. // typedef __va_list_tag __builtin_va_list[1];
  7747. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  7748. QualType VaListTagArrayType = Context->getConstantArrayType(
  7749. VaListTagTypedefType, Size, nullptr, ArrayType::Normal, 0);
  7750. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  7751. }
  7752. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  7753. TargetInfo::BuiltinVaListKind Kind) {
  7754. switch (Kind) {
  7755. case TargetInfo::CharPtrBuiltinVaList:
  7756. return CreateCharPtrBuiltinVaListDecl(Context);
  7757. case TargetInfo::VoidPtrBuiltinVaList:
  7758. return CreateVoidPtrBuiltinVaListDecl(Context);
  7759. case TargetInfo::AArch64ABIBuiltinVaList:
  7760. return CreateAArch64ABIBuiltinVaListDecl(Context);
  7761. case TargetInfo::PowerABIBuiltinVaList:
  7762. return CreatePowerABIBuiltinVaListDecl(Context);
  7763. case TargetInfo::X86_64ABIBuiltinVaList:
  7764. return CreateX86_64ABIBuiltinVaListDecl(Context);
  7765. case TargetInfo::PNaClABIBuiltinVaList:
  7766. return CreatePNaClABIBuiltinVaListDecl(Context);
  7767. case TargetInfo::AAPCSABIBuiltinVaList:
  7768. return CreateAAPCSABIBuiltinVaListDecl(Context);
  7769. case TargetInfo::SystemZBuiltinVaList:
  7770. return CreateSystemZBuiltinVaListDecl(Context);
  7771. case TargetInfo::HexagonBuiltinVaList:
  7772. return CreateHexagonBuiltinVaListDecl(Context);
  7773. }
  7774. llvm_unreachable("Unhandled __builtin_va_list type kind");
  7775. }
  7776. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  7777. if (!BuiltinVaListDecl) {
  7778. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  7779. assert(BuiltinVaListDecl->isImplicit());
  7780. }
  7781. return BuiltinVaListDecl;
  7782. }
  7783. Decl *ASTContext::getVaListTagDecl() const {
  7784. // Force the creation of VaListTagDecl by building the __builtin_va_list
  7785. // declaration.
  7786. if (!VaListTagDecl)
  7787. (void)getBuiltinVaListDecl();
  7788. return VaListTagDecl;
  7789. }
  7790. TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
  7791. if (!BuiltinMSVaListDecl)
  7792. BuiltinMSVaListDecl = CreateMSVaListDecl(this);
  7793. return BuiltinMSVaListDecl;
  7794. }
  7795. bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
  7796. return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
  7797. }
  7798. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  7799. assert(ObjCConstantStringType.isNull() &&
  7800. "'NSConstantString' type already set!");
  7801. ObjCConstantStringType = getObjCInterfaceType(Decl);
  7802. }
  7803. /// Retrieve the template name that corresponds to a non-empty
  7804. /// lookup.
  7805. TemplateName
  7806. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  7807. UnresolvedSetIterator End) const {
  7808. unsigned size = End - Begin;
  7809. assert(size > 1 && "set is not overloaded!");
  7810. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  7811. size * sizeof(FunctionTemplateDecl*));
  7812. auto *OT = new (memory) OverloadedTemplateStorage(size);
  7813. NamedDecl **Storage = OT->getStorage();
  7814. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  7815. NamedDecl *D = *I;
  7816. assert(isa<FunctionTemplateDecl>(D) ||
  7817. isa<UnresolvedUsingValueDecl>(D) ||
  7818. (isa<UsingShadowDecl>(D) &&
  7819. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  7820. *Storage++ = D;
  7821. }
  7822. return TemplateName(OT);
  7823. }
  7824. /// Retrieve a template name representing an unqualified-id that has been
  7825. /// assumed to name a template for ADL purposes.
  7826. TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
  7827. auto *OT = new (*this) AssumedTemplateStorage(Name);
  7828. return TemplateName(OT);
  7829. }
  7830. /// Retrieve the template name that represents a qualified
  7831. /// template name such as \c std::vector.
  7832. TemplateName
  7833. ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  7834. bool TemplateKeyword,
  7835. TemplateDecl *Template) const {
  7836. assert(NNS && "Missing nested-name-specifier in qualified template name");
  7837. // FIXME: Canonicalization?
  7838. llvm::FoldingSetNodeID ID;
  7839. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  7840. void *InsertPos = nullptr;
  7841. QualifiedTemplateName *QTN =
  7842. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7843. if (!QTN) {
  7844. QTN = new (*this, alignof(QualifiedTemplateName))
  7845. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  7846. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  7847. }
  7848. return TemplateName(QTN);
  7849. }
  7850. /// Retrieve the template name that represents a dependent
  7851. /// template name such as \c MetaFun::template apply.
  7852. TemplateName
  7853. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  7854. const IdentifierInfo *Name) const {
  7855. assert((!NNS || NNS->isDependent()) &&
  7856. "Nested name specifier must be dependent");
  7857. llvm::FoldingSetNodeID ID;
  7858. DependentTemplateName::Profile(ID, NNS, Name);
  7859. void *InsertPos = nullptr;
  7860. DependentTemplateName *QTN =
  7861. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7862. if (QTN)
  7863. return TemplateName(QTN);
  7864. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  7865. if (CanonNNS == NNS) {
  7866. QTN = new (*this, alignof(DependentTemplateName))
  7867. DependentTemplateName(NNS, Name);
  7868. } else {
  7869. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  7870. QTN = new (*this, alignof(DependentTemplateName))
  7871. DependentTemplateName(NNS, Name, Canon);
  7872. DependentTemplateName *CheckQTN =
  7873. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7874. assert(!CheckQTN && "Dependent type name canonicalization broken");
  7875. (void)CheckQTN;
  7876. }
  7877. DependentTemplateNames.InsertNode(QTN, InsertPos);
  7878. return TemplateName(QTN);
  7879. }
  7880. /// Retrieve the template name that represents a dependent
  7881. /// template name such as \c MetaFun::template operator+.
  7882. TemplateName
  7883. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  7884. OverloadedOperatorKind Operator) const {
  7885. assert((!NNS || NNS->isDependent()) &&
  7886. "Nested name specifier must be dependent");
  7887. llvm::FoldingSetNodeID ID;
  7888. DependentTemplateName::Profile(ID, NNS, Operator);
  7889. void *InsertPos = nullptr;
  7890. DependentTemplateName *QTN
  7891. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7892. if (QTN)
  7893. return TemplateName(QTN);
  7894. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  7895. if (CanonNNS == NNS) {
  7896. QTN = new (*this, alignof(DependentTemplateName))
  7897. DependentTemplateName(NNS, Operator);
  7898. } else {
  7899. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  7900. QTN = new (*this, alignof(DependentTemplateName))
  7901. DependentTemplateName(NNS, Operator, Canon);
  7902. DependentTemplateName *CheckQTN
  7903. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  7904. assert(!CheckQTN && "Dependent template name canonicalization broken");
  7905. (void)CheckQTN;
  7906. }
  7907. DependentTemplateNames.InsertNode(QTN, InsertPos);
  7908. return TemplateName(QTN);
  7909. }
  7910. TemplateName
  7911. ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
  7912. TemplateName replacement) const {
  7913. llvm::FoldingSetNodeID ID;
  7914. SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
  7915. void *insertPos = nullptr;
  7916. SubstTemplateTemplateParmStorage *subst
  7917. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  7918. if (!subst) {
  7919. subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
  7920. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  7921. }
  7922. return TemplateName(subst);
  7923. }
  7924. TemplateName
  7925. ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
  7926. const TemplateArgument &ArgPack) const {
  7927. auto &Self = const_cast<ASTContext &>(*this);
  7928. llvm::FoldingSetNodeID ID;
  7929. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
  7930. void *InsertPos = nullptr;
  7931. SubstTemplateTemplateParmPackStorage *Subst
  7932. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  7933. if (!Subst) {
  7934. Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
  7935. ArgPack.pack_size(),
  7936. ArgPack.pack_begin());
  7937. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  7938. }
  7939. return TemplateName(Subst);
  7940. }
  7941. /// getFromTargetType - Given one of the integer types provided by
  7942. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  7943. /// is actually a value of type @c TargetInfo::IntType.
  7944. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  7945. switch (Type) {
  7946. case TargetInfo::NoInt: return {};
  7947. case TargetInfo::SignedChar: return SignedCharTy;
  7948. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  7949. case TargetInfo::SignedShort: return ShortTy;
  7950. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  7951. case TargetInfo::SignedInt: return IntTy;
  7952. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  7953. case TargetInfo::SignedLong: return LongTy;
  7954. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  7955. case TargetInfo::SignedLongLong: return LongLongTy;
  7956. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  7957. }
  7958. llvm_unreachable("Unhandled TargetInfo::IntType value");
  7959. }
  7960. //===----------------------------------------------------------------------===//
  7961. // Type Predicates.
  7962. //===----------------------------------------------------------------------===//
  7963. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  7964. /// garbage collection attribute.
  7965. ///
  7966. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  7967. if (getLangOpts().getGC() == LangOptions::NonGC)
  7968. return Qualifiers::GCNone;
  7969. assert(getLangOpts().ObjC);
  7970. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  7971. // Default behaviour under objective-C's gc is for ObjC pointers
  7972. // (or pointers to them) be treated as though they were declared
  7973. // as __strong.
  7974. if (GCAttrs == Qualifiers::GCNone) {
  7975. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  7976. return Qualifiers::Strong;
  7977. else if (Ty->isPointerType())
  7978. return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
  7979. } else {
  7980. // It's not valid to set GC attributes on anything that isn't a
  7981. // pointer.
  7982. #ifndef NDEBUG
  7983. QualType CT = Ty->getCanonicalTypeInternal();
  7984. while (const auto *AT = dyn_cast<ArrayType>(CT))
  7985. CT = AT->getElementType();
  7986. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  7987. #endif
  7988. }
  7989. return GCAttrs;
  7990. }
  7991. //===----------------------------------------------------------------------===//
  7992. // Type Compatibility Testing
  7993. //===----------------------------------------------------------------------===//
  7994. /// areCompatVectorTypes - Return true if the two specified vector types are
  7995. /// compatible.
  7996. static bool areCompatVectorTypes(const VectorType *LHS,
  7997. const VectorType *RHS) {
  7998. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  7999. return LHS->getElementType() == RHS->getElementType() &&
  8000. LHS->getNumElements() == RHS->getNumElements();
  8001. }
  8002. /// areCompatMatrixTypes - Return true if the two specified matrix types are
  8003. /// compatible.
  8004. static bool areCompatMatrixTypes(const ConstantMatrixType *LHS,
  8005. const ConstantMatrixType *RHS) {
  8006. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  8007. return LHS->getElementType() == RHS->getElementType() &&
  8008. LHS->getNumRows() == RHS->getNumRows() &&
  8009. LHS->getNumColumns() == RHS->getNumColumns();
  8010. }
  8011. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  8012. QualType SecondVec) {
  8013. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  8014. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  8015. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  8016. return true;
  8017. // Treat Neon vector types and most AltiVec vector types as if they are the
  8018. // equivalent GCC vector types.
  8019. const auto *First = FirstVec->castAs<VectorType>();
  8020. const auto *Second = SecondVec->castAs<VectorType>();
  8021. if (First->getNumElements() == Second->getNumElements() &&
  8022. hasSameType(First->getElementType(), Second->getElementType()) &&
  8023. First->getVectorKind() != VectorType::AltiVecPixel &&
  8024. First->getVectorKind() != VectorType::AltiVecBool &&
  8025. Second->getVectorKind() != VectorType::AltiVecPixel &&
  8026. Second->getVectorKind() != VectorType::AltiVecBool &&
  8027. First->getVectorKind() != VectorType::SveFixedLengthDataVector &&
  8028. First->getVectorKind() != VectorType::SveFixedLengthPredicateVector &&
  8029. Second->getVectorKind() != VectorType::SveFixedLengthDataVector &&
  8030. Second->getVectorKind() != VectorType::SveFixedLengthPredicateVector)
  8031. return true;
  8032. return false;
  8033. }
  8034. /// getSVETypeSize - Return SVE vector or predicate register size.
  8035. static uint64_t getSVETypeSize(ASTContext &Context, const BuiltinType *Ty) {
  8036. assert(Ty->isVLSTBuiltinType() && "Invalid SVE Type");
  8037. return Ty->getKind() == BuiltinType::SveBool
  8038. ? (Context.getLangOpts().VScaleMin * 128) / Context.getCharWidth()
  8039. : Context.getLangOpts().VScaleMin * 128;
  8040. }
  8041. bool ASTContext::areCompatibleSveTypes(QualType FirstType,
  8042. QualType SecondType) {
  8043. assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
  8044. (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
  8045. "Expected SVE builtin type and vector type!");
  8046. auto IsValidCast = [this](QualType FirstType, QualType SecondType) {
  8047. if (const auto *BT = FirstType->getAs<BuiltinType>()) {
  8048. if (const auto *VT = SecondType->getAs<VectorType>()) {
  8049. // Predicates have the same representation as uint8 so we also have to
  8050. // check the kind to make these types incompatible.
  8051. if (VT->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  8052. return BT->getKind() == BuiltinType::SveBool;
  8053. else if (VT->getVectorKind() == VectorType::SveFixedLengthDataVector)
  8054. return VT->getElementType().getCanonicalType() ==
  8055. FirstType->getSveEltType(*this);
  8056. else if (VT->getVectorKind() == VectorType::GenericVector)
  8057. return getTypeSize(SecondType) == getSVETypeSize(*this, BT) &&
  8058. hasSameType(VT->getElementType(),
  8059. getBuiltinVectorTypeInfo(BT).ElementType);
  8060. }
  8061. }
  8062. return false;
  8063. };
  8064. return IsValidCast(FirstType, SecondType) ||
  8065. IsValidCast(SecondType, FirstType);
  8066. }
  8067. bool ASTContext::areLaxCompatibleSveTypes(QualType FirstType,
  8068. QualType SecondType) {
  8069. assert(((FirstType->isSizelessBuiltinType() && SecondType->isVectorType()) ||
  8070. (FirstType->isVectorType() && SecondType->isSizelessBuiltinType())) &&
  8071. "Expected SVE builtin type and vector type!");
  8072. auto IsLaxCompatible = [this](QualType FirstType, QualType SecondType) {
  8073. const auto *BT = FirstType->getAs<BuiltinType>();
  8074. if (!BT)
  8075. return false;
  8076. const auto *VecTy = SecondType->getAs<VectorType>();
  8077. if (VecTy &&
  8078. (VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  8079. VecTy->getVectorKind() == VectorType::GenericVector)) {
  8080. const LangOptions::LaxVectorConversionKind LVCKind =
  8081. getLangOpts().getLaxVectorConversions();
  8082. // Can not convert between sve predicates and sve vectors because of
  8083. // different size.
  8084. if (BT->getKind() == BuiltinType::SveBool &&
  8085. VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector)
  8086. return false;
  8087. // If __ARM_FEATURE_SVE_BITS != N do not allow GNU vector lax conversion.
  8088. // "Whenever __ARM_FEATURE_SVE_BITS==N, GNUT implicitly
  8089. // converts to VLAT and VLAT implicitly converts to GNUT."
  8090. // ACLE Spec Version 00bet6, 3.7.3.2. Behavior common to vectors and
  8091. // predicates.
  8092. if (VecTy->getVectorKind() == VectorType::GenericVector &&
  8093. getTypeSize(SecondType) != getSVETypeSize(*this, BT))
  8094. return false;
  8095. // If -flax-vector-conversions=all is specified, the types are
  8096. // certainly compatible.
  8097. if (LVCKind == LangOptions::LaxVectorConversionKind::All)
  8098. return true;
  8099. // If -flax-vector-conversions=integer is specified, the types are
  8100. // compatible if the elements are integer types.
  8101. if (LVCKind == LangOptions::LaxVectorConversionKind::Integer)
  8102. return VecTy->getElementType().getCanonicalType()->isIntegerType() &&
  8103. FirstType->getSveEltType(*this)->isIntegerType();
  8104. }
  8105. return false;
  8106. };
  8107. return IsLaxCompatible(FirstType, SecondType) ||
  8108. IsLaxCompatible(SecondType, FirstType);
  8109. }
  8110. bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
  8111. while (true) {
  8112. // __strong id
  8113. if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
  8114. if (Attr->getAttrKind() == attr::ObjCOwnership)
  8115. return true;
  8116. Ty = Attr->getModifiedType();
  8117. // X *__strong (...)
  8118. } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
  8119. Ty = Paren->getInnerType();
  8120. // We do not want to look through typedefs, typeof(expr),
  8121. // typeof(type), or any other way that the type is somehow
  8122. // abstracted.
  8123. } else {
  8124. return false;
  8125. }
  8126. }
  8127. }
  8128. //===----------------------------------------------------------------------===//
  8129. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  8130. //===----------------------------------------------------------------------===//
  8131. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  8132. /// inheritance hierarchy of 'rProto'.
  8133. bool
  8134. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  8135. ObjCProtocolDecl *rProto) const {
  8136. if (declaresSameEntity(lProto, rProto))
  8137. return true;
  8138. for (auto *PI : rProto->protocols())
  8139. if (ProtocolCompatibleWithProtocol(lProto, PI))
  8140. return true;
  8141. return false;
  8142. }
  8143. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  8144. /// Class<pr1, ...>.
  8145. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
  8146. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
  8147. for (auto *lhsProto : lhs->quals()) {
  8148. bool match = false;
  8149. for (auto *rhsProto : rhs->quals()) {
  8150. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  8151. match = true;
  8152. break;
  8153. }
  8154. }
  8155. if (!match)
  8156. return false;
  8157. }
  8158. return true;
  8159. }
  8160. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  8161. /// ObjCQualifiedIDType.
  8162. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
  8163. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
  8164. bool compare) {
  8165. // Allow id<P..> and an 'id' in all cases.
  8166. if (lhs->isObjCIdType() || rhs->isObjCIdType())
  8167. return true;
  8168. // Don't allow id<P..> to convert to Class or Class<P..> in either direction.
  8169. if (lhs->isObjCClassType() || lhs->isObjCQualifiedClassType() ||
  8170. rhs->isObjCClassType() || rhs->isObjCQualifiedClassType())
  8171. return false;
  8172. if (lhs->isObjCQualifiedIdType()) {
  8173. if (rhs->qual_empty()) {
  8174. // If the RHS is a unqualified interface pointer "NSString*",
  8175. // make sure we check the class hierarchy.
  8176. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  8177. for (auto *I : lhs->quals()) {
  8178. // when comparing an id<P> on lhs with a static type on rhs,
  8179. // see if static class implements all of id's protocols, directly or
  8180. // through its super class and categories.
  8181. if (!rhsID->ClassImplementsProtocol(I, true))
  8182. return false;
  8183. }
  8184. }
  8185. // If there are no qualifiers and no interface, we have an 'id'.
  8186. return true;
  8187. }
  8188. // Both the right and left sides have qualifiers.
  8189. for (auto *lhsProto : lhs->quals()) {
  8190. bool match = false;
  8191. // when comparing an id<P> on lhs with a static type on rhs,
  8192. // see if static class implements all of id's protocols, directly or
  8193. // through its super class and categories.
  8194. for (auto *rhsProto : rhs->quals()) {
  8195. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8196. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8197. match = true;
  8198. break;
  8199. }
  8200. }
  8201. // If the RHS is a qualified interface pointer "NSString<P>*",
  8202. // make sure we check the class hierarchy.
  8203. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  8204. for (auto *I : lhs->quals()) {
  8205. // when comparing an id<P> on lhs with a static type on rhs,
  8206. // see if static class implements all of id's protocols, directly or
  8207. // through its super class and categories.
  8208. if (rhsID->ClassImplementsProtocol(I, true)) {
  8209. match = true;
  8210. break;
  8211. }
  8212. }
  8213. }
  8214. if (!match)
  8215. return false;
  8216. }
  8217. return true;
  8218. }
  8219. assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
  8220. if (lhs->getInterfaceType()) {
  8221. // If both the right and left sides have qualifiers.
  8222. for (auto *lhsProto : lhs->quals()) {
  8223. bool match = false;
  8224. // when comparing an id<P> on rhs with a static type on lhs,
  8225. // see if static class implements all of id's protocols, directly or
  8226. // through its super class and categories.
  8227. // First, lhs protocols in the qualifier list must be found, direct
  8228. // or indirect in rhs's qualifier list or it is a mismatch.
  8229. for (auto *rhsProto : rhs->quals()) {
  8230. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8231. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8232. match = true;
  8233. break;
  8234. }
  8235. }
  8236. if (!match)
  8237. return false;
  8238. }
  8239. // Static class's protocols, or its super class or category protocols
  8240. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  8241. if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
  8242. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  8243. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  8244. // This is rather dubious but matches gcc's behavior. If lhs has
  8245. // no type qualifier and its class has no static protocol(s)
  8246. // assume that it is mismatch.
  8247. if (LHSInheritedProtocols.empty() && lhs->qual_empty())
  8248. return false;
  8249. for (auto *lhsProto : LHSInheritedProtocols) {
  8250. bool match = false;
  8251. for (auto *rhsProto : rhs->quals()) {
  8252. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  8253. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  8254. match = true;
  8255. break;
  8256. }
  8257. }
  8258. if (!match)
  8259. return false;
  8260. }
  8261. }
  8262. return true;
  8263. }
  8264. return false;
  8265. }
  8266. /// canAssignObjCInterfaces - Return true if the two interface types are
  8267. /// compatible for assignment from RHS to LHS. This handles validation of any
  8268. /// protocol qualifiers on the LHS or RHS.
  8269. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  8270. const ObjCObjectPointerType *RHSOPT) {
  8271. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  8272. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  8273. // If either type represents the built-in 'id' type, return true.
  8274. if (LHS->isObjCUnqualifiedId() || RHS->isObjCUnqualifiedId())
  8275. return true;
  8276. // Function object that propagates a successful result or handles
  8277. // __kindof types.
  8278. auto finish = [&](bool succeeded) -> bool {
  8279. if (succeeded)
  8280. return true;
  8281. if (!RHS->isKindOfType())
  8282. return false;
  8283. // Strip off __kindof and protocol qualifiers, then check whether
  8284. // we can assign the other way.
  8285. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8286. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  8287. };
  8288. // Casts from or to id<P> are allowed when the other side has compatible
  8289. // protocols.
  8290. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  8291. return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
  8292. }
  8293. // Verify protocol compatibility for casts from Class<P1> to Class<P2>.
  8294. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  8295. return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
  8296. }
  8297. // Casts from Class to Class<Foo>, or vice-versa, are allowed.
  8298. if (LHS->isObjCClass() && RHS->isObjCClass()) {
  8299. return true;
  8300. }
  8301. // If we have 2 user-defined types, fall into that path.
  8302. if (LHS->getInterface() && RHS->getInterface()) {
  8303. return finish(canAssignObjCInterfaces(LHS, RHS));
  8304. }
  8305. return false;
  8306. }
  8307. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  8308. /// for providing type-safety for objective-c pointers used to pass/return
  8309. /// arguments in block literals. When passed as arguments, passing 'A*' where
  8310. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  8311. /// not OK. For the return type, the opposite is not OK.
  8312. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  8313. const ObjCObjectPointerType *LHSOPT,
  8314. const ObjCObjectPointerType *RHSOPT,
  8315. bool BlockReturnType) {
  8316. // Function object that propagates a successful result or handles
  8317. // __kindof types.
  8318. auto finish = [&](bool succeeded) -> bool {
  8319. if (succeeded)
  8320. return true;
  8321. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  8322. if (!Expected->isKindOfType())
  8323. return false;
  8324. // Strip off __kindof and protocol qualifiers, then check whether
  8325. // we can assign the other way.
  8326. return canAssignObjCInterfacesInBlockPointer(
  8327. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8328. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  8329. BlockReturnType);
  8330. };
  8331. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  8332. return true;
  8333. if (LHSOPT->isObjCBuiltinType()) {
  8334. return finish(RHSOPT->isObjCBuiltinType() ||
  8335. RHSOPT->isObjCQualifiedIdType());
  8336. }
  8337. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) {
  8338. if (getLangOpts().CompatibilityQualifiedIdBlockParamTypeChecking)
  8339. // Use for block parameters previous type checking for compatibility.
  8340. return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false) ||
  8341. // Or corrected type checking as in non-compat mode.
  8342. (!BlockReturnType &&
  8343. ObjCQualifiedIdTypesAreCompatible(RHSOPT, LHSOPT, false)));
  8344. else
  8345. return finish(ObjCQualifiedIdTypesAreCompatible(
  8346. (BlockReturnType ? LHSOPT : RHSOPT),
  8347. (BlockReturnType ? RHSOPT : LHSOPT), false));
  8348. }
  8349. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  8350. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  8351. if (LHS && RHS) { // We have 2 user-defined types.
  8352. if (LHS != RHS) {
  8353. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  8354. return finish(BlockReturnType);
  8355. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  8356. return finish(!BlockReturnType);
  8357. }
  8358. else
  8359. return true;
  8360. }
  8361. return false;
  8362. }
  8363. /// Comparison routine for Objective-C protocols to be used with
  8364. /// llvm::array_pod_sort.
  8365. static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
  8366. ObjCProtocolDecl * const *rhs) {
  8367. return (*lhs)->getName().compare((*rhs)->getName());
  8368. }
  8369. /// getIntersectionOfProtocols - This routine finds the intersection of set
  8370. /// of protocols inherited from two distinct objective-c pointer objects with
  8371. /// the given common base.
  8372. /// It is used to build composite qualifier list of the composite type of
  8373. /// the conditional expression involving two objective-c pointer objects.
  8374. static
  8375. void getIntersectionOfProtocols(ASTContext &Context,
  8376. const ObjCInterfaceDecl *CommonBase,
  8377. const ObjCObjectPointerType *LHSOPT,
  8378. const ObjCObjectPointerType *RHSOPT,
  8379. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  8380. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  8381. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  8382. assert(LHS->getInterface() && "LHS must have an interface base");
  8383. assert(RHS->getInterface() && "RHS must have an interface base");
  8384. // Add all of the protocols for the LHS.
  8385. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  8386. // Start with the protocol qualifiers.
  8387. for (auto proto : LHS->quals()) {
  8388. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  8389. }
  8390. // Also add the protocols associated with the LHS interface.
  8391. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  8392. // Add all of the protocols for the RHS.
  8393. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  8394. // Start with the protocol qualifiers.
  8395. for (auto proto : RHS->quals()) {
  8396. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  8397. }
  8398. // Also add the protocols associated with the RHS interface.
  8399. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  8400. // Compute the intersection of the collected protocol sets.
  8401. for (auto proto : LHSProtocolSet) {
  8402. if (RHSProtocolSet.count(proto))
  8403. IntersectionSet.push_back(proto);
  8404. }
  8405. // Compute the set of protocols that is implied by either the common type or
  8406. // the protocols within the intersection.
  8407. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  8408. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  8409. // Remove any implied protocols from the list of inherited protocols.
  8410. if (!ImpliedProtocols.empty()) {
  8411. llvm::erase_if(IntersectionSet, [&](ObjCProtocolDecl *proto) -> bool {
  8412. return ImpliedProtocols.contains(proto);
  8413. });
  8414. }
  8415. // Sort the remaining protocols by name.
  8416. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  8417. compareObjCProtocolsByName);
  8418. }
  8419. /// Determine whether the first type is a subtype of the second.
  8420. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  8421. QualType rhs) {
  8422. // Common case: two object pointers.
  8423. const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  8424. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  8425. if (lhsOPT && rhsOPT)
  8426. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  8427. // Two block pointers.
  8428. const auto *lhsBlock = lhs->getAs<BlockPointerType>();
  8429. const auto *rhsBlock = rhs->getAs<BlockPointerType>();
  8430. if (lhsBlock && rhsBlock)
  8431. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  8432. // If either is an unqualified 'id' and the other is a block, it's
  8433. // acceptable.
  8434. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  8435. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  8436. return true;
  8437. return false;
  8438. }
  8439. // Check that the given Objective-C type argument lists are equivalent.
  8440. static bool sameObjCTypeArgs(ASTContext &ctx,
  8441. const ObjCInterfaceDecl *iface,
  8442. ArrayRef<QualType> lhsArgs,
  8443. ArrayRef<QualType> rhsArgs,
  8444. bool stripKindOf) {
  8445. if (lhsArgs.size() != rhsArgs.size())
  8446. return false;
  8447. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  8448. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  8449. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  8450. continue;
  8451. switch (typeParams->begin()[i]->getVariance()) {
  8452. case ObjCTypeParamVariance::Invariant:
  8453. if (!stripKindOf ||
  8454. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  8455. rhsArgs[i].stripObjCKindOfType(ctx))) {
  8456. return false;
  8457. }
  8458. break;
  8459. case ObjCTypeParamVariance::Covariant:
  8460. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  8461. return false;
  8462. break;
  8463. case ObjCTypeParamVariance::Contravariant:
  8464. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  8465. return false;
  8466. break;
  8467. }
  8468. }
  8469. return true;
  8470. }
  8471. QualType ASTContext::areCommonBaseCompatible(
  8472. const ObjCObjectPointerType *Lptr,
  8473. const ObjCObjectPointerType *Rptr) {
  8474. const ObjCObjectType *LHS = Lptr->getObjectType();
  8475. const ObjCObjectType *RHS = Rptr->getObjectType();
  8476. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  8477. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  8478. if (!LDecl || !RDecl)
  8479. return {};
  8480. // When either LHS or RHS is a kindof type, we should return a kindof type.
  8481. // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
  8482. // kindof(A).
  8483. bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
  8484. // Follow the left-hand side up the class hierarchy until we either hit a
  8485. // root or find the RHS. Record the ancestors in case we don't find it.
  8486. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  8487. LHSAncestors;
  8488. while (true) {
  8489. // Record this ancestor. We'll need this if the common type isn't in the
  8490. // path from the LHS to the root.
  8491. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  8492. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  8493. // Get the type arguments.
  8494. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  8495. bool anyChanges = false;
  8496. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  8497. // Both have type arguments, compare them.
  8498. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  8499. LHS->getTypeArgs(), RHS->getTypeArgs(),
  8500. /*stripKindOf=*/true))
  8501. return {};
  8502. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  8503. // If only one has type arguments, the result will not have type
  8504. // arguments.
  8505. LHSTypeArgs = {};
  8506. anyChanges = true;
  8507. }
  8508. // Compute the intersection of protocols.
  8509. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  8510. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  8511. Protocols);
  8512. if (!Protocols.empty())
  8513. anyChanges = true;
  8514. // If anything in the LHS will have changed, build a new result type.
  8515. // If we need to return a kindof type but LHS is not a kindof type, we
  8516. // build a new result type.
  8517. if (anyChanges || LHS->isKindOfType() != anyKindOf) {
  8518. QualType Result = getObjCInterfaceType(LHS->getInterface());
  8519. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  8520. anyKindOf || LHS->isKindOfType());
  8521. return getObjCObjectPointerType(Result);
  8522. }
  8523. return getObjCObjectPointerType(QualType(LHS, 0));
  8524. }
  8525. // Find the superclass.
  8526. QualType LHSSuperType = LHS->getSuperClassType();
  8527. if (LHSSuperType.isNull())
  8528. break;
  8529. LHS = LHSSuperType->castAs<ObjCObjectType>();
  8530. }
  8531. // We didn't find anything by following the LHS to its root; now check
  8532. // the RHS against the cached set of ancestors.
  8533. while (true) {
  8534. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  8535. if (KnownLHS != LHSAncestors.end()) {
  8536. LHS = KnownLHS->second;
  8537. // Get the type arguments.
  8538. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  8539. bool anyChanges = false;
  8540. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  8541. // Both have type arguments, compare them.
  8542. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  8543. LHS->getTypeArgs(), RHS->getTypeArgs(),
  8544. /*stripKindOf=*/true))
  8545. return {};
  8546. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  8547. // If only one has type arguments, the result will not have type
  8548. // arguments.
  8549. RHSTypeArgs = {};
  8550. anyChanges = true;
  8551. }
  8552. // Compute the intersection of protocols.
  8553. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  8554. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  8555. Protocols);
  8556. if (!Protocols.empty())
  8557. anyChanges = true;
  8558. // If we need to return a kindof type but RHS is not a kindof type, we
  8559. // build a new result type.
  8560. if (anyChanges || RHS->isKindOfType() != anyKindOf) {
  8561. QualType Result = getObjCInterfaceType(RHS->getInterface());
  8562. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  8563. anyKindOf || RHS->isKindOfType());
  8564. return getObjCObjectPointerType(Result);
  8565. }
  8566. return getObjCObjectPointerType(QualType(RHS, 0));
  8567. }
  8568. // Find the superclass of the RHS.
  8569. QualType RHSSuperType = RHS->getSuperClassType();
  8570. if (RHSSuperType.isNull())
  8571. break;
  8572. RHS = RHSSuperType->castAs<ObjCObjectType>();
  8573. }
  8574. return {};
  8575. }
  8576. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  8577. const ObjCObjectType *RHS) {
  8578. assert(LHS->getInterface() && "LHS is not an interface type");
  8579. assert(RHS->getInterface() && "RHS is not an interface type");
  8580. // Verify that the base decls are compatible: the RHS must be a subclass of
  8581. // the LHS.
  8582. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  8583. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  8584. if (!IsSuperClass)
  8585. return false;
  8586. // If the LHS has protocol qualifiers, determine whether all of them are
  8587. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  8588. // LHS).
  8589. if (LHS->getNumProtocols() > 0) {
  8590. // OK if conversion of LHS to SuperClass results in narrowing of types
  8591. // ; i.e., SuperClass may implement at least one of the protocols
  8592. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  8593. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  8594. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  8595. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  8596. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  8597. // qualifiers.
  8598. for (auto *RHSPI : RHS->quals())
  8599. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  8600. // If there is no protocols associated with RHS, it is not a match.
  8601. if (SuperClassInheritedProtocols.empty())
  8602. return false;
  8603. for (const auto *LHSProto : LHS->quals()) {
  8604. bool SuperImplementsProtocol = false;
  8605. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  8606. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  8607. SuperImplementsProtocol = true;
  8608. break;
  8609. }
  8610. if (!SuperImplementsProtocol)
  8611. return false;
  8612. }
  8613. }
  8614. // If the LHS is specialized, we may need to check type arguments.
  8615. if (LHS->isSpecialized()) {
  8616. // Follow the superclass chain until we've matched the LHS class in the
  8617. // hierarchy. This substitutes type arguments through.
  8618. const ObjCObjectType *RHSSuper = RHS;
  8619. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  8620. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  8621. // If the RHS is specializd, compare type arguments.
  8622. if (RHSSuper->isSpecialized() &&
  8623. !sameObjCTypeArgs(*this, LHS->getInterface(),
  8624. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  8625. /*stripKindOf=*/true)) {
  8626. return false;
  8627. }
  8628. }
  8629. return true;
  8630. }
  8631. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  8632. // get the "pointed to" types
  8633. const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  8634. const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  8635. if (!LHSOPT || !RHSOPT)
  8636. return false;
  8637. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  8638. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  8639. }
  8640. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  8641. return canAssignObjCInterfaces(
  8642. getObjCObjectPointerType(To)->castAs<ObjCObjectPointerType>(),
  8643. getObjCObjectPointerType(From)->castAs<ObjCObjectPointerType>());
  8644. }
  8645. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  8646. /// both shall have the identically qualified version of a compatible type.
  8647. /// C99 6.2.7p1: Two types have compatible types if their types are the
  8648. /// same. See 6.7.[2,3,5] for additional rules.
  8649. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  8650. bool CompareUnqualified) {
  8651. if (getLangOpts().CPlusPlus)
  8652. return hasSameType(LHS, RHS);
  8653. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  8654. }
  8655. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  8656. return typesAreCompatible(LHS, RHS);
  8657. }
  8658. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  8659. return !mergeTypes(LHS, RHS, true).isNull();
  8660. }
  8661. /// mergeTransparentUnionType - if T is a transparent union type and a member
  8662. /// of T is compatible with SubType, return the merged type, else return
  8663. /// QualType()
  8664. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  8665. bool OfBlockPointer,
  8666. bool Unqualified) {
  8667. if (const RecordType *UT = T->getAsUnionType()) {
  8668. RecordDecl *UD = UT->getDecl();
  8669. if (UD->hasAttr<TransparentUnionAttr>()) {
  8670. for (const auto *I : UD->fields()) {
  8671. QualType ET = I->getType().getUnqualifiedType();
  8672. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  8673. if (!MT.isNull())
  8674. return MT;
  8675. }
  8676. }
  8677. }
  8678. return {};
  8679. }
  8680. /// mergeFunctionParameterTypes - merge two types which appear as function
  8681. /// parameter types
  8682. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  8683. bool OfBlockPointer,
  8684. bool Unqualified) {
  8685. // GNU extension: two types are compatible if they appear as a function
  8686. // argument, one of the types is a transparent union type and the other
  8687. // type is compatible with a union member
  8688. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  8689. Unqualified);
  8690. if (!lmerge.isNull())
  8691. return lmerge;
  8692. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  8693. Unqualified);
  8694. if (!rmerge.isNull())
  8695. return rmerge;
  8696. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  8697. }
  8698. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  8699. bool OfBlockPointer, bool Unqualified,
  8700. bool AllowCXX) {
  8701. const auto *lbase = lhs->castAs<FunctionType>();
  8702. const auto *rbase = rhs->castAs<FunctionType>();
  8703. const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
  8704. const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
  8705. bool allLTypes = true;
  8706. bool allRTypes = true;
  8707. // Check return type
  8708. QualType retType;
  8709. if (OfBlockPointer) {
  8710. QualType RHS = rbase->getReturnType();
  8711. QualType LHS = lbase->getReturnType();
  8712. bool UnqualifiedResult = Unqualified;
  8713. if (!UnqualifiedResult)
  8714. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  8715. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  8716. }
  8717. else
  8718. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  8719. Unqualified);
  8720. if (retType.isNull())
  8721. return {};
  8722. if (Unqualified)
  8723. retType = retType.getUnqualifiedType();
  8724. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  8725. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  8726. if (Unqualified) {
  8727. LRetType = LRetType.getUnqualifiedType();
  8728. RRetType = RRetType.getUnqualifiedType();
  8729. }
  8730. if (getCanonicalType(retType) != LRetType)
  8731. allLTypes = false;
  8732. if (getCanonicalType(retType) != RRetType)
  8733. allRTypes = false;
  8734. // FIXME: double check this
  8735. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  8736. // rbase->getRegParmAttr() != 0 &&
  8737. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  8738. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  8739. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  8740. // Compatible functions must have compatible calling conventions
  8741. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  8742. return {};
  8743. // Regparm is part of the calling convention.
  8744. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  8745. return {};
  8746. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  8747. return {};
  8748. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  8749. return {};
  8750. if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
  8751. return {};
  8752. if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
  8753. return {};
  8754. // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
  8755. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  8756. if (lbaseInfo.getNoReturn() != NoReturn)
  8757. allLTypes = false;
  8758. if (rbaseInfo.getNoReturn() != NoReturn)
  8759. allRTypes = false;
  8760. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  8761. if (lproto && rproto) { // two C99 style function prototypes
  8762. assert((AllowCXX ||
  8763. (!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec())) &&
  8764. "C++ shouldn't be here");
  8765. // Compatible functions must have the same number of parameters
  8766. if (lproto->getNumParams() != rproto->getNumParams())
  8767. return {};
  8768. // Variadic and non-variadic functions aren't compatible
  8769. if (lproto->isVariadic() != rproto->isVariadic())
  8770. return {};
  8771. if (lproto->getMethodQuals() != rproto->getMethodQuals())
  8772. return {};
  8773. SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
  8774. bool canUseLeft, canUseRight;
  8775. if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
  8776. newParamInfos))
  8777. return {};
  8778. if (!canUseLeft)
  8779. allLTypes = false;
  8780. if (!canUseRight)
  8781. allRTypes = false;
  8782. // Check parameter type compatibility
  8783. SmallVector<QualType, 10> types;
  8784. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  8785. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  8786. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  8787. QualType paramType = mergeFunctionParameterTypes(
  8788. lParamType, rParamType, OfBlockPointer, Unqualified);
  8789. if (paramType.isNull())
  8790. return {};
  8791. if (Unqualified)
  8792. paramType = paramType.getUnqualifiedType();
  8793. types.push_back(paramType);
  8794. if (Unqualified) {
  8795. lParamType = lParamType.getUnqualifiedType();
  8796. rParamType = rParamType.getUnqualifiedType();
  8797. }
  8798. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  8799. allLTypes = false;
  8800. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  8801. allRTypes = false;
  8802. }
  8803. if (allLTypes) return lhs;
  8804. if (allRTypes) return rhs;
  8805. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  8806. EPI.ExtInfo = einfo;
  8807. EPI.ExtParameterInfos =
  8808. newParamInfos.empty() ? nullptr : newParamInfos.data();
  8809. return getFunctionType(retType, types, EPI);
  8810. }
  8811. if (lproto) allRTypes = false;
  8812. if (rproto) allLTypes = false;
  8813. const FunctionProtoType *proto = lproto ? lproto : rproto;
  8814. if (proto) {
  8815. assert((AllowCXX || !proto->hasExceptionSpec()) && "C++ shouldn't be here");
  8816. if (proto->isVariadic())
  8817. return {};
  8818. // Check that the types are compatible with the types that
  8819. // would result from default argument promotions (C99 6.7.5.3p15).
  8820. // The only types actually affected are promotable integer
  8821. // types and floats, which would be passed as a different
  8822. // type depending on whether the prototype is visible.
  8823. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  8824. QualType paramTy = proto->getParamType(i);
  8825. // Look at the converted type of enum types, since that is the type used
  8826. // to pass enum values.
  8827. if (const auto *Enum = paramTy->getAs<EnumType>()) {
  8828. paramTy = Enum->getDecl()->getIntegerType();
  8829. if (paramTy.isNull())
  8830. return {};
  8831. }
  8832. if (paramTy->isPromotableIntegerType() ||
  8833. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  8834. return {};
  8835. }
  8836. if (allLTypes) return lhs;
  8837. if (allRTypes) return rhs;
  8838. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  8839. EPI.ExtInfo = einfo;
  8840. return getFunctionType(retType, proto->getParamTypes(), EPI);
  8841. }
  8842. if (allLTypes) return lhs;
  8843. if (allRTypes) return rhs;
  8844. return getFunctionNoProtoType(retType, einfo);
  8845. }
  8846. /// Given that we have an enum type and a non-enum type, try to merge them.
  8847. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  8848. QualType other, bool isBlockReturnType) {
  8849. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  8850. // a signed integer type, or an unsigned integer type.
  8851. // Compatibility is based on the underlying type, not the promotion
  8852. // type.
  8853. QualType underlyingType = ET->getDecl()->getIntegerType();
  8854. if (underlyingType.isNull())
  8855. return {};
  8856. if (Context.hasSameType(underlyingType, other))
  8857. return other;
  8858. // In block return types, we're more permissive and accept any
  8859. // integral type of the same size.
  8860. if (isBlockReturnType && other->isIntegerType() &&
  8861. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  8862. return other;
  8863. return {};
  8864. }
  8865. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
  8866. bool OfBlockPointer,
  8867. bool Unqualified, bool BlockReturnType) {
  8868. // For C++ we will not reach this code with reference types (see below),
  8869. // for OpenMP variant call overloading we might.
  8870. //
  8871. // C++ [expr]: If an expression initially has the type "reference to T", the
  8872. // type is adjusted to "T" prior to any further analysis, the expression
  8873. // designates the object or function denoted by the reference, and the
  8874. // expression is an lvalue unless the reference is an rvalue reference and
  8875. // the expression is a function call (possibly inside parentheses).
  8876. auto *LHSRefTy = LHS->getAs<ReferenceType>();
  8877. auto *RHSRefTy = RHS->getAs<ReferenceType>();
  8878. if (LangOpts.OpenMP && LHSRefTy && RHSRefTy &&
  8879. LHS->getTypeClass() == RHS->getTypeClass())
  8880. return mergeTypes(LHSRefTy->getPointeeType(), RHSRefTy->getPointeeType(),
  8881. OfBlockPointer, Unqualified, BlockReturnType);
  8882. if (LHSRefTy || RHSRefTy)
  8883. return {};
  8884. if (Unqualified) {
  8885. LHS = LHS.getUnqualifiedType();
  8886. RHS = RHS.getUnqualifiedType();
  8887. }
  8888. QualType LHSCan = getCanonicalType(LHS),
  8889. RHSCan = getCanonicalType(RHS);
  8890. // If two types are identical, they are compatible.
  8891. if (LHSCan == RHSCan)
  8892. return LHS;
  8893. // If the qualifiers are different, the types aren't compatible... mostly.
  8894. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  8895. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  8896. if (LQuals != RQuals) {
  8897. // If any of these qualifiers are different, we have a type
  8898. // mismatch.
  8899. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  8900. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  8901. LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
  8902. LQuals.hasUnaligned() != RQuals.hasUnaligned())
  8903. return {};
  8904. // Exactly one GC qualifier difference is allowed: __strong is
  8905. // okay if the other type has no GC qualifier but is an Objective
  8906. // C object pointer (i.e. implicitly strong by default). We fix
  8907. // this by pretending that the unqualified type was actually
  8908. // qualified __strong.
  8909. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  8910. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  8911. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  8912. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  8913. return {};
  8914. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  8915. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  8916. }
  8917. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  8918. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  8919. }
  8920. return {};
  8921. }
  8922. // Okay, qualifiers are equal.
  8923. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  8924. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  8925. // We want to consider the two function types to be the same for these
  8926. // comparisons, just force one to the other.
  8927. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  8928. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  8929. // Same as above for arrays
  8930. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  8931. LHSClass = Type::ConstantArray;
  8932. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  8933. RHSClass = Type::ConstantArray;
  8934. // ObjCInterfaces are just specialized ObjCObjects.
  8935. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  8936. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  8937. // Canonicalize ExtVector -> Vector.
  8938. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  8939. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  8940. // If the canonical type classes don't match.
  8941. if (LHSClass != RHSClass) {
  8942. // Note that we only have special rules for turning block enum
  8943. // returns into block int returns, not vice-versa.
  8944. if (const auto *ETy = LHS->getAs<EnumType>()) {
  8945. return mergeEnumWithInteger(*this, ETy, RHS, false);
  8946. }
  8947. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  8948. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  8949. }
  8950. // allow block pointer type to match an 'id' type.
  8951. if (OfBlockPointer && !BlockReturnType) {
  8952. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  8953. return LHS;
  8954. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  8955. return RHS;
  8956. }
  8957. return {};
  8958. }
  8959. // The canonical type classes match.
  8960. switch (LHSClass) {
  8961. #define TYPE(Class, Base)
  8962. #define ABSTRACT_TYPE(Class, Base)
  8963. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  8964. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  8965. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  8966. #include "clang/AST/TypeNodes.inc"
  8967. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  8968. case Type::Auto:
  8969. case Type::DeducedTemplateSpecialization:
  8970. case Type::LValueReference:
  8971. case Type::RValueReference:
  8972. case Type::MemberPointer:
  8973. llvm_unreachable("C++ should never be in mergeTypes");
  8974. case Type::ObjCInterface:
  8975. case Type::IncompleteArray:
  8976. case Type::VariableArray:
  8977. case Type::FunctionProto:
  8978. case Type::ExtVector:
  8979. llvm_unreachable("Types are eliminated above");
  8980. case Type::Pointer:
  8981. {
  8982. // Merge two pointer types, while trying to preserve typedef info
  8983. QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
  8984. QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
  8985. if (Unqualified) {
  8986. LHSPointee = LHSPointee.getUnqualifiedType();
  8987. RHSPointee = RHSPointee.getUnqualifiedType();
  8988. }
  8989. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  8990. Unqualified);
  8991. if (ResultType.isNull())
  8992. return {};
  8993. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  8994. return LHS;
  8995. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  8996. return RHS;
  8997. return getPointerType(ResultType);
  8998. }
  8999. case Type::BlockPointer:
  9000. {
  9001. // Merge two block pointer types, while trying to preserve typedef info
  9002. QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
  9003. QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
  9004. if (Unqualified) {
  9005. LHSPointee = LHSPointee.getUnqualifiedType();
  9006. RHSPointee = RHSPointee.getUnqualifiedType();
  9007. }
  9008. if (getLangOpts().OpenCL) {
  9009. Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
  9010. Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
  9011. // Blocks can't be an expression in a ternary operator (OpenCL v2.0
  9012. // 6.12.5) thus the following check is asymmetric.
  9013. if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
  9014. return {};
  9015. LHSPteeQual.removeAddressSpace();
  9016. RHSPteeQual.removeAddressSpace();
  9017. LHSPointee =
  9018. QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
  9019. RHSPointee =
  9020. QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
  9021. }
  9022. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  9023. Unqualified);
  9024. if (ResultType.isNull())
  9025. return {};
  9026. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  9027. return LHS;
  9028. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  9029. return RHS;
  9030. return getBlockPointerType(ResultType);
  9031. }
  9032. case Type::Atomic:
  9033. {
  9034. // Merge two pointer types, while trying to preserve typedef info
  9035. QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
  9036. QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
  9037. if (Unqualified) {
  9038. LHSValue = LHSValue.getUnqualifiedType();
  9039. RHSValue = RHSValue.getUnqualifiedType();
  9040. }
  9041. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  9042. Unqualified);
  9043. if (ResultType.isNull())
  9044. return {};
  9045. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  9046. return LHS;
  9047. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  9048. return RHS;
  9049. return getAtomicType(ResultType);
  9050. }
  9051. case Type::ConstantArray:
  9052. {
  9053. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  9054. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  9055. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  9056. return {};
  9057. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  9058. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  9059. if (Unqualified) {
  9060. LHSElem = LHSElem.getUnqualifiedType();
  9061. RHSElem = RHSElem.getUnqualifiedType();
  9062. }
  9063. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  9064. if (ResultType.isNull())
  9065. return {};
  9066. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  9067. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  9068. // If either side is a variable array, and both are complete, check whether
  9069. // the current dimension is definite.
  9070. if (LVAT || RVAT) {
  9071. auto SizeFetch = [this](const VariableArrayType* VAT,
  9072. const ConstantArrayType* CAT)
  9073. -> std::pair<bool,llvm::APInt> {
  9074. if (VAT) {
  9075. Optional<llvm::APSInt> TheInt;
  9076. Expr *E = VAT->getSizeExpr();
  9077. if (E && (TheInt = E->getIntegerConstantExpr(*this)))
  9078. return std::make_pair(true, *TheInt);
  9079. return std::make_pair(false, llvm::APSInt());
  9080. }
  9081. if (CAT)
  9082. return std::make_pair(true, CAT->getSize());
  9083. return std::make_pair(false, llvm::APInt());
  9084. };
  9085. bool HaveLSize, HaveRSize;
  9086. llvm::APInt LSize, RSize;
  9087. std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
  9088. std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
  9089. if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
  9090. return {}; // Definite, but unequal, array dimension
  9091. }
  9092. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  9093. return LHS;
  9094. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  9095. return RHS;
  9096. if (LCAT)
  9097. return getConstantArrayType(ResultType, LCAT->getSize(),
  9098. LCAT->getSizeExpr(),
  9099. ArrayType::ArraySizeModifier(), 0);
  9100. if (RCAT)
  9101. return getConstantArrayType(ResultType, RCAT->getSize(),
  9102. RCAT->getSizeExpr(),
  9103. ArrayType::ArraySizeModifier(), 0);
  9104. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  9105. return LHS;
  9106. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  9107. return RHS;
  9108. if (LVAT) {
  9109. // FIXME: This isn't correct! But tricky to implement because
  9110. // the array's size has to be the size of LHS, but the type
  9111. // has to be different.
  9112. return LHS;
  9113. }
  9114. if (RVAT) {
  9115. // FIXME: This isn't correct! But tricky to implement because
  9116. // the array's size has to be the size of RHS, but the type
  9117. // has to be different.
  9118. return RHS;
  9119. }
  9120. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  9121. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  9122. return getIncompleteArrayType(ResultType,
  9123. ArrayType::ArraySizeModifier(), 0);
  9124. }
  9125. case Type::FunctionNoProto:
  9126. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
  9127. case Type::Record:
  9128. case Type::Enum:
  9129. return {};
  9130. case Type::Builtin:
  9131. // Only exactly equal builtin types are compatible, which is tested above.
  9132. return {};
  9133. case Type::Complex:
  9134. // Distinct complex types are incompatible.
  9135. return {};
  9136. case Type::Vector:
  9137. // FIXME: The merged type should be an ExtVector!
  9138. if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
  9139. RHSCan->castAs<VectorType>()))
  9140. return LHS;
  9141. return {};
  9142. case Type::ConstantMatrix:
  9143. if (areCompatMatrixTypes(LHSCan->castAs<ConstantMatrixType>(),
  9144. RHSCan->castAs<ConstantMatrixType>()))
  9145. return LHS;
  9146. return {};
  9147. case Type::ObjCObject: {
  9148. // Check if the types are assignment compatible.
  9149. // FIXME: This should be type compatibility, e.g. whether
  9150. // "LHS x; RHS x;" at global scope is legal.
  9151. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
  9152. RHS->castAs<ObjCObjectType>()))
  9153. return LHS;
  9154. return {};
  9155. }
  9156. case Type::ObjCObjectPointer:
  9157. if (OfBlockPointer) {
  9158. if (canAssignObjCInterfacesInBlockPointer(
  9159. LHS->castAs<ObjCObjectPointerType>(),
  9160. RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
  9161. return LHS;
  9162. return {};
  9163. }
  9164. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
  9165. RHS->castAs<ObjCObjectPointerType>()))
  9166. return LHS;
  9167. return {};
  9168. case Type::Pipe:
  9169. assert(LHS != RHS &&
  9170. "Equivalent pipe types should have already been handled!");
  9171. return {};
  9172. case Type::BitInt: {
  9173. // Merge two bit-precise int types, while trying to preserve typedef info.
  9174. bool LHSUnsigned = LHS->castAs<BitIntType>()->isUnsigned();
  9175. bool RHSUnsigned = RHS->castAs<BitIntType>()->isUnsigned();
  9176. unsigned LHSBits = LHS->castAs<BitIntType>()->getNumBits();
  9177. unsigned RHSBits = RHS->castAs<BitIntType>()->getNumBits();
  9178. // Like unsigned/int, shouldn't have a type if they don't match.
  9179. if (LHSUnsigned != RHSUnsigned)
  9180. return {};
  9181. if (LHSBits != RHSBits)
  9182. return {};
  9183. return LHS;
  9184. }
  9185. }
  9186. llvm_unreachable("Invalid Type::Class!");
  9187. }
  9188. bool ASTContext::mergeExtParameterInfo(
  9189. const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
  9190. bool &CanUseFirst, bool &CanUseSecond,
  9191. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
  9192. assert(NewParamInfos.empty() && "param info list not empty");
  9193. CanUseFirst = CanUseSecond = true;
  9194. bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
  9195. bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
  9196. // Fast path: if the first type doesn't have ext parameter infos,
  9197. // we match if and only if the second type also doesn't have them.
  9198. if (!FirstHasInfo && !SecondHasInfo)
  9199. return true;
  9200. bool NeedParamInfo = false;
  9201. size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
  9202. : SecondFnType->getExtParameterInfos().size();
  9203. for (size_t I = 0; I < E; ++I) {
  9204. FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
  9205. if (FirstHasInfo)
  9206. FirstParam = FirstFnType->getExtParameterInfo(I);
  9207. if (SecondHasInfo)
  9208. SecondParam = SecondFnType->getExtParameterInfo(I);
  9209. // Cannot merge unless everything except the noescape flag matches.
  9210. if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
  9211. return false;
  9212. bool FirstNoEscape = FirstParam.isNoEscape();
  9213. bool SecondNoEscape = SecondParam.isNoEscape();
  9214. bool IsNoEscape = FirstNoEscape && SecondNoEscape;
  9215. NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
  9216. if (NewParamInfos.back().getOpaqueValue())
  9217. NeedParamInfo = true;
  9218. if (FirstNoEscape != IsNoEscape)
  9219. CanUseFirst = false;
  9220. if (SecondNoEscape != IsNoEscape)
  9221. CanUseSecond = false;
  9222. }
  9223. if (!NeedParamInfo)
  9224. NewParamInfos.clear();
  9225. return true;
  9226. }
  9227. void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
  9228. ObjCLayouts[CD] = nullptr;
  9229. }
  9230. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  9231. /// 'RHS' attributes and returns the merged version; including for function
  9232. /// return types.
  9233. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  9234. QualType LHSCan = getCanonicalType(LHS),
  9235. RHSCan = getCanonicalType(RHS);
  9236. // If two types are identical, they are compatible.
  9237. if (LHSCan == RHSCan)
  9238. return LHS;
  9239. if (RHSCan->isFunctionType()) {
  9240. if (!LHSCan->isFunctionType())
  9241. return {};
  9242. QualType OldReturnType =
  9243. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  9244. QualType NewReturnType =
  9245. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  9246. QualType ResReturnType =
  9247. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  9248. if (ResReturnType.isNull())
  9249. return {};
  9250. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  9251. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  9252. // In either case, use OldReturnType to build the new function type.
  9253. const auto *F = LHS->castAs<FunctionType>();
  9254. if (const auto *FPT = cast<FunctionProtoType>(F)) {
  9255. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  9256. EPI.ExtInfo = getFunctionExtInfo(LHS);
  9257. QualType ResultType =
  9258. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
  9259. return ResultType;
  9260. }
  9261. }
  9262. return {};
  9263. }
  9264. // If the qualifiers are different, the types can still be merged.
  9265. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  9266. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  9267. if (LQuals != RQuals) {
  9268. // If any of these qualifiers are different, we have a type mismatch.
  9269. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  9270. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  9271. return {};
  9272. // Exactly one GC qualifier difference is allowed: __strong is
  9273. // okay if the other type has no GC qualifier but is an Objective
  9274. // C object pointer (i.e. implicitly strong by default). We fix
  9275. // this by pretending that the unqualified type was actually
  9276. // qualified __strong.
  9277. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  9278. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  9279. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  9280. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  9281. return {};
  9282. if (GC_L == Qualifiers::Strong)
  9283. return LHS;
  9284. if (GC_R == Qualifiers::Strong)
  9285. return RHS;
  9286. return {};
  9287. }
  9288. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  9289. QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  9290. QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  9291. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  9292. if (ResQT == LHSBaseQT)
  9293. return LHS;
  9294. if (ResQT == RHSBaseQT)
  9295. return RHS;
  9296. }
  9297. return {};
  9298. }
  9299. //===----------------------------------------------------------------------===//
  9300. // Integer Predicates
  9301. //===----------------------------------------------------------------------===//
  9302. unsigned ASTContext::getIntWidth(QualType T) const {
  9303. if (const auto *ET = T->getAs<EnumType>())
  9304. T = ET->getDecl()->getIntegerType();
  9305. if (T->isBooleanType())
  9306. return 1;
  9307. if (const auto *EIT = T->getAs<BitIntType>())
  9308. return EIT->getNumBits();
  9309. // For builtin types, just use the standard type sizing method
  9310. return (unsigned)getTypeSize(T);
  9311. }
  9312. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  9313. assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
  9314. "Unexpected type");
  9315. // Turn <4 x signed int> -> <4 x unsigned int>
  9316. if (const auto *VTy = T->getAs<VectorType>())
  9317. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  9318. VTy->getNumElements(), VTy->getVectorKind());
  9319. // For _BitInt, return an unsigned _BitInt with same width.
  9320. if (const auto *EITy = T->getAs<BitIntType>())
  9321. return getBitIntType(/*Unsigned=*/true, EITy->getNumBits());
  9322. // For enums, get the underlying integer type of the enum, and let the general
  9323. // integer type signchanging code handle it.
  9324. if (const auto *ETy = T->getAs<EnumType>())
  9325. T = ETy->getDecl()->getIntegerType();
  9326. switch (T->castAs<BuiltinType>()->getKind()) {
  9327. case BuiltinType::Char_S:
  9328. case BuiltinType::SChar:
  9329. return UnsignedCharTy;
  9330. case BuiltinType::Short:
  9331. return UnsignedShortTy;
  9332. case BuiltinType::Int:
  9333. return UnsignedIntTy;
  9334. case BuiltinType::Long:
  9335. return UnsignedLongTy;
  9336. case BuiltinType::LongLong:
  9337. return UnsignedLongLongTy;
  9338. case BuiltinType::Int128:
  9339. return UnsignedInt128Ty;
  9340. // wchar_t is special. It is either signed or not, but when it's signed,
  9341. // there's no matching "unsigned wchar_t". Therefore we return the unsigned
  9342. // version of it's underlying type instead.
  9343. case BuiltinType::WChar_S:
  9344. return getUnsignedWCharType();
  9345. case BuiltinType::ShortAccum:
  9346. return UnsignedShortAccumTy;
  9347. case BuiltinType::Accum:
  9348. return UnsignedAccumTy;
  9349. case BuiltinType::LongAccum:
  9350. return UnsignedLongAccumTy;
  9351. case BuiltinType::SatShortAccum:
  9352. return SatUnsignedShortAccumTy;
  9353. case BuiltinType::SatAccum:
  9354. return SatUnsignedAccumTy;
  9355. case BuiltinType::SatLongAccum:
  9356. return SatUnsignedLongAccumTy;
  9357. case BuiltinType::ShortFract:
  9358. return UnsignedShortFractTy;
  9359. case BuiltinType::Fract:
  9360. return UnsignedFractTy;
  9361. case BuiltinType::LongFract:
  9362. return UnsignedLongFractTy;
  9363. case BuiltinType::SatShortFract:
  9364. return SatUnsignedShortFractTy;
  9365. case BuiltinType::SatFract:
  9366. return SatUnsignedFractTy;
  9367. case BuiltinType::SatLongFract:
  9368. return SatUnsignedLongFractTy;
  9369. default:
  9370. llvm_unreachable("Unexpected signed integer or fixed point type");
  9371. }
  9372. }
  9373. QualType ASTContext::getCorrespondingSignedType(QualType T) const {
  9374. assert((T->hasUnsignedIntegerRepresentation() ||
  9375. T->isUnsignedFixedPointType()) &&
  9376. "Unexpected type");
  9377. // Turn <4 x unsigned int> -> <4 x signed int>
  9378. if (const auto *VTy = T->getAs<VectorType>())
  9379. return getVectorType(getCorrespondingSignedType(VTy->getElementType()),
  9380. VTy->getNumElements(), VTy->getVectorKind());
  9381. // For _BitInt, return a signed _BitInt with same width.
  9382. if (const auto *EITy = T->getAs<BitIntType>())
  9383. return getBitIntType(/*Unsigned=*/false, EITy->getNumBits());
  9384. // For enums, get the underlying integer type of the enum, and let the general
  9385. // integer type signchanging code handle it.
  9386. if (const auto *ETy = T->getAs<EnumType>())
  9387. T = ETy->getDecl()->getIntegerType();
  9388. switch (T->castAs<BuiltinType>()->getKind()) {
  9389. case BuiltinType::Char_U:
  9390. case BuiltinType::UChar:
  9391. return SignedCharTy;
  9392. case BuiltinType::UShort:
  9393. return ShortTy;
  9394. case BuiltinType::UInt:
  9395. return IntTy;
  9396. case BuiltinType::ULong:
  9397. return LongTy;
  9398. case BuiltinType::ULongLong:
  9399. return LongLongTy;
  9400. case BuiltinType::UInt128:
  9401. return Int128Ty;
  9402. // wchar_t is special. It is either unsigned or not, but when it's unsigned,
  9403. // there's no matching "signed wchar_t". Therefore we return the signed
  9404. // version of it's underlying type instead.
  9405. case BuiltinType::WChar_U:
  9406. return getSignedWCharType();
  9407. case BuiltinType::UShortAccum:
  9408. return ShortAccumTy;
  9409. case BuiltinType::UAccum:
  9410. return AccumTy;
  9411. case BuiltinType::ULongAccum:
  9412. return LongAccumTy;
  9413. case BuiltinType::SatUShortAccum:
  9414. return SatShortAccumTy;
  9415. case BuiltinType::SatUAccum:
  9416. return SatAccumTy;
  9417. case BuiltinType::SatULongAccum:
  9418. return SatLongAccumTy;
  9419. case BuiltinType::UShortFract:
  9420. return ShortFractTy;
  9421. case BuiltinType::UFract:
  9422. return FractTy;
  9423. case BuiltinType::ULongFract:
  9424. return LongFractTy;
  9425. case BuiltinType::SatUShortFract:
  9426. return SatShortFractTy;
  9427. case BuiltinType::SatUFract:
  9428. return SatFractTy;
  9429. case BuiltinType::SatULongFract:
  9430. return SatLongFractTy;
  9431. default:
  9432. llvm_unreachable("Unexpected unsigned integer or fixed point type");
  9433. }
  9434. }
  9435. ASTMutationListener::~ASTMutationListener() = default;
  9436. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  9437. QualType ReturnType) {}
  9438. //===----------------------------------------------------------------------===//
  9439. // Builtin Type Computation
  9440. //===----------------------------------------------------------------------===//
  9441. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  9442. /// pointer over the consumed characters. This returns the resultant type. If
  9443. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  9444. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  9445. /// a vector of "i*".
  9446. ///
  9447. /// RequiresICE is filled in on return to indicate whether the value is required
  9448. /// to be an Integer Constant Expression.
  9449. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  9450. ASTContext::GetBuiltinTypeError &Error,
  9451. bool &RequiresICE,
  9452. bool AllowTypeModifiers) {
  9453. // Modifiers.
  9454. int HowLong = 0;
  9455. bool Signed = false, Unsigned = false;
  9456. RequiresICE = false;
  9457. // Read the prefixed modifiers first.
  9458. bool Done = false;
  9459. #ifndef NDEBUG
  9460. bool IsSpecial = false;
  9461. #endif
  9462. while (!Done) {
  9463. switch (*Str++) {
  9464. default: Done = true; --Str; break;
  9465. case 'I':
  9466. RequiresICE = true;
  9467. break;
  9468. case 'S':
  9469. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  9470. assert(!Signed && "Can't use 'S' modifier multiple times!");
  9471. Signed = true;
  9472. break;
  9473. case 'U':
  9474. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  9475. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  9476. Unsigned = true;
  9477. break;
  9478. case 'L':
  9479. assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
  9480. assert(HowLong <= 2 && "Can't have LLLL modifier");
  9481. ++HowLong;
  9482. break;
  9483. case 'N':
  9484. // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
  9485. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9486. assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
  9487. #ifndef NDEBUG
  9488. IsSpecial = true;
  9489. #endif
  9490. if (Context.getTargetInfo().getLongWidth() == 32)
  9491. ++HowLong;
  9492. break;
  9493. case 'W':
  9494. // This modifier represents int64 type.
  9495. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9496. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  9497. #ifndef NDEBUG
  9498. IsSpecial = true;
  9499. #endif
  9500. switch (Context.getTargetInfo().getInt64Type()) {
  9501. default:
  9502. llvm_unreachable("Unexpected integer type");
  9503. case TargetInfo::SignedLong:
  9504. HowLong = 1;
  9505. break;
  9506. case TargetInfo::SignedLongLong:
  9507. HowLong = 2;
  9508. break;
  9509. }
  9510. break;
  9511. case 'Z':
  9512. // This modifier represents int32 type.
  9513. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9514. assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
  9515. #ifndef NDEBUG
  9516. IsSpecial = true;
  9517. #endif
  9518. switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
  9519. default:
  9520. llvm_unreachable("Unexpected integer type");
  9521. case TargetInfo::SignedInt:
  9522. HowLong = 0;
  9523. break;
  9524. case TargetInfo::SignedLong:
  9525. HowLong = 1;
  9526. break;
  9527. case TargetInfo::SignedLongLong:
  9528. HowLong = 2;
  9529. break;
  9530. }
  9531. break;
  9532. case 'O':
  9533. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  9534. assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
  9535. #ifndef NDEBUG
  9536. IsSpecial = true;
  9537. #endif
  9538. if (Context.getLangOpts().OpenCL)
  9539. HowLong = 1;
  9540. else
  9541. HowLong = 2;
  9542. break;
  9543. }
  9544. }
  9545. QualType Type;
  9546. // Read the base type.
  9547. switch (*Str++) {
  9548. default: llvm_unreachable("Unknown builtin type letter!");
  9549. case 'x':
  9550. assert(HowLong == 0 && !Signed && !Unsigned &&
  9551. "Bad modifiers used with 'x'!");
  9552. Type = Context.Float16Ty;
  9553. break;
  9554. case 'y':
  9555. assert(HowLong == 0 && !Signed && !Unsigned &&
  9556. "Bad modifiers used with 'y'!");
  9557. Type = Context.BFloat16Ty;
  9558. break;
  9559. case 'v':
  9560. assert(HowLong == 0 && !Signed && !Unsigned &&
  9561. "Bad modifiers used with 'v'!");
  9562. Type = Context.VoidTy;
  9563. break;
  9564. case 'h':
  9565. assert(HowLong == 0 && !Signed && !Unsigned &&
  9566. "Bad modifiers used with 'h'!");
  9567. Type = Context.HalfTy;
  9568. break;
  9569. case 'f':
  9570. assert(HowLong == 0 && !Signed && !Unsigned &&
  9571. "Bad modifiers used with 'f'!");
  9572. Type = Context.FloatTy;
  9573. break;
  9574. case 'd':
  9575. assert(HowLong < 3 && !Signed && !Unsigned &&
  9576. "Bad modifiers used with 'd'!");
  9577. if (HowLong == 1)
  9578. Type = Context.LongDoubleTy;
  9579. else if (HowLong == 2)
  9580. Type = Context.Float128Ty;
  9581. else
  9582. Type = Context.DoubleTy;
  9583. break;
  9584. case 's':
  9585. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  9586. if (Unsigned)
  9587. Type = Context.UnsignedShortTy;
  9588. else
  9589. Type = Context.ShortTy;
  9590. break;
  9591. case 'i':
  9592. if (HowLong == 3)
  9593. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  9594. else if (HowLong == 2)
  9595. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  9596. else if (HowLong == 1)
  9597. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  9598. else
  9599. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  9600. break;
  9601. case 'c':
  9602. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  9603. if (Signed)
  9604. Type = Context.SignedCharTy;
  9605. else if (Unsigned)
  9606. Type = Context.UnsignedCharTy;
  9607. else
  9608. Type = Context.CharTy;
  9609. break;
  9610. case 'b': // boolean
  9611. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  9612. Type = Context.BoolTy;
  9613. break;
  9614. case 'z': // size_t.
  9615. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  9616. Type = Context.getSizeType();
  9617. break;
  9618. case 'w': // wchar_t.
  9619. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
  9620. Type = Context.getWideCharType();
  9621. break;
  9622. case 'F':
  9623. Type = Context.getCFConstantStringType();
  9624. break;
  9625. case 'G':
  9626. Type = Context.getObjCIdType();
  9627. break;
  9628. case 'H':
  9629. Type = Context.getObjCSelType();
  9630. break;
  9631. case 'M':
  9632. Type = Context.getObjCSuperType();
  9633. break;
  9634. case 'a':
  9635. Type = Context.getBuiltinVaListType();
  9636. assert(!Type.isNull() && "builtin va list type not initialized!");
  9637. break;
  9638. case 'A':
  9639. // This is a "reference" to a va_list; however, what exactly
  9640. // this means depends on how va_list is defined. There are two
  9641. // different kinds of va_list: ones passed by value, and ones
  9642. // passed by reference. An example of a by-value va_list is
  9643. // x86, where va_list is a char*. An example of by-ref va_list
  9644. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  9645. // we want this argument to be a char*&; for x86-64, we want
  9646. // it to be a __va_list_tag*.
  9647. Type = Context.getBuiltinVaListType();
  9648. assert(!Type.isNull() && "builtin va list type not initialized!");
  9649. if (Type->isArrayType())
  9650. Type = Context.getArrayDecayedType(Type);
  9651. else
  9652. Type = Context.getLValueReferenceType(Type);
  9653. break;
  9654. case 'q': {
  9655. char *End;
  9656. unsigned NumElements = strtoul(Str, &End, 10);
  9657. assert(End != Str && "Missing vector size");
  9658. Str = End;
  9659. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  9660. RequiresICE, false);
  9661. assert(!RequiresICE && "Can't require vector ICE");
  9662. Type = Context.getScalableVectorType(ElementType, NumElements);
  9663. break;
  9664. }
  9665. case 'V': {
  9666. char *End;
  9667. unsigned NumElements = strtoul(Str, &End, 10);
  9668. assert(End != Str && "Missing vector size");
  9669. Str = End;
  9670. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  9671. RequiresICE, false);
  9672. assert(!RequiresICE && "Can't require vector ICE");
  9673. // TODO: No way to make AltiVec vectors in builtins yet.
  9674. Type = Context.getVectorType(ElementType, NumElements,
  9675. VectorType::GenericVector);
  9676. break;
  9677. }
  9678. case 'E': {
  9679. char *End;
  9680. unsigned NumElements = strtoul(Str, &End, 10);
  9681. assert(End != Str && "Missing vector size");
  9682. Str = End;
  9683. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  9684. false);
  9685. Type = Context.getExtVectorType(ElementType, NumElements);
  9686. break;
  9687. }
  9688. case 'X': {
  9689. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  9690. false);
  9691. assert(!RequiresICE && "Can't require complex ICE");
  9692. Type = Context.getComplexType(ElementType);
  9693. break;
  9694. }
  9695. case 'Y':
  9696. Type = Context.getPointerDiffType();
  9697. break;
  9698. case 'P':
  9699. Type = Context.getFILEType();
  9700. if (Type.isNull()) {
  9701. Error = ASTContext::GE_Missing_stdio;
  9702. return {};
  9703. }
  9704. break;
  9705. case 'J':
  9706. if (Signed)
  9707. Type = Context.getsigjmp_bufType();
  9708. else
  9709. Type = Context.getjmp_bufType();
  9710. if (Type.isNull()) {
  9711. Error = ASTContext::GE_Missing_setjmp;
  9712. return {};
  9713. }
  9714. break;
  9715. case 'K':
  9716. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  9717. Type = Context.getucontext_tType();
  9718. if (Type.isNull()) {
  9719. Error = ASTContext::GE_Missing_ucontext;
  9720. return {};
  9721. }
  9722. break;
  9723. case 'p':
  9724. Type = Context.getProcessIDType();
  9725. break;
  9726. }
  9727. // If there are modifiers and if we're allowed to parse them, go for it.
  9728. Done = !AllowTypeModifiers;
  9729. while (!Done) {
  9730. switch (char c = *Str++) {
  9731. default: Done = true; --Str; break;
  9732. case '*':
  9733. case '&': {
  9734. // Both pointers and references can have their pointee types
  9735. // qualified with an address space.
  9736. char *End;
  9737. unsigned AddrSpace = strtoul(Str, &End, 10);
  9738. if (End != Str) {
  9739. // Note AddrSpace == 0 is not the same as an unspecified address space.
  9740. Type = Context.getAddrSpaceQualType(
  9741. Type,
  9742. Context.getLangASForBuiltinAddressSpace(AddrSpace));
  9743. Str = End;
  9744. }
  9745. if (c == '*')
  9746. Type = Context.getPointerType(Type);
  9747. else
  9748. Type = Context.getLValueReferenceType(Type);
  9749. break;
  9750. }
  9751. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  9752. case 'C':
  9753. Type = Type.withConst();
  9754. break;
  9755. case 'D':
  9756. Type = Context.getVolatileType(Type);
  9757. break;
  9758. case 'R':
  9759. Type = Type.withRestrict();
  9760. break;
  9761. }
  9762. }
  9763. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  9764. "Integer constant 'I' type must be an integer");
  9765. return Type;
  9766. }
  9767. // On some targets such as PowerPC, some of the builtins are defined with custom
  9768. // type descriptors for target-dependent types. These descriptors are decoded in
  9769. // other functions, but it may be useful to be able to fall back to default
  9770. // descriptor decoding to define builtins mixing target-dependent and target-
  9771. // independent types. This function allows decoding one type descriptor with
  9772. // default decoding.
  9773. QualType ASTContext::DecodeTypeStr(const char *&Str, const ASTContext &Context,
  9774. GetBuiltinTypeError &Error, bool &RequireICE,
  9775. bool AllowTypeModifiers) const {
  9776. return DecodeTypeFromStr(Str, Context, Error, RequireICE, AllowTypeModifiers);
  9777. }
  9778. /// GetBuiltinType - Return the type for the specified builtin.
  9779. QualType ASTContext::GetBuiltinType(unsigned Id,
  9780. GetBuiltinTypeError &Error,
  9781. unsigned *IntegerConstantArgs) const {
  9782. const char *TypeStr = BuiltinInfo.getTypeString(Id);
  9783. if (TypeStr[0] == '\0') {
  9784. Error = GE_Missing_type;
  9785. return {};
  9786. }
  9787. SmallVector<QualType, 8> ArgTypes;
  9788. bool RequiresICE = false;
  9789. Error = GE_None;
  9790. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  9791. RequiresICE, true);
  9792. if (Error != GE_None)
  9793. return {};
  9794. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  9795. while (TypeStr[0] && TypeStr[0] != '.') {
  9796. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  9797. if (Error != GE_None)
  9798. return {};
  9799. // If this argument is required to be an IntegerConstantExpression and the
  9800. // caller cares, fill in the bitmask we return.
  9801. if (RequiresICE && IntegerConstantArgs)
  9802. *IntegerConstantArgs |= 1 << ArgTypes.size();
  9803. // Do array -> pointer decay. The builtin should use the decayed type.
  9804. if (Ty->isArrayType())
  9805. Ty = getArrayDecayedType(Ty);
  9806. ArgTypes.push_back(Ty);
  9807. }
  9808. if (Id == Builtin::BI__GetExceptionInfo)
  9809. return {};
  9810. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  9811. "'.' should only occur at end of builtin type list!");
  9812. bool Variadic = (TypeStr[0] == '.');
  9813. FunctionType::ExtInfo EI(getDefaultCallingConvention(
  9814. Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
  9815. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  9816. // We really shouldn't be making a no-proto type here.
  9817. if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
  9818. return getFunctionNoProtoType(ResType, EI);
  9819. FunctionProtoType::ExtProtoInfo EPI;
  9820. EPI.ExtInfo = EI;
  9821. EPI.Variadic = Variadic;
  9822. if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
  9823. EPI.ExceptionSpec.Type =
  9824. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  9825. return getFunctionType(ResType, ArgTypes, EPI);
  9826. }
  9827. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  9828. const FunctionDecl *FD) {
  9829. if (!FD->isExternallyVisible())
  9830. return GVA_Internal;
  9831. // Non-user-provided functions get emitted as weak definitions with every
  9832. // use, no matter whether they've been explicitly instantiated etc.
  9833. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  9834. if (!MD->isUserProvided())
  9835. return GVA_DiscardableODR;
  9836. GVALinkage External;
  9837. switch (FD->getTemplateSpecializationKind()) {
  9838. case TSK_Undeclared:
  9839. case TSK_ExplicitSpecialization:
  9840. External = GVA_StrongExternal;
  9841. break;
  9842. case TSK_ExplicitInstantiationDefinition:
  9843. return GVA_StrongODR;
  9844. // C++11 [temp.explicit]p10:
  9845. // [ Note: The intent is that an inline function that is the subject of
  9846. // an explicit instantiation declaration will still be implicitly
  9847. // instantiated when used so that the body can be considered for
  9848. // inlining, but that no out-of-line copy of the inline function would be
  9849. // generated in the translation unit. -- end note ]
  9850. case TSK_ExplicitInstantiationDeclaration:
  9851. return GVA_AvailableExternally;
  9852. case TSK_ImplicitInstantiation:
  9853. External = GVA_DiscardableODR;
  9854. break;
  9855. }
  9856. if (!FD->isInlined())
  9857. return External;
  9858. if ((!Context.getLangOpts().CPlusPlus &&
  9859. !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  9860. !FD->hasAttr<DLLExportAttr>()) ||
  9861. FD->hasAttr<GNUInlineAttr>()) {
  9862. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  9863. // GNU or C99 inline semantics. Determine whether this symbol should be
  9864. // externally visible.
  9865. if (FD->isInlineDefinitionExternallyVisible())
  9866. return External;
  9867. // C99 inline semantics, where the symbol is not externally visible.
  9868. return GVA_AvailableExternally;
  9869. }
  9870. // Functions specified with extern and inline in -fms-compatibility mode
  9871. // forcibly get emitted. While the body of the function cannot be later
  9872. // replaced, the function definition cannot be discarded.
  9873. if (FD->isMSExternInline())
  9874. return GVA_StrongODR;
  9875. return GVA_DiscardableODR;
  9876. }
  9877. static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
  9878. const Decl *D, GVALinkage L) {
  9879. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  9880. // dllexport/dllimport on inline functions.
  9881. if (D->hasAttr<DLLImportAttr>()) {
  9882. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  9883. return GVA_AvailableExternally;
  9884. } else if (D->hasAttr<DLLExportAttr>()) {
  9885. if (L == GVA_DiscardableODR)
  9886. return GVA_StrongODR;
  9887. } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice) {
  9888. // Device-side functions with __global__ attribute must always be
  9889. // visible externally so they can be launched from host.
  9890. if (D->hasAttr<CUDAGlobalAttr>() &&
  9891. (L == GVA_DiscardableODR || L == GVA_Internal))
  9892. return GVA_StrongODR;
  9893. // Single source offloading languages like CUDA/HIP need to be able to
  9894. // access static device variables from host code of the same compilation
  9895. // unit. This is done by externalizing the static variable with a shared
  9896. // name between the host and device compilation which is the same for the
  9897. // same compilation unit whereas different among different compilation
  9898. // units.
  9899. if (Context.shouldExternalizeStaticVar(D))
  9900. return GVA_StrongExternal;
  9901. }
  9902. return L;
  9903. }
  9904. /// Adjust the GVALinkage for a declaration based on what an external AST source
  9905. /// knows about whether there can be other definitions of this declaration.
  9906. static GVALinkage
  9907. adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
  9908. GVALinkage L) {
  9909. ExternalASTSource *Source = Ctx.getExternalSource();
  9910. if (!Source)
  9911. return L;
  9912. switch (Source->hasExternalDefinitions(D)) {
  9913. case ExternalASTSource::EK_Never:
  9914. // Other translation units rely on us to provide the definition.
  9915. if (L == GVA_DiscardableODR)
  9916. return GVA_StrongODR;
  9917. break;
  9918. case ExternalASTSource::EK_Always:
  9919. return GVA_AvailableExternally;
  9920. case ExternalASTSource::EK_ReplyHazy:
  9921. break;
  9922. }
  9923. return L;
  9924. }
  9925. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  9926. return adjustGVALinkageForExternalDefinitionKind(*this, FD,
  9927. adjustGVALinkageForAttributes(*this, FD,
  9928. basicGVALinkageForFunction(*this, FD)));
  9929. }
  9930. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  9931. const VarDecl *VD) {
  9932. if (!VD->isExternallyVisible())
  9933. return GVA_Internal;
  9934. if (VD->isStaticLocal()) {
  9935. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  9936. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  9937. LexicalContext = LexicalContext->getLexicalParent();
  9938. // ObjC Blocks can create local variables that don't have a FunctionDecl
  9939. // LexicalContext.
  9940. if (!LexicalContext)
  9941. return GVA_DiscardableODR;
  9942. // Otherwise, let the static local variable inherit its linkage from the
  9943. // nearest enclosing function.
  9944. auto StaticLocalLinkage =
  9945. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  9946. // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
  9947. // be emitted in any object with references to the symbol for the object it
  9948. // contains, whether inline or out-of-line."
  9949. // Similar behavior is observed with MSVC. An alternative ABI could use
  9950. // StrongODR/AvailableExternally to match the function, but none are
  9951. // known/supported currently.
  9952. if (StaticLocalLinkage == GVA_StrongODR ||
  9953. StaticLocalLinkage == GVA_AvailableExternally)
  9954. return GVA_DiscardableODR;
  9955. return StaticLocalLinkage;
  9956. }
  9957. // MSVC treats in-class initialized static data members as definitions.
  9958. // By giving them non-strong linkage, out-of-line definitions won't
  9959. // cause link errors.
  9960. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  9961. return GVA_DiscardableODR;
  9962. // Most non-template variables have strong linkage; inline variables are
  9963. // linkonce_odr or (occasionally, for compatibility) weak_odr.
  9964. GVALinkage StrongLinkage;
  9965. switch (Context.getInlineVariableDefinitionKind(VD)) {
  9966. case ASTContext::InlineVariableDefinitionKind::None:
  9967. StrongLinkage = GVA_StrongExternal;
  9968. break;
  9969. case ASTContext::InlineVariableDefinitionKind::Weak:
  9970. case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
  9971. StrongLinkage = GVA_DiscardableODR;
  9972. break;
  9973. case ASTContext::InlineVariableDefinitionKind::Strong:
  9974. StrongLinkage = GVA_StrongODR;
  9975. break;
  9976. }
  9977. switch (VD->getTemplateSpecializationKind()) {
  9978. case TSK_Undeclared:
  9979. return StrongLinkage;
  9980. case TSK_ExplicitSpecialization:
  9981. return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  9982. VD->isStaticDataMember()
  9983. ? GVA_StrongODR
  9984. : StrongLinkage;
  9985. case TSK_ExplicitInstantiationDefinition:
  9986. return GVA_StrongODR;
  9987. case TSK_ExplicitInstantiationDeclaration:
  9988. return GVA_AvailableExternally;
  9989. case TSK_ImplicitInstantiation:
  9990. return GVA_DiscardableODR;
  9991. }
  9992. llvm_unreachable("Invalid Linkage!");
  9993. }
  9994. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  9995. return adjustGVALinkageForExternalDefinitionKind(*this, VD,
  9996. adjustGVALinkageForAttributes(*this, VD,
  9997. basicGVALinkageForVariable(*this, VD)));
  9998. }
  9999. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  10000. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  10001. if (!VD->isFileVarDecl())
  10002. return false;
  10003. // Global named register variables (GNU extension) are never emitted.
  10004. if (VD->getStorageClass() == SC_Register)
  10005. return false;
  10006. if (VD->getDescribedVarTemplate() ||
  10007. isa<VarTemplatePartialSpecializationDecl>(VD))
  10008. return false;
  10009. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  10010. // We never need to emit an uninstantiated function template.
  10011. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  10012. return false;
  10013. } else if (isa<PragmaCommentDecl>(D))
  10014. return true;
  10015. else if (isa<PragmaDetectMismatchDecl>(D))
  10016. return true;
  10017. else if (isa<OMPRequiresDecl>(D))
  10018. return true;
  10019. else if (isa<OMPThreadPrivateDecl>(D))
  10020. return !D->getDeclContext()->isDependentContext();
  10021. else if (isa<OMPAllocateDecl>(D))
  10022. return !D->getDeclContext()->isDependentContext();
  10023. else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
  10024. return !D->getDeclContext()->isDependentContext();
  10025. else if (isa<ImportDecl>(D))
  10026. return true;
  10027. else
  10028. return false;
  10029. // If this is a member of a class template, we do not need to emit it.
  10030. if (D->getDeclContext()->isDependentContext())
  10031. return false;
  10032. // Weak references don't produce any output by themselves.
  10033. if (D->hasAttr<WeakRefAttr>())
  10034. return false;
  10035. // Aliases and used decls are required.
  10036. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  10037. return true;
  10038. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  10039. // Forward declarations aren't required.
  10040. if (!FD->doesThisDeclarationHaveABody())
  10041. return FD->doesDeclarationForceExternallyVisibleDefinition();
  10042. // Constructors and destructors are required.
  10043. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  10044. return true;
  10045. // The key function for a class is required. This rule only comes
  10046. // into play when inline functions can be key functions, though.
  10047. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  10048. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  10049. const CXXRecordDecl *RD = MD->getParent();
  10050. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  10051. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  10052. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  10053. return true;
  10054. }
  10055. }
  10056. }
  10057. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  10058. // static, static inline, always_inline, and extern inline functions can
  10059. // always be deferred. Normal inline functions can be deferred in C99/C++.
  10060. // Implicit template instantiations can also be deferred in C++.
  10061. return !isDiscardableGVALinkage(Linkage);
  10062. }
  10063. const auto *VD = cast<VarDecl>(D);
  10064. assert(VD->isFileVarDecl() && "Expected file scoped var");
  10065. // If the decl is marked as `declare target to`, it should be emitted for the
  10066. // host and for the device.
  10067. if (LangOpts.OpenMP &&
  10068. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  10069. return true;
  10070. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  10071. !isMSStaticDataMemberInlineDefinition(VD))
  10072. return false;
  10073. // Variables that can be needed in other TUs are required.
  10074. auto Linkage = GetGVALinkageForVariable(VD);
  10075. if (!isDiscardableGVALinkage(Linkage))
  10076. return true;
  10077. // We never need to emit a variable that is available in another TU.
  10078. if (Linkage == GVA_AvailableExternally)
  10079. return false;
  10080. // Variables that have destruction with side-effects are required.
  10081. if (VD->needsDestruction(*this))
  10082. return true;
  10083. // Variables that have initialization with side-effects are required.
  10084. if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
  10085. // We can get a value-dependent initializer during error recovery.
  10086. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  10087. return true;
  10088. // Likewise, variables with tuple-like bindings are required if their
  10089. // bindings have side-effects.
  10090. if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
  10091. for (const auto *BD : DD->bindings())
  10092. if (const auto *BindingVD = BD->getHoldingVar())
  10093. if (DeclMustBeEmitted(BindingVD))
  10094. return true;
  10095. return false;
  10096. }
  10097. void ASTContext::forEachMultiversionedFunctionVersion(
  10098. const FunctionDecl *FD,
  10099. llvm::function_ref<void(FunctionDecl *)> Pred) const {
  10100. assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
  10101. llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
  10102. FD = FD->getMostRecentDecl();
  10103. // FIXME: The order of traversal here matters and depends on the order of
  10104. // lookup results, which happens to be (mostly) oldest-to-newest, but we
  10105. // shouldn't rely on that.
  10106. for (auto *CurDecl :
  10107. FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
  10108. FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
  10109. if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
  10110. std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
  10111. SeenDecls.insert(CurFD);
  10112. Pred(CurFD);
  10113. }
  10114. }
  10115. }
  10116. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  10117. bool IsCXXMethod,
  10118. bool IsBuiltin) const {
  10119. // Pass through to the C++ ABI object
  10120. if (IsCXXMethod)
  10121. return ABI->getDefaultMethodCallConv(IsVariadic);
  10122. // Builtins ignore user-specified default calling convention and remain the
  10123. // Target's default calling convention.
  10124. if (!IsBuiltin) {
  10125. switch (LangOpts.getDefaultCallingConv()) {
  10126. case LangOptions::DCC_None:
  10127. break;
  10128. case LangOptions::DCC_CDecl:
  10129. return CC_C;
  10130. case LangOptions::DCC_FastCall:
  10131. if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
  10132. return CC_X86FastCall;
  10133. break;
  10134. case LangOptions::DCC_StdCall:
  10135. if (!IsVariadic)
  10136. return CC_X86StdCall;
  10137. break;
  10138. case LangOptions::DCC_VectorCall:
  10139. // __vectorcall cannot be applied to variadic functions.
  10140. if (!IsVariadic)
  10141. return CC_X86VectorCall;
  10142. break;
  10143. case LangOptions::DCC_RegCall:
  10144. // __regcall cannot be applied to variadic functions.
  10145. if (!IsVariadic)
  10146. return CC_X86RegCall;
  10147. break;
  10148. }
  10149. }
  10150. return Target->getDefaultCallingConv();
  10151. }
  10152. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  10153. // Pass through to the C++ ABI object
  10154. return ABI->isNearlyEmpty(RD);
  10155. }
  10156. VTableContextBase *ASTContext::getVTableContext() {
  10157. if (!VTContext.get()) {
  10158. auto ABI = Target->getCXXABI();
  10159. if (ABI.isMicrosoft())
  10160. VTContext.reset(new MicrosoftVTableContext(*this));
  10161. else {
  10162. auto ComponentLayout = getLangOpts().RelativeCXXABIVTables
  10163. ? ItaniumVTableContext::Relative
  10164. : ItaniumVTableContext::Pointer;
  10165. VTContext.reset(new ItaniumVTableContext(*this, ComponentLayout));
  10166. }
  10167. }
  10168. return VTContext.get();
  10169. }
  10170. MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
  10171. if (!T)
  10172. T = Target;
  10173. switch (T->getCXXABI().getKind()) {
  10174. case TargetCXXABI::AppleARM64:
  10175. case TargetCXXABI::Fuchsia:
  10176. case TargetCXXABI::GenericAArch64:
  10177. case TargetCXXABI::GenericItanium:
  10178. case TargetCXXABI::GenericARM:
  10179. case TargetCXXABI::GenericMIPS:
  10180. case TargetCXXABI::iOS:
  10181. case TargetCXXABI::WebAssembly:
  10182. case TargetCXXABI::WatchOS:
  10183. case TargetCXXABI::XL:
  10184. return ItaniumMangleContext::create(*this, getDiagnostics());
  10185. case TargetCXXABI::Microsoft:
  10186. return MicrosoftMangleContext::create(*this, getDiagnostics());
  10187. }
  10188. llvm_unreachable("Unsupported ABI");
  10189. }
  10190. MangleContext *ASTContext::createDeviceMangleContext(const TargetInfo &T) {
  10191. assert(T.getCXXABI().getKind() != TargetCXXABI::Microsoft &&
  10192. "Device mangle context does not support Microsoft mangling.");
  10193. switch (T.getCXXABI().getKind()) {
  10194. case TargetCXXABI::AppleARM64:
  10195. case TargetCXXABI::Fuchsia:
  10196. case TargetCXXABI::GenericAArch64:
  10197. case TargetCXXABI::GenericItanium:
  10198. case TargetCXXABI::GenericARM:
  10199. case TargetCXXABI::GenericMIPS:
  10200. case TargetCXXABI::iOS:
  10201. case TargetCXXABI::WebAssembly:
  10202. case TargetCXXABI::WatchOS:
  10203. case TargetCXXABI::XL:
  10204. return ItaniumMangleContext::create(
  10205. *this, getDiagnostics(),
  10206. [](ASTContext &, const NamedDecl *ND) -> llvm::Optional<unsigned> {
  10207. if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
  10208. return RD->getDeviceLambdaManglingNumber();
  10209. return llvm::None;
  10210. });
  10211. case TargetCXXABI::Microsoft:
  10212. return MicrosoftMangleContext::create(*this, getDiagnostics());
  10213. }
  10214. llvm_unreachable("Unsupported ABI");
  10215. }
  10216. CXXABI::~CXXABI() = default;
  10217. size_t ASTContext::getSideTableAllocatedMemory() const {
  10218. return ASTRecordLayouts.getMemorySize() +
  10219. llvm::capacity_in_bytes(ObjCLayouts) +
  10220. llvm::capacity_in_bytes(KeyFunctions) +
  10221. llvm::capacity_in_bytes(ObjCImpls) +
  10222. llvm::capacity_in_bytes(BlockVarCopyInits) +
  10223. llvm::capacity_in_bytes(DeclAttrs) +
  10224. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  10225. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  10226. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  10227. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  10228. llvm::capacity_in_bytes(OverriddenMethods) +
  10229. llvm::capacity_in_bytes(Types) +
  10230. llvm::capacity_in_bytes(VariableArrayTypes);
  10231. }
  10232. /// getIntTypeForBitwidth -
  10233. /// sets integer QualTy according to specified details:
  10234. /// bitwidth, signed/unsigned.
  10235. /// Returns empty type if there is no appropriate target types.
  10236. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  10237. unsigned Signed) const {
  10238. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  10239. CanQualType QualTy = getFromTargetType(Ty);
  10240. if (!QualTy && DestWidth == 128)
  10241. return Signed ? Int128Ty : UnsignedInt128Ty;
  10242. return QualTy;
  10243. }
  10244. /// getRealTypeForBitwidth -
  10245. /// sets floating point QualTy according to specified bitwidth.
  10246. /// Returns empty type if there is no appropriate target types.
  10247. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth,
  10248. FloatModeKind ExplicitType) const {
  10249. FloatModeKind Ty =
  10250. getTargetInfo().getRealTypeByWidth(DestWidth, ExplicitType);
  10251. switch (Ty) {
  10252. case FloatModeKind::Float:
  10253. return FloatTy;
  10254. case FloatModeKind::Double:
  10255. return DoubleTy;
  10256. case FloatModeKind::LongDouble:
  10257. return LongDoubleTy;
  10258. case FloatModeKind::Float128:
  10259. return Float128Ty;
  10260. case FloatModeKind::Ibm128:
  10261. return Ibm128Ty;
  10262. case FloatModeKind::NoFloat:
  10263. return {};
  10264. }
  10265. llvm_unreachable("Unhandled TargetInfo::RealType value");
  10266. }
  10267. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  10268. if (Number > 1)
  10269. MangleNumbers[ND] = Number;
  10270. }
  10271. unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
  10272. auto I = MangleNumbers.find(ND);
  10273. return I != MangleNumbers.end() ? I->second : 1;
  10274. }
  10275. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  10276. if (Number > 1)
  10277. StaticLocalNumbers[VD] = Number;
  10278. }
  10279. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  10280. auto I = StaticLocalNumbers.find(VD);
  10281. return I != StaticLocalNumbers.end() ? I->second : 1;
  10282. }
  10283. MangleNumberingContext &
  10284. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  10285. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  10286. std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
  10287. if (!MCtx)
  10288. MCtx = createMangleNumberingContext();
  10289. return *MCtx;
  10290. }
  10291. MangleNumberingContext &
  10292. ASTContext::getManglingNumberContext(NeedExtraManglingDecl_t, const Decl *D) {
  10293. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  10294. std::unique_ptr<MangleNumberingContext> &MCtx =
  10295. ExtraMangleNumberingContexts[D];
  10296. if (!MCtx)
  10297. MCtx = createMangleNumberingContext();
  10298. return *MCtx;
  10299. }
  10300. std::unique_ptr<MangleNumberingContext>
  10301. ASTContext::createMangleNumberingContext() const {
  10302. return ABI->createMangleNumberingContext();
  10303. }
  10304. const CXXConstructorDecl *
  10305. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  10306. return ABI->getCopyConstructorForExceptionObject(
  10307. cast<CXXRecordDecl>(RD->getFirstDecl()));
  10308. }
  10309. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  10310. CXXConstructorDecl *CD) {
  10311. return ABI->addCopyConstructorForExceptionObject(
  10312. cast<CXXRecordDecl>(RD->getFirstDecl()),
  10313. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  10314. }
  10315. void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
  10316. TypedefNameDecl *DD) {
  10317. return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
  10318. }
  10319. TypedefNameDecl *
  10320. ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
  10321. return ABI->getTypedefNameForUnnamedTagDecl(TD);
  10322. }
  10323. void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
  10324. DeclaratorDecl *DD) {
  10325. return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
  10326. }
  10327. DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
  10328. return ABI->getDeclaratorForUnnamedTagDecl(TD);
  10329. }
  10330. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  10331. ParamIndices[D] = index;
  10332. }
  10333. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  10334. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  10335. assert(I != ParamIndices.end() &&
  10336. "ParmIndices lacks entry set by ParmVarDecl");
  10337. return I->second;
  10338. }
  10339. QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
  10340. unsigned Length) const {
  10341. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  10342. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  10343. EltTy = EltTy.withConst();
  10344. EltTy = adjustStringLiteralBaseType(EltTy);
  10345. // Get an array type for the string, according to C99 6.4.5. This includes
  10346. // the null terminator character.
  10347. return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
  10348. ArrayType::Normal, /*IndexTypeQuals*/ 0);
  10349. }
  10350. StringLiteral *
  10351. ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
  10352. StringLiteral *&Result = StringLiteralCache[Key];
  10353. if (!Result)
  10354. Result = StringLiteral::Create(
  10355. *this, Key, StringLiteral::Ascii,
  10356. /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
  10357. SourceLocation());
  10358. return Result;
  10359. }
  10360. MSGuidDecl *
  10361. ASTContext::getMSGuidDecl(MSGuidDecl::Parts Parts) const {
  10362. assert(MSGuidTagDecl && "building MS GUID without MS extensions?");
  10363. llvm::FoldingSetNodeID ID;
  10364. MSGuidDecl::Profile(ID, Parts);
  10365. void *InsertPos;
  10366. if (MSGuidDecl *Existing = MSGuidDecls.FindNodeOrInsertPos(ID, InsertPos))
  10367. return Existing;
  10368. QualType GUIDType = getMSGuidType().withConst();
  10369. MSGuidDecl *New = MSGuidDecl::Create(*this, GUIDType, Parts);
  10370. MSGuidDecls.InsertNode(New, InsertPos);
  10371. return New;
  10372. }
  10373. TemplateParamObjectDecl *
  10374. ASTContext::getTemplateParamObjectDecl(QualType T, const APValue &V) const {
  10375. assert(T->isRecordType() && "template param object of unexpected type");
  10376. // C++ [temp.param]p8:
  10377. // [...] a static storage duration object of type 'const T' [...]
  10378. T.addConst();
  10379. llvm::FoldingSetNodeID ID;
  10380. TemplateParamObjectDecl::Profile(ID, T, V);
  10381. void *InsertPos;
  10382. if (TemplateParamObjectDecl *Existing =
  10383. TemplateParamObjectDecls.FindNodeOrInsertPos(ID, InsertPos))
  10384. return Existing;
  10385. TemplateParamObjectDecl *New = TemplateParamObjectDecl::Create(*this, T, V);
  10386. TemplateParamObjectDecls.InsertNode(New, InsertPos);
  10387. return New;
  10388. }
  10389. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  10390. const llvm::Triple &T = getTargetInfo().getTriple();
  10391. if (!T.isOSDarwin())
  10392. return false;
  10393. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  10394. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  10395. return false;
  10396. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  10397. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  10398. uint64_t Size = sizeChars.getQuantity();
  10399. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  10400. unsigned Align = alignChars.getQuantity();
  10401. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  10402. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  10403. }
  10404. bool
  10405. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  10406. const ObjCMethodDecl *MethodImpl) {
  10407. // No point trying to match an unavailable/deprecated mothod.
  10408. if (MethodDecl->hasAttr<UnavailableAttr>()
  10409. || MethodDecl->hasAttr<DeprecatedAttr>())
  10410. return false;
  10411. if (MethodDecl->getObjCDeclQualifier() !=
  10412. MethodImpl->getObjCDeclQualifier())
  10413. return false;
  10414. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  10415. return false;
  10416. if (MethodDecl->param_size() != MethodImpl->param_size())
  10417. return false;
  10418. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  10419. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  10420. EF = MethodDecl->param_end();
  10421. IM != EM && IF != EF; ++IM, ++IF) {
  10422. const ParmVarDecl *DeclVar = (*IF);
  10423. const ParmVarDecl *ImplVar = (*IM);
  10424. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  10425. return false;
  10426. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  10427. return false;
  10428. }
  10429. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  10430. }
  10431. uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
  10432. LangAS AS;
  10433. if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
  10434. AS = LangAS::Default;
  10435. else
  10436. AS = QT->getPointeeType().getAddressSpace();
  10437. return getTargetInfo().getNullPointerValue(AS);
  10438. }
  10439. unsigned ASTContext::getTargetAddressSpace(QualType T) const {
  10440. return T->isFunctionType() ? getTargetInfo().getProgramAddressSpace()
  10441. : getTargetAddressSpace(T.getQualifiers());
  10442. }
  10443. unsigned ASTContext::getTargetAddressSpace(Qualifiers Q) const {
  10444. return getTargetAddressSpace(Q.getAddressSpace());
  10445. }
  10446. unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
  10447. if (isTargetAddressSpace(AS))
  10448. return toTargetAddressSpace(AS);
  10449. else
  10450. return (*AddrSpaceMap)[(unsigned)AS];
  10451. }
  10452. QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
  10453. assert(Ty->isFixedPointType());
  10454. if (Ty->isSaturatedFixedPointType()) return Ty;
  10455. switch (Ty->castAs<BuiltinType>()->getKind()) {
  10456. default:
  10457. llvm_unreachable("Not a fixed point type!");
  10458. case BuiltinType::ShortAccum:
  10459. return SatShortAccumTy;
  10460. case BuiltinType::Accum:
  10461. return SatAccumTy;
  10462. case BuiltinType::LongAccum:
  10463. return SatLongAccumTy;
  10464. case BuiltinType::UShortAccum:
  10465. return SatUnsignedShortAccumTy;
  10466. case BuiltinType::UAccum:
  10467. return SatUnsignedAccumTy;
  10468. case BuiltinType::ULongAccum:
  10469. return SatUnsignedLongAccumTy;
  10470. case BuiltinType::ShortFract:
  10471. return SatShortFractTy;
  10472. case BuiltinType::Fract:
  10473. return SatFractTy;
  10474. case BuiltinType::LongFract:
  10475. return SatLongFractTy;
  10476. case BuiltinType::UShortFract:
  10477. return SatUnsignedShortFractTy;
  10478. case BuiltinType::UFract:
  10479. return SatUnsignedFractTy;
  10480. case BuiltinType::ULongFract:
  10481. return SatUnsignedLongFractTy;
  10482. }
  10483. }
  10484. LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
  10485. if (LangOpts.OpenCL)
  10486. return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
  10487. if (LangOpts.CUDA)
  10488. return getTargetInfo().getCUDABuiltinAddressSpace(AS);
  10489. return getLangASFromTargetAS(AS);
  10490. }
  10491. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  10492. // doesn't include ASTContext.h
  10493. template
  10494. clang::LazyGenerationalUpdatePtr<
  10495. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  10496. clang::LazyGenerationalUpdatePtr<
  10497. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  10498. const clang::ASTContext &Ctx, Decl *Value);
  10499. unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
  10500. assert(Ty->isFixedPointType());
  10501. const TargetInfo &Target = getTargetInfo();
  10502. switch (Ty->castAs<BuiltinType>()->getKind()) {
  10503. default:
  10504. llvm_unreachable("Not a fixed point type!");
  10505. case BuiltinType::ShortAccum:
  10506. case BuiltinType::SatShortAccum:
  10507. return Target.getShortAccumScale();
  10508. case BuiltinType::Accum:
  10509. case BuiltinType::SatAccum:
  10510. return Target.getAccumScale();
  10511. case BuiltinType::LongAccum:
  10512. case BuiltinType::SatLongAccum:
  10513. return Target.getLongAccumScale();
  10514. case BuiltinType::UShortAccum:
  10515. case BuiltinType::SatUShortAccum:
  10516. return Target.getUnsignedShortAccumScale();
  10517. case BuiltinType::UAccum:
  10518. case BuiltinType::SatUAccum:
  10519. return Target.getUnsignedAccumScale();
  10520. case BuiltinType::ULongAccum:
  10521. case BuiltinType::SatULongAccum:
  10522. return Target.getUnsignedLongAccumScale();
  10523. case BuiltinType::ShortFract:
  10524. case BuiltinType::SatShortFract:
  10525. return Target.getShortFractScale();
  10526. case BuiltinType::Fract:
  10527. case BuiltinType::SatFract:
  10528. return Target.getFractScale();
  10529. case BuiltinType::LongFract:
  10530. case BuiltinType::SatLongFract:
  10531. return Target.getLongFractScale();
  10532. case BuiltinType::UShortFract:
  10533. case BuiltinType::SatUShortFract:
  10534. return Target.getUnsignedShortFractScale();
  10535. case BuiltinType::UFract:
  10536. case BuiltinType::SatUFract:
  10537. return Target.getUnsignedFractScale();
  10538. case BuiltinType::ULongFract:
  10539. case BuiltinType::SatULongFract:
  10540. return Target.getUnsignedLongFractScale();
  10541. }
  10542. }
  10543. unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
  10544. assert(Ty->isFixedPointType());
  10545. const TargetInfo &Target = getTargetInfo();
  10546. switch (Ty->castAs<BuiltinType>()->getKind()) {
  10547. default:
  10548. llvm_unreachable("Not a fixed point type!");
  10549. case BuiltinType::ShortAccum:
  10550. case BuiltinType::SatShortAccum:
  10551. return Target.getShortAccumIBits();
  10552. case BuiltinType::Accum:
  10553. case BuiltinType::SatAccum:
  10554. return Target.getAccumIBits();
  10555. case BuiltinType::LongAccum:
  10556. case BuiltinType::SatLongAccum:
  10557. return Target.getLongAccumIBits();
  10558. case BuiltinType::UShortAccum:
  10559. case BuiltinType::SatUShortAccum:
  10560. return Target.getUnsignedShortAccumIBits();
  10561. case BuiltinType::UAccum:
  10562. case BuiltinType::SatUAccum:
  10563. return Target.getUnsignedAccumIBits();
  10564. case BuiltinType::ULongAccum:
  10565. case BuiltinType::SatULongAccum:
  10566. return Target.getUnsignedLongAccumIBits();
  10567. case BuiltinType::ShortFract:
  10568. case BuiltinType::SatShortFract:
  10569. case BuiltinType::Fract:
  10570. case BuiltinType::SatFract:
  10571. case BuiltinType::LongFract:
  10572. case BuiltinType::SatLongFract:
  10573. case BuiltinType::UShortFract:
  10574. case BuiltinType::SatUShortFract:
  10575. case BuiltinType::UFract:
  10576. case BuiltinType::SatUFract:
  10577. case BuiltinType::ULongFract:
  10578. case BuiltinType::SatULongFract:
  10579. return 0;
  10580. }
  10581. }
  10582. llvm::FixedPointSemantics
  10583. ASTContext::getFixedPointSemantics(QualType Ty) const {
  10584. assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
  10585. "Can only get the fixed point semantics for a "
  10586. "fixed point or integer type.");
  10587. if (Ty->isIntegerType())
  10588. return llvm::FixedPointSemantics::GetIntegerSemantics(
  10589. getIntWidth(Ty), Ty->isSignedIntegerType());
  10590. bool isSigned = Ty->isSignedFixedPointType();
  10591. return llvm::FixedPointSemantics(
  10592. static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
  10593. Ty->isSaturatedFixedPointType(),
  10594. !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
  10595. }
  10596. llvm::APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
  10597. assert(Ty->isFixedPointType());
  10598. return llvm::APFixedPoint::getMax(getFixedPointSemantics(Ty));
  10599. }
  10600. llvm::APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
  10601. assert(Ty->isFixedPointType());
  10602. return llvm::APFixedPoint::getMin(getFixedPointSemantics(Ty));
  10603. }
  10604. QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
  10605. assert(Ty->isUnsignedFixedPointType() &&
  10606. "Expected unsigned fixed point type");
  10607. switch (Ty->castAs<BuiltinType>()->getKind()) {
  10608. case BuiltinType::UShortAccum:
  10609. return ShortAccumTy;
  10610. case BuiltinType::UAccum:
  10611. return AccumTy;
  10612. case BuiltinType::ULongAccum:
  10613. return LongAccumTy;
  10614. case BuiltinType::SatUShortAccum:
  10615. return SatShortAccumTy;
  10616. case BuiltinType::SatUAccum:
  10617. return SatAccumTy;
  10618. case BuiltinType::SatULongAccum:
  10619. return SatLongAccumTy;
  10620. case BuiltinType::UShortFract:
  10621. return ShortFractTy;
  10622. case BuiltinType::UFract:
  10623. return FractTy;
  10624. case BuiltinType::ULongFract:
  10625. return LongFractTy;
  10626. case BuiltinType::SatUShortFract:
  10627. return SatShortFractTy;
  10628. case BuiltinType::SatUFract:
  10629. return SatFractTy;
  10630. case BuiltinType::SatULongFract:
  10631. return SatLongFractTy;
  10632. default:
  10633. llvm_unreachable("Unexpected unsigned fixed point type");
  10634. }
  10635. }
  10636. ParsedTargetAttr
  10637. ASTContext::filterFunctionTargetAttrs(const TargetAttr *TD) const {
  10638. assert(TD != nullptr);
  10639. ParsedTargetAttr ParsedAttr = TD->parse();
  10640. llvm::erase_if(ParsedAttr.Features, [&](const std::string &Feat) {
  10641. return !Target->isValidFeatureName(StringRef{Feat}.substr(1));
  10642. });
  10643. return ParsedAttr;
  10644. }
  10645. void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  10646. const FunctionDecl *FD) const {
  10647. if (FD)
  10648. getFunctionFeatureMap(FeatureMap, GlobalDecl().getWithDecl(FD));
  10649. else
  10650. Target->initFeatureMap(FeatureMap, getDiagnostics(),
  10651. Target->getTargetOpts().CPU,
  10652. Target->getTargetOpts().Features);
  10653. }
  10654. // Fills in the supplied string map with the set of target features for the
  10655. // passed in function.
  10656. void ASTContext::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  10657. GlobalDecl GD) const {
  10658. StringRef TargetCPU = Target->getTargetOpts().CPU;
  10659. const FunctionDecl *FD = GD.getDecl()->getAsFunction();
  10660. if (const auto *TD = FD->getAttr<TargetAttr>()) {
  10661. ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
  10662. // Make a copy of the features as passed on the command line into the
  10663. // beginning of the additional features from the function to override.
  10664. ParsedAttr.Features.insert(
  10665. ParsedAttr.Features.begin(),
  10666. Target->getTargetOpts().FeaturesAsWritten.begin(),
  10667. Target->getTargetOpts().FeaturesAsWritten.end());
  10668. if (ParsedAttr.Architecture != "" &&
  10669. Target->isValidCPUName(ParsedAttr.Architecture))
  10670. TargetCPU = ParsedAttr.Architecture;
  10671. // Now populate the feature map, first with the TargetCPU which is either
  10672. // the default or a new one from the target attribute string. Then we'll use
  10673. // the passed in features (FeaturesAsWritten) along with the new ones from
  10674. // the attribute.
  10675. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU,
  10676. ParsedAttr.Features);
  10677. } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
  10678. llvm::SmallVector<StringRef, 32> FeaturesTmp;
  10679. Target->getCPUSpecificCPUDispatchFeatures(
  10680. SD->getCPUName(GD.getMultiVersionIndex())->getName(), FeaturesTmp);
  10681. std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
  10682. Features.insert(Features.begin(),
  10683. Target->getTargetOpts().FeaturesAsWritten.begin(),
  10684. Target->getTargetOpts().FeaturesAsWritten.end());
  10685. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
  10686. } else if (const auto *TC = FD->getAttr<TargetClonesAttr>()) {
  10687. std::vector<std::string> Features;
  10688. StringRef VersionStr = TC->getFeatureStr(GD.getMultiVersionIndex());
  10689. if (VersionStr.startswith("arch="))
  10690. TargetCPU = VersionStr.drop_front(sizeof("arch=") - 1);
  10691. else if (VersionStr != "default")
  10692. Features.push_back((StringRef{"+"} + VersionStr).str());
  10693. Target->initFeatureMap(FeatureMap, getDiagnostics(), TargetCPU, Features);
  10694. } else {
  10695. FeatureMap = Target->getTargetOpts().FeatureMap;
  10696. }
  10697. }
  10698. OMPTraitInfo &ASTContext::getNewOMPTraitInfo() {
  10699. OMPTraitInfoVector.emplace_back(new OMPTraitInfo());
  10700. return *OMPTraitInfoVector.back();
  10701. }
  10702. const StreamingDiagnostic &clang::
  10703. operator<<(const StreamingDiagnostic &DB,
  10704. const ASTContext::SectionInfo &Section) {
  10705. if (Section.Decl)
  10706. return DB << Section.Decl;
  10707. return DB << "a prior #pragma section";
  10708. }
  10709. bool ASTContext::mayExternalizeStaticVar(const Decl *D) const {
  10710. bool IsStaticVar =
  10711. isa<VarDecl>(D) && cast<VarDecl>(D)->getStorageClass() == SC_Static;
  10712. bool IsExplicitDeviceVar = (D->hasAttr<CUDADeviceAttr>() &&
  10713. !D->getAttr<CUDADeviceAttr>()->isImplicit()) ||
  10714. (D->hasAttr<CUDAConstantAttr>() &&
  10715. !D->getAttr<CUDAConstantAttr>()->isImplicit());
  10716. // CUDA/HIP: static managed variables need to be externalized since it is
  10717. // a declaration in IR, therefore cannot have internal linkage. Kernels in
  10718. // anonymous name space needs to be externalized to avoid duplicate symbols.
  10719. return (IsStaticVar &&
  10720. (D->hasAttr<HIPManagedAttr>() || IsExplicitDeviceVar)) ||
  10721. (D->hasAttr<CUDAGlobalAttr>() &&
  10722. basicGVALinkageForFunction(*this, cast<FunctionDecl>(D)) ==
  10723. GVA_Internal);
  10724. }
  10725. bool ASTContext::shouldExternalizeStaticVar(const Decl *D) const {
  10726. return mayExternalizeStaticVar(D) &&
  10727. (D->hasAttr<HIPManagedAttr>() || D->hasAttr<CUDAGlobalAttr>() ||
  10728. CUDADeviceVarODRUsedByHost.count(cast<VarDecl>(D)));
  10729. }
  10730. StringRef ASTContext::getCUIDHash() const {
  10731. if (!CUIDHash.empty())
  10732. return CUIDHash;
  10733. if (LangOpts.CUID.empty())
  10734. return StringRef();
  10735. CUIDHash = llvm::utohexstr(llvm::MD5Hash(LangOpts.CUID), /*LowerCase=*/true);
  10736. return CUIDHash;
  10737. }