ASTContext.cpp 326 KB

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