ASTContext.cpp 387 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750
  1. //===- ASTContext.cpp - Context to hold long-lived AST nodes --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the ASTContext interface.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTContext.h"
  13. #include "CXXABI.h"
  14. #include "Interp/Context.h"
  15. #include "clang/AST/APValue.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/ASTTypeTraits.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/AttrIterator.h"
  20. #include "clang/AST/CharUnits.h"
  21. #include "clang/AST/Comment.h"
  22. #include "clang/AST/Decl.h"
  23. #include "clang/AST/DeclBase.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/DeclContextInternals.h"
  26. #include "clang/AST/DeclObjC.h"
  27. #include "clang/AST/DeclOpenMP.h"
  28. #include "clang/AST/DeclTemplate.h"
  29. #include "clang/AST/DeclarationName.h"
  30. #include "clang/AST/Expr.h"
  31. #include "clang/AST/ExprCXX.h"
  32. #include "clang/AST/ExternalASTSource.h"
  33. #include "clang/AST/Mangle.h"
  34. #include "clang/AST/MangleNumberingContext.h"
  35. #include "clang/AST/NestedNameSpecifier.h"
  36. #include "clang/AST/RawCommentList.h"
  37. #include "clang/AST/RecordLayout.h"
  38. #include "clang/AST/RecursiveASTVisitor.h"
  39. #include "clang/AST/Stmt.h"
  40. #include "clang/AST/TemplateBase.h"
  41. #include "clang/AST/TemplateName.h"
  42. #include "clang/AST/Type.h"
  43. #include "clang/AST/TypeLoc.h"
  44. #include "clang/AST/UnresolvedSet.h"
  45. #include "clang/AST/VTableBuilder.h"
  46. #include "clang/Basic/AddressSpaces.h"
  47. #include "clang/Basic/Builtins.h"
  48. #include "clang/Basic/CommentOptions.h"
  49. #include "clang/Basic/ExceptionSpecificationType.h"
  50. #include "clang/Basic/FixedPoint.h"
  51. #include "clang/Basic/IdentifierTable.h"
  52. #include "clang/Basic/LLVM.h"
  53. #include "clang/Basic/LangOptions.h"
  54. #include "clang/Basic/Linkage.h"
  55. #include "clang/Basic/ObjCRuntime.h"
  56. #include "clang/Basic/SanitizerBlacklist.h"
  57. #include "clang/Basic/SourceLocation.h"
  58. #include "clang/Basic/SourceManager.h"
  59. #include "clang/Basic/Specifiers.h"
  60. #include "clang/Basic/TargetCXXABI.h"
  61. #include "clang/Basic/TargetInfo.h"
  62. #include "clang/Basic/XRayLists.h"
  63. #include "llvm/ADT/APInt.h"
  64. #include "llvm/ADT/APSInt.h"
  65. #include "llvm/ADT/ArrayRef.h"
  66. #include "llvm/ADT/DenseMap.h"
  67. #include "llvm/ADT/DenseSet.h"
  68. #include "llvm/ADT/FoldingSet.h"
  69. #include "llvm/ADT/None.h"
  70. #include "llvm/ADT/Optional.h"
  71. #include "llvm/ADT/PointerUnion.h"
  72. #include "llvm/ADT/STLExtras.h"
  73. #include "llvm/ADT/SmallPtrSet.h"
  74. #include "llvm/ADT/SmallVector.h"
  75. #include "llvm/ADT/StringExtras.h"
  76. #include "llvm/ADT/StringRef.h"
  77. #include "llvm/ADT/Triple.h"
  78. #include "llvm/Support/Capacity.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/ErrorHandling.h"
  82. #include "llvm/Support/MathExtras.h"
  83. #include "llvm/Support/raw_ostream.h"
  84. #include <algorithm>
  85. #include <cassert>
  86. #include <cstddef>
  87. #include <cstdint>
  88. #include <cstdlib>
  89. #include <map>
  90. #include <memory>
  91. #include <string>
  92. #include <tuple>
  93. #include <utility>
  94. using namespace clang;
  95. enum FloatingRank {
  96. Float16Rank, HalfRank, FloatRank, DoubleRank, LongDoubleRank, Float128Rank
  97. };
  98. /// \returns location that is relevant when searching for Doc comments related
  99. /// to \p D.
  100. static SourceLocation getDeclLocForCommentSearch(const Decl *D,
  101. SourceManager &SourceMgr) {
  102. assert(D);
  103. // User can not attach documentation to implicit declarations.
  104. if (D->isImplicit())
  105. return {};
  106. // User can not attach documentation to implicit instantiations.
  107. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  108. if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  109. return {};
  110. }
  111. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  112. if (VD->isStaticDataMember() &&
  113. VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  114. return {};
  115. }
  116. if (const auto *CRD = dyn_cast<CXXRecordDecl>(D)) {
  117. if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  118. return {};
  119. }
  120. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  121. TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
  122. if (TSK == TSK_ImplicitInstantiation ||
  123. TSK == TSK_Undeclared)
  124. return {};
  125. }
  126. if (const auto *ED = dyn_cast<EnumDecl>(D)) {
  127. if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
  128. return {};
  129. }
  130. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  131. // When tag declaration (but not definition!) is part of the
  132. // decl-specifier-seq of some other declaration, it doesn't get comment
  133. if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
  134. return {};
  135. }
  136. // TODO: handle comments for function parameters properly.
  137. if (isa<ParmVarDecl>(D))
  138. return {};
  139. // TODO: we could look up template parameter documentation in the template
  140. // documentation.
  141. if (isa<TemplateTypeParmDecl>(D) ||
  142. isa<NonTypeTemplateParmDecl>(D) ||
  143. isa<TemplateTemplateParmDecl>(D))
  144. return {};
  145. // Find declaration location.
  146. // For Objective-C declarations we generally don't expect to have multiple
  147. // declarators, thus use declaration starting location as the "declaration
  148. // location".
  149. // For all other declarations multiple declarators are used quite frequently,
  150. // so we use the location of the identifier as the "declaration location".
  151. if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
  152. isa<ObjCPropertyDecl>(D) ||
  153. isa<RedeclarableTemplateDecl>(D) ||
  154. isa<ClassTemplateSpecializationDecl>(D))
  155. return D->getBeginLoc();
  156. else {
  157. const SourceLocation DeclLoc = D->getLocation();
  158. if (DeclLoc.isMacroID()) {
  159. if (isa<TypedefDecl>(D)) {
  160. // If location of the typedef name is in a macro, it is because being
  161. // declared via a macro. Try using declaration's starting location as
  162. // the "declaration location".
  163. return D->getBeginLoc();
  164. } else if (const auto *TD = dyn_cast<TagDecl>(D)) {
  165. // If location of the tag decl is inside a macro, but the spelling of
  166. // the tag name comes from a macro argument, it looks like a special
  167. // macro like NS_ENUM is being used to define the tag decl. In that
  168. // case, adjust the source location to the expansion loc so that we can
  169. // attach the comment to the tag decl.
  170. if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
  171. TD->isCompleteDefinition())
  172. return SourceMgr.getExpansionLoc(DeclLoc);
  173. }
  174. }
  175. return DeclLoc;
  176. }
  177. return {};
  178. }
  179. RawComment *ASTContext::getRawCommentForDeclNoCacheImpl(
  180. const Decl *D, const SourceLocation RepresentativeLocForDecl,
  181. const std::map<unsigned, RawComment *> &CommentsInTheFile) const {
  182. // If the declaration doesn't map directly to a location in a file, we
  183. // can't find the comment.
  184. if (RepresentativeLocForDecl.isInvalid() ||
  185. !RepresentativeLocForDecl.isFileID())
  186. return nullptr;
  187. // If there are no comments anywhere, we won't find anything.
  188. if (CommentsInTheFile.empty())
  189. return nullptr;
  190. // Decompose the location for the declaration and find the beginning of the
  191. // file buffer.
  192. const std::pair<FileID, unsigned> DeclLocDecomp =
  193. SourceMgr.getDecomposedLoc(RepresentativeLocForDecl);
  194. // Slow path.
  195. auto OffsetCommentBehindDecl =
  196. CommentsInTheFile.lower_bound(DeclLocDecomp.second);
  197. // First check whether we have a trailing comment.
  198. if (OffsetCommentBehindDecl != CommentsInTheFile.end()) {
  199. RawComment *CommentBehindDecl = OffsetCommentBehindDecl->second;
  200. if ((CommentBehindDecl->isDocumentation() ||
  201. LangOpts.CommentOpts.ParseAllComments) &&
  202. CommentBehindDecl->isTrailingComment() &&
  203. (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
  204. isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
  205. // Check that Doxygen trailing comment comes after the declaration, starts
  206. // on the same line and in the same file as the declaration.
  207. if (SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) ==
  208. Comments.getCommentBeginLine(CommentBehindDecl, DeclLocDecomp.first,
  209. OffsetCommentBehindDecl->first)) {
  210. return CommentBehindDecl;
  211. }
  212. }
  213. }
  214. // The comment just after the declaration was not a trailing comment.
  215. // Let's look at the previous comment.
  216. if (OffsetCommentBehindDecl == CommentsInTheFile.begin())
  217. return nullptr;
  218. auto OffsetCommentBeforeDecl = --OffsetCommentBehindDecl;
  219. RawComment *CommentBeforeDecl = OffsetCommentBeforeDecl->second;
  220. // Check that we actually have a non-member Doxygen comment.
  221. if (!(CommentBeforeDecl->isDocumentation() ||
  222. LangOpts.CommentOpts.ParseAllComments) ||
  223. CommentBeforeDecl->isTrailingComment())
  224. return nullptr;
  225. // Decompose the end of the comment.
  226. const unsigned CommentEndOffset =
  227. Comments.getCommentEndOffset(CommentBeforeDecl);
  228. // Get the corresponding buffer.
  229. bool Invalid = false;
  230. const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
  231. &Invalid).data();
  232. if (Invalid)
  233. return nullptr;
  234. // Extract text between the comment and declaration.
  235. StringRef Text(Buffer + CommentEndOffset,
  236. DeclLocDecomp.second - CommentEndOffset);
  237. // There should be no other declarations or preprocessor directives between
  238. // comment and declaration.
  239. if (Text.find_first_of(";{}#@") != StringRef::npos)
  240. return nullptr;
  241. return CommentBeforeDecl;
  242. }
  243. RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
  244. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  245. // If the declaration doesn't map directly to a location in a file, we
  246. // can't find the comment.
  247. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  248. return nullptr;
  249. if (ExternalSource && !CommentsLoaded) {
  250. ExternalSource->ReadComments();
  251. CommentsLoaded = true;
  252. }
  253. if (Comments.empty())
  254. return nullptr;
  255. const FileID File = SourceMgr.getDecomposedLoc(DeclLoc).first;
  256. const auto CommentsInThisFile = Comments.getCommentsInFile(File);
  257. if (!CommentsInThisFile || CommentsInThisFile->empty())
  258. return nullptr;
  259. return getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile);
  260. }
  261. /// If we have a 'templated' declaration for a template, adjust 'D' to
  262. /// refer to the actual template.
  263. /// If we have an implicit instantiation, adjust 'D' to refer to template.
  264. static const Decl &adjustDeclToTemplate(const Decl &D) {
  265. if (const auto *FD = dyn_cast<FunctionDecl>(&D)) {
  266. // Is this function declaration part of a function template?
  267. if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
  268. return *FTD;
  269. // Nothing to do if function is not an implicit instantiation.
  270. if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
  271. return D;
  272. // Function is an implicit instantiation of a function template?
  273. if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
  274. return *FTD;
  275. // Function is instantiated from a member definition of a class template?
  276. if (const FunctionDecl *MemberDecl =
  277. FD->getInstantiatedFromMemberFunction())
  278. return *MemberDecl;
  279. return D;
  280. }
  281. if (const auto *VD = dyn_cast<VarDecl>(&D)) {
  282. // Static data member is instantiated from a member definition of a class
  283. // template?
  284. if (VD->isStaticDataMember())
  285. if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
  286. return *MemberDecl;
  287. return D;
  288. }
  289. if (const auto *CRD = dyn_cast<CXXRecordDecl>(&D)) {
  290. // Is this class declaration part of a class template?
  291. if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
  292. return *CTD;
  293. // Class is an implicit instantiation of a class template or partial
  294. // specialization?
  295. if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
  296. if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
  297. return D;
  298. llvm::PointerUnion<ClassTemplateDecl *,
  299. ClassTemplatePartialSpecializationDecl *>
  300. PU = CTSD->getSpecializedTemplateOrPartial();
  301. return PU.is<ClassTemplateDecl *>()
  302. ? *static_cast<const Decl *>(PU.get<ClassTemplateDecl *>())
  303. : *static_cast<const Decl *>(
  304. PU.get<ClassTemplatePartialSpecializationDecl *>());
  305. }
  306. // Class is instantiated from a member definition of a class template?
  307. if (const MemberSpecializationInfo *Info =
  308. CRD->getMemberSpecializationInfo())
  309. return *Info->getInstantiatedFrom();
  310. return D;
  311. }
  312. if (const auto *ED = dyn_cast<EnumDecl>(&D)) {
  313. // Enum is instantiated from a member definition of a class template?
  314. if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
  315. return *MemberDecl;
  316. return D;
  317. }
  318. // FIXME: Adjust alias templates?
  319. return D;
  320. }
  321. const RawComment *ASTContext::getRawCommentForAnyRedecl(
  322. const Decl *D,
  323. const Decl **OriginalDecl) const {
  324. if (!D) {
  325. if (OriginalDecl)
  326. OriginalDecl = nullptr;
  327. return nullptr;
  328. }
  329. D = &adjustDeclToTemplate(*D);
  330. // Any comment directly attached to D?
  331. {
  332. auto DeclComment = DeclRawComments.find(D);
  333. if (DeclComment != DeclRawComments.end()) {
  334. if (OriginalDecl)
  335. *OriginalDecl = D;
  336. return DeclComment->second;
  337. }
  338. }
  339. // Any comment attached to any redeclaration of D?
  340. const Decl *CanonicalD = D->getCanonicalDecl();
  341. if (!CanonicalD)
  342. return nullptr;
  343. {
  344. auto RedeclComment = RedeclChainComments.find(CanonicalD);
  345. if (RedeclComment != RedeclChainComments.end()) {
  346. if (OriginalDecl)
  347. *OriginalDecl = RedeclComment->second;
  348. auto CommentAtRedecl = DeclRawComments.find(RedeclComment->second);
  349. assert(CommentAtRedecl != DeclRawComments.end() &&
  350. "This decl is supposed to have comment attached.");
  351. return CommentAtRedecl->second;
  352. }
  353. }
  354. // Any redeclarations of D that we haven't checked for comments yet?
  355. // We can't use DenseMap::iterator directly since it'd get invalid.
  356. auto LastCheckedRedecl = [this, CanonicalD]() -> const Decl * {
  357. auto LookupRes = CommentlessRedeclChains.find(CanonicalD);
  358. if (LookupRes != CommentlessRedeclChains.end())
  359. return LookupRes->second;
  360. return nullptr;
  361. }();
  362. for (const auto Redecl : D->redecls()) {
  363. assert(Redecl);
  364. // Skip all redeclarations that have been checked previously.
  365. if (LastCheckedRedecl) {
  366. if (LastCheckedRedecl == Redecl) {
  367. LastCheckedRedecl = nullptr;
  368. }
  369. continue;
  370. }
  371. const RawComment *RedeclComment = getRawCommentForDeclNoCache(Redecl);
  372. if (RedeclComment) {
  373. cacheRawCommentForDecl(*Redecl, *RedeclComment);
  374. if (OriginalDecl)
  375. *OriginalDecl = Redecl;
  376. return RedeclComment;
  377. }
  378. CommentlessRedeclChains[CanonicalD] = Redecl;
  379. }
  380. if (OriginalDecl)
  381. *OriginalDecl = nullptr;
  382. return nullptr;
  383. }
  384. void ASTContext::cacheRawCommentForDecl(const Decl &OriginalD,
  385. const RawComment &Comment) const {
  386. assert(Comment.isDocumentation() || LangOpts.CommentOpts.ParseAllComments);
  387. DeclRawComments.try_emplace(&OriginalD, &Comment);
  388. const Decl *const CanonicalDecl = OriginalD.getCanonicalDecl();
  389. RedeclChainComments.try_emplace(CanonicalDecl, &OriginalD);
  390. CommentlessRedeclChains.erase(CanonicalDecl);
  391. }
  392. static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
  393. SmallVectorImpl<const NamedDecl *> &Redeclared) {
  394. const DeclContext *DC = ObjCMethod->getDeclContext();
  395. if (const auto *IMD = dyn_cast<ObjCImplDecl>(DC)) {
  396. const ObjCInterfaceDecl *ID = IMD->getClassInterface();
  397. if (!ID)
  398. return;
  399. // Add redeclared method here.
  400. for (const auto *Ext : ID->known_extensions()) {
  401. if (ObjCMethodDecl *RedeclaredMethod =
  402. Ext->getMethod(ObjCMethod->getSelector(),
  403. ObjCMethod->isInstanceMethod()))
  404. Redeclared.push_back(RedeclaredMethod);
  405. }
  406. }
  407. }
  408. void ASTContext::attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
  409. const Preprocessor *PP) {
  410. if (Comments.empty() || Decls.empty())
  411. return;
  412. // See if there are any new comments that are not attached to a decl.
  413. // The location doesn't have to be precise - we care only about the file.
  414. const FileID File =
  415. SourceMgr.getDecomposedLoc((*Decls.begin())->getLocation()).first;
  416. auto CommentsInThisFile = Comments.getCommentsInFile(File);
  417. if (!CommentsInThisFile || CommentsInThisFile->empty() ||
  418. CommentsInThisFile->rbegin()->second->isAttached())
  419. return;
  420. // There is at least one comment not attached to a decl.
  421. // Maybe it should be attached to one of Decls?
  422. //
  423. // Note that this way we pick up not only comments that precede the
  424. // declaration, but also comments that *follow* the declaration -- thanks to
  425. // the lookahead in the lexer: we've consumed the semicolon and looked
  426. // ahead through comments.
  427. for (const Decl *D : Decls) {
  428. assert(D);
  429. if (D->isInvalidDecl())
  430. continue;
  431. D = &adjustDeclToTemplate(*D);
  432. const SourceLocation DeclLoc = getDeclLocForCommentSearch(D, SourceMgr);
  433. if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
  434. continue;
  435. if (DeclRawComments.count(D) > 0)
  436. continue;
  437. if (RawComment *const DocComment =
  438. getRawCommentForDeclNoCacheImpl(D, DeclLoc, *CommentsInThisFile)) {
  439. cacheRawCommentForDecl(*D, *DocComment);
  440. comments::FullComment *FC = DocComment->parse(*this, PP, D);
  441. ParsedComments[D->getCanonicalDecl()] = FC;
  442. }
  443. }
  444. }
  445. comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
  446. const Decl *D) const {
  447. auto *ThisDeclInfo = new (*this) comments::DeclInfo;
  448. ThisDeclInfo->CommentDecl = D;
  449. ThisDeclInfo->IsFilled = false;
  450. ThisDeclInfo->fill();
  451. ThisDeclInfo->CommentDecl = FC->getDecl();
  452. if (!ThisDeclInfo->TemplateParameters)
  453. ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
  454. comments::FullComment *CFC =
  455. new (*this) comments::FullComment(FC->getBlocks(),
  456. ThisDeclInfo);
  457. return CFC;
  458. }
  459. comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
  460. const RawComment *RC = getRawCommentForDeclNoCache(D);
  461. return RC ? RC->parse(*this, nullptr, D) : nullptr;
  462. }
  463. comments::FullComment *ASTContext::getCommentForDecl(
  464. const Decl *D,
  465. const Preprocessor *PP) const {
  466. if (!D || D->isInvalidDecl())
  467. return nullptr;
  468. D = &adjustDeclToTemplate(*D);
  469. const Decl *Canonical = D->getCanonicalDecl();
  470. llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
  471. ParsedComments.find(Canonical);
  472. if (Pos != ParsedComments.end()) {
  473. if (Canonical != D) {
  474. comments::FullComment *FC = Pos->second;
  475. comments::FullComment *CFC = cloneFullComment(FC, D);
  476. return CFC;
  477. }
  478. return Pos->second;
  479. }
  480. const Decl *OriginalDecl = nullptr;
  481. const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
  482. if (!RC) {
  483. if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
  484. SmallVector<const NamedDecl*, 8> Overridden;
  485. const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
  486. if (OMD && OMD->isPropertyAccessor())
  487. if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
  488. if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
  489. return cloneFullComment(FC, D);
  490. if (OMD)
  491. addRedeclaredMethods(OMD, Overridden);
  492. getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
  493. for (unsigned i = 0, e = Overridden.size(); i < e; i++)
  494. if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
  495. return cloneFullComment(FC, D);
  496. }
  497. else if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
  498. // Attach any tag type's documentation to its typedef if latter
  499. // does not have one of its own.
  500. QualType QT = TD->getUnderlyingType();
  501. if (const auto *TT = QT->getAs<TagType>())
  502. if (const Decl *TD = TT->getDecl())
  503. if (comments::FullComment *FC = getCommentForDecl(TD, PP))
  504. return cloneFullComment(FC, D);
  505. }
  506. else if (const auto *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
  507. while (IC->getSuperClass()) {
  508. IC = IC->getSuperClass();
  509. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  510. return cloneFullComment(FC, D);
  511. }
  512. }
  513. else if (const auto *CD = dyn_cast<ObjCCategoryDecl>(D)) {
  514. if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
  515. if (comments::FullComment *FC = getCommentForDecl(IC, PP))
  516. return cloneFullComment(FC, D);
  517. }
  518. else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  519. if (!(RD = RD->getDefinition()))
  520. return nullptr;
  521. // Check non-virtual bases.
  522. for (const auto &I : RD->bases()) {
  523. if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
  524. continue;
  525. QualType Ty = I.getType();
  526. if (Ty.isNull())
  527. continue;
  528. if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
  529. if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
  530. continue;
  531. if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
  532. return cloneFullComment(FC, D);
  533. }
  534. }
  535. // Check virtual bases.
  536. for (const auto &I : RD->vbases()) {
  537. if (I.getAccessSpecifier() != AS_public)
  538. continue;
  539. QualType Ty = I.getType();
  540. if (Ty.isNull())
  541. continue;
  542. if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
  543. if (!(VirtualBase= VirtualBase->getDefinition()))
  544. continue;
  545. if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
  546. return cloneFullComment(FC, D);
  547. }
  548. }
  549. }
  550. return nullptr;
  551. }
  552. // If the RawComment was attached to other redeclaration of this Decl, we
  553. // should parse the comment in context of that other Decl. This is important
  554. // because comments can contain references to parameter names which can be
  555. // different across redeclarations.
  556. if (D != OriginalDecl && OriginalDecl)
  557. return getCommentForDecl(OriginalDecl, PP);
  558. comments::FullComment *FC = RC->parse(*this, PP, D);
  559. ParsedComments[Canonical] = FC;
  560. return FC;
  561. }
  562. void
  563. ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
  564. TemplateTemplateParmDecl *Parm) {
  565. ID.AddInteger(Parm->getDepth());
  566. ID.AddInteger(Parm->getPosition());
  567. ID.AddBoolean(Parm->isParameterPack());
  568. TemplateParameterList *Params = Parm->getTemplateParameters();
  569. ID.AddInteger(Params->size());
  570. for (TemplateParameterList::const_iterator P = Params->begin(),
  571. PEnd = Params->end();
  572. P != PEnd; ++P) {
  573. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  574. ID.AddInteger(0);
  575. ID.AddBoolean(TTP->isParameterPack());
  576. continue;
  577. }
  578. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  579. ID.AddInteger(1);
  580. ID.AddBoolean(NTTP->isParameterPack());
  581. ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
  582. if (NTTP->isExpandedParameterPack()) {
  583. ID.AddBoolean(true);
  584. ID.AddInteger(NTTP->getNumExpansionTypes());
  585. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  586. QualType T = NTTP->getExpansionType(I);
  587. ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
  588. }
  589. } else
  590. ID.AddBoolean(false);
  591. continue;
  592. }
  593. auto *TTP = cast<TemplateTemplateParmDecl>(*P);
  594. ID.AddInteger(2);
  595. Profile(ID, TTP);
  596. }
  597. }
  598. TemplateTemplateParmDecl *
  599. ASTContext::getCanonicalTemplateTemplateParmDecl(
  600. TemplateTemplateParmDecl *TTP) const {
  601. // Check if we already have a canonical template template parameter.
  602. llvm::FoldingSetNodeID ID;
  603. CanonicalTemplateTemplateParm::Profile(ID, TTP);
  604. void *InsertPos = nullptr;
  605. CanonicalTemplateTemplateParm *Canonical
  606. = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  607. if (Canonical)
  608. return Canonical->getParam();
  609. // Build a canonical template parameter list.
  610. TemplateParameterList *Params = TTP->getTemplateParameters();
  611. SmallVector<NamedDecl *, 4> CanonParams;
  612. CanonParams.reserve(Params->size());
  613. for (TemplateParameterList::const_iterator P = Params->begin(),
  614. PEnd = Params->end();
  615. P != PEnd; ++P) {
  616. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
  617. CanonParams.push_back(
  618. TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
  619. SourceLocation(),
  620. SourceLocation(),
  621. TTP->getDepth(),
  622. TTP->getIndex(), nullptr, false,
  623. TTP->isParameterPack()));
  624. else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  625. QualType T = getCanonicalType(NTTP->getType());
  626. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  627. NonTypeTemplateParmDecl *Param;
  628. if (NTTP->isExpandedParameterPack()) {
  629. SmallVector<QualType, 2> ExpandedTypes;
  630. SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
  631. for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
  632. ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
  633. ExpandedTInfos.push_back(
  634. getTrivialTypeSourceInfo(ExpandedTypes.back()));
  635. }
  636. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  637. SourceLocation(),
  638. SourceLocation(),
  639. NTTP->getDepth(),
  640. NTTP->getPosition(), nullptr,
  641. T,
  642. TInfo,
  643. ExpandedTypes,
  644. ExpandedTInfos);
  645. } else {
  646. Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  647. SourceLocation(),
  648. SourceLocation(),
  649. NTTP->getDepth(),
  650. NTTP->getPosition(), nullptr,
  651. T,
  652. NTTP->isParameterPack(),
  653. TInfo);
  654. }
  655. CanonParams.push_back(Param);
  656. } else
  657. CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
  658. cast<TemplateTemplateParmDecl>(*P)));
  659. }
  660. assert(!TTP->getRequiresClause() &&
  661. "Unexpected requires-clause on template template-parameter");
  662. Expr *const CanonRequiresClause = nullptr;
  663. TemplateTemplateParmDecl *CanonTTP
  664. = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
  665. SourceLocation(), TTP->getDepth(),
  666. TTP->getPosition(),
  667. TTP->isParameterPack(),
  668. nullptr,
  669. TemplateParameterList::Create(*this, SourceLocation(),
  670. SourceLocation(),
  671. CanonParams,
  672. SourceLocation(),
  673. CanonRequiresClause));
  674. // Get the new insert position for the node we care about.
  675. Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
  676. assert(!Canonical && "Shouldn't be in the map!");
  677. (void)Canonical;
  678. // Create the canonical template template parameter entry.
  679. Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
  680. CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
  681. return CanonTTP;
  682. }
  683. CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
  684. if (!LangOpts.CPlusPlus) return nullptr;
  685. switch (T.getCXXABI().getKind()) {
  686. case TargetCXXABI::GenericARM: // Same as Itanium at this level
  687. case TargetCXXABI::iOS:
  688. case TargetCXXABI::iOS64:
  689. case TargetCXXABI::WatchOS:
  690. case TargetCXXABI::GenericAArch64:
  691. case TargetCXXABI::GenericMIPS:
  692. case TargetCXXABI::GenericItanium:
  693. case TargetCXXABI::WebAssembly:
  694. return CreateItaniumCXXABI(*this);
  695. case TargetCXXABI::Microsoft:
  696. return CreateMicrosoftCXXABI(*this);
  697. }
  698. llvm_unreachable("Invalid CXXABI type!");
  699. }
  700. interp::Context &ASTContext::getInterpContext() {
  701. if (!InterpContext) {
  702. InterpContext.reset(new interp::Context(*this));
  703. }
  704. return *InterpContext.get();
  705. }
  706. static const LangASMap *getAddressSpaceMap(const TargetInfo &T,
  707. const LangOptions &LOpts) {
  708. if (LOpts.FakeAddressSpaceMap) {
  709. // The fake address space map must have a distinct entry for each
  710. // language-specific address space.
  711. static const unsigned FakeAddrSpaceMap[] = {
  712. 0, // Default
  713. 1, // opencl_global
  714. 3, // opencl_local
  715. 2, // opencl_constant
  716. 0, // opencl_private
  717. 4, // opencl_generic
  718. 5, // cuda_device
  719. 6, // cuda_constant
  720. 7 // cuda_shared
  721. };
  722. return &FakeAddrSpaceMap;
  723. } else {
  724. return &T.getAddressSpaceMap();
  725. }
  726. }
  727. static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
  728. const LangOptions &LangOpts) {
  729. switch (LangOpts.getAddressSpaceMapMangling()) {
  730. case LangOptions::ASMM_Target:
  731. return TI.useAddressSpaceMapMangling();
  732. case LangOptions::ASMM_On:
  733. return true;
  734. case LangOptions::ASMM_Off:
  735. return false;
  736. }
  737. llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
  738. }
  739. ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
  740. IdentifierTable &idents, SelectorTable &sels,
  741. Builtin::Context &builtins)
  742. : ConstantArrayTypes(this_()), FunctionProtoTypes(this_()),
  743. TemplateSpecializationTypes(this_()),
  744. DependentTemplateSpecializationTypes(this_()),
  745. SubstTemplateTemplateParmPacks(this_()), SourceMgr(SM), LangOpts(LOpts),
  746. SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
  747. XRayFilter(new XRayFunctionFilter(LangOpts.XRayAlwaysInstrumentFiles,
  748. LangOpts.XRayNeverInstrumentFiles,
  749. LangOpts.XRayAttrListFiles, SM)),
  750. PrintingPolicy(LOpts), Idents(idents), Selectors(sels),
  751. BuiltinInfo(builtins), DeclarationNames(*this), Comments(SM),
  752. CommentCommandTraits(BumpAlloc, LOpts.CommentOpts),
  753. CompCategories(this_()), LastSDM(nullptr, 0) {
  754. TUDecl = TranslationUnitDecl::Create(*this);
  755. TraversalScope = {TUDecl};
  756. }
  757. ASTContext::~ASTContext() {
  758. // Release the DenseMaps associated with DeclContext objects.
  759. // FIXME: Is this the ideal solution?
  760. ReleaseDeclContextMaps();
  761. // Call all of the deallocation functions on all of their targets.
  762. for (auto &Pair : Deallocations)
  763. (Pair.first)(Pair.second);
  764. // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
  765. // because they can contain DenseMaps.
  766. for (llvm::DenseMap<const ObjCContainerDecl*,
  767. const ASTRecordLayout*>::iterator
  768. I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
  769. // Increment in loop to prevent using deallocated memory.
  770. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  771. R->Destroy(*this);
  772. for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
  773. I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
  774. // Increment in loop to prevent using deallocated memory.
  775. if (auto *R = const_cast<ASTRecordLayout *>((I++)->second))
  776. R->Destroy(*this);
  777. }
  778. for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
  779. AEnd = DeclAttrs.end();
  780. A != AEnd; ++A)
  781. A->second->~AttrVec();
  782. for (std::pair<const MaterializeTemporaryExpr *, APValue *> &MTVPair :
  783. MaterializedTemporaryValues)
  784. MTVPair.second->~APValue();
  785. for (const auto &Value : ModuleInitializers)
  786. Value.second->~PerModuleInitializers();
  787. for (APValue *Value : APValueCleanups)
  788. Value->~APValue();
  789. }
  790. class ASTContext::ParentMap {
  791. /// Contains parents of a node.
  792. using ParentVector = llvm::SmallVector<ast_type_traits::DynTypedNode, 2>;
  793. /// Maps from a node to its parents. This is used for nodes that have
  794. /// pointer identity only, which are more common and we can save space by
  795. /// only storing a unique pointer to them.
  796. using ParentMapPointers = llvm::DenseMap<
  797. const void *,
  798. llvm::PointerUnion4<const Decl *, const Stmt *,
  799. ast_type_traits::DynTypedNode *, ParentVector *>>;
  800. /// Parent map for nodes without pointer identity. We store a full
  801. /// DynTypedNode for all keys.
  802. using ParentMapOtherNodes = llvm::DenseMap<
  803. ast_type_traits::DynTypedNode,
  804. llvm::PointerUnion4<const Decl *, const Stmt *,
  805. ast_type_traits::DynTypedNode *, ParentVector *>>;
  806. ParentMapPointers PointerParents;
  807. ParentMapOtherNodes OtherParents;
  808. class ASTVisitor;
  809. static ast_type_traits::DynTypedNode
  810. getSingleDynTypedNodeFromParentMap(ParentMapPointers::mapped_type U) {
  811. if (const auto *D = U.dyn_cast<const Decl *>())
  812. return ast_type_traits::DynTypedNode::create(*D);
  813. if (const auto *S = U.dyn_cast<const Stmt *>())
  814. return ast_type_traits::DynTypedNode::create(*S);
  815. return *U.get<ast_type_traits::DynTypedNode *>();
  816. }
  817. template <typename NodeTy, typename MapTy>
  818. static ASTContext::DynTypedNodeList getDynNodeFromMap(const NodeTy &Node,
  819. const MapTy &Map) {
  820. auto I = Map.find(Node);
  821. if (I == Map.end()) {
  822. return llvm::ArrayRef<ast_type_traits::DynTypedNode>();
  823. }
  824. if (const auto *V = I->second.template dyn_cast<ParentVector *>()) {
  825. return llvm::makeArrayRef(*V);
  826. }
  827. return getSingleDynTypedNodeFromParentMap(I->second);
  828. }
  829. public:
  830. ParentMap(ASTContext &Ctx);
  831. ~ParentMap() {
  832. for (const auto &Entry : PointerParents) {
  833. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  834. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  835. } else if (Entry.second.is<ParentVector *>()) {
  836. delete Entry.second.get<ParentVector *>();
  837. }
  838. }
  839. for (const auto &Entry : OtherParents) {
  840. if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
  841. delete Entry.second.get<ast_type_traits::DynTypedNode *>();
  842. } else if (Entry.second.is<ParentVector *>()) {
  843. delete Entry.second.get<ParentVector *>();
  844. }
  845. }
  846. }
  847. DynTypedNodeList getParents(const ast_type_traits::DynTypedNode &Node) {
  848. if (Node.getNodeKind().hasPointerIdentity())
  849. return getDynNodeFromMap(Node.getMemoizationData(), PointerParents);
  850. return getDynNodeFromMap(Node, OtherParents);
  851. }
  852. };
  853. void ASTContext::setTraversalScope(const std::vector<Decl *> &TopLevelDecls) {
  854. TraversalScope = TopLevelDecls;
  855. Parents.reset();
  856. }
  857. void ASTContext::AddDeallocation(void (*Callback)(void *), void *Data) const {
  858. Deallocations.push_back({Callback, Data});
  859. }
  860. void
  861. ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
  862. ExternalSource = std::move(Source);
  863. }
  864. void ASTContext::PrintStats() const {
  865. llvm::errs() << "\n*** AST Context Stats:\n";
  866. llvm::errs() << " " << Types.size() << " types total.\n";
  867. unsigned counts[] = {
  868. #define TYPE(Name, Parent) 0,
  869. #define ABSTRACT_TYPE(Name, Parent)
  870. #include "clang/AST/TypeNodes.inc"
  871. 0 // Extra
  872. };
  873. for (unsigned i = 0, e = Types.size(); i != e; ++i) {
  874. Type *T = Types[i];
  875. counts[(unsigned)T->getTypeClass()]++;
  876. }
  877. unsigned Idx = 0;
  878. unsigned TotalBytes = 0;
  879. #define TYPE(Name, Parent) \
  880. if (counts[Idx]) \
  881. llvm::errs() << " " << counts[Idx] << " " << #Name \
  882. << " types, " << sizeof(Name##Type) << " each " \
  883. << "(" << counts[Idx] * sizeof(Name##Type) \
  884. << " bytes)\n"; \
  885. TotalBytes += counts[Idx] * sizeof(Name##Type); \
  886. ++Idx;
  887. #define ABSTRACT_TYPE(Name, Parent)
  888. #include "clang/AST/TypeNodes.inc"
  889. llvm::errs() << "Total bytes = " << TotalBytes << "\n";
  890. // Implicit special member functions.
  891. llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
  892. << NumImplicitDefaultConstructors
  893. << " implicit default constructors created\n";
  894. llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
  895. << NumImplicitCopyConstructors
  896. << " implicit copy constructors created\n";
  897. if (getLangOpts().CPlusPlus)
  898. llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
  899. << NumImplicitMoveConstructors
  900. << " implicit move constructors created\n";
  901. llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
  902. << NumImplicitCopyAssignmentOperators
  903. << " implicit copy assignment operators created\n";
  904. if (getLangOpts().CPlusPlus)
  905. llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
  906. << NumImplicitMoveAssignmentOperators
  907. << " implicit move assignment operators created\n";
  908. llvm::errs() << NumImplicitDestructorsDeclared << "/"
  909. << NumImplicitDestructors
  910. << " implicit destructors created\n";
  911. if (ExternalSource) {
  912. llvm::errs() << "\n";
  913. ExternalSource->PrintStats();
  914. }
  915. BumpAlloc.PrintStats();
  916. }
  917. void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  918. bool NotifyListeners) {
  919. if (NotifyListeners)
  920. if (auto *Listener = getASTMutationListener())
  921. Listener->RedefinedHiddenDefinition(ND, M);
  922. MergedDefModules[cast<NamedDecl>(ND->getCanonicalDecl())].push_back(M);
  923. }
  924. void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
  925. auto It = MergedDefModules.find(cast<NamedDecl>(ND->getCanonicalDecl()));
  926. if (It == MergedDefModules.end())
  927. return;
  928. auto &Merged = It->second;
  929. llvm::DenseSet<Module*> Found;
  930. for (Module *&M : Merged)
  931. if (!Found.insert(M).second)
  932. M = nullptr;
  933. Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
  934. }
  935. void ASTContext::PerModuleInitializers::resolve(ASTContext &Ctx) {
  936. if (LazyInitializers.empty())
  937. return;
  938. auto *Source = Ctx.getExternalSource();
  939. assert(Source && "lazy initializers but no external source");
  940. auto LazyInits = std::move(LazyInitializers);
  941. LazyInitializers.clear();
  942. for (auto ID : LazyInits)
  943. Initializers.push_back(Source->GetExternalDecl(ID));
  944. assert(LazyInitializers.empty() &&
  945. "GetExternalDecl for lazy module initializer added more inits");
  946. }
  947. void ASTContext::addModuleInitializer(Module *M, Decl *D) {
  948. // One special case: if we add a module initializer that imports another
  949. // module, and that module's only initializer is an ImportDecl, simplify.
  950. if (const auto *ID = dyn_cast<ImportDecl>(D)) {
  951. auto It = ModuleInitializers.find(ID->getImportedModule());
  952. // Maybe the ImportDecl does nothing at all. (Common case.)
  953. if (It == ModuleInitializers.end())
  954. return;
  955. // Maybe the ImportDecl only imports another ImportDecl.
  956. auto &Imported = *It->second;
  957. if (Imported.Initializers.size() + Imported.LazyInitializers.size() == 1) {
  958. Imported.resolve(*this);
  959. auto *OnlyDecl = Imported.Initializers.front();
  960. if (isa<ImportDecl>(OnlyDecl))
  961. D = OnlyDecl;
  962. }
  963. }
  964. auto *&Inits = ModuleInitializers[M];
  965. if (!Inits)
  966. Inits = new (*this) PerModuleInitializers;
  967. Inits->Initializers.push_back(D);
  968. }
  969. void ASTContext::addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs) {
  970. auto *&Inits = ModuleInitializers[M];
  971. if (!Inits)
  972. Inits = new (*this) PerModuleInitializers;
  973. Inits->LazyInitializers.insert(Inits->LazyInitializers.end(),
  974. IDs.begin(), IDs.end());
  975. }
  976. ArrayRef<Decl *> ASTContext::getModuleInitializers(Module *M) {
  977. auto It = ModuleInitializers.find(M);
  978. if (It == ModuleInitializers.end())
  979. return None;
  980. auto *Inits = It->second;
  981. Inits->resolve(*this);
  982. return Inits->Initializers;
  983. }
  984. ExternCContextDecl *ASTContext::getExternCContextDecl() const {
  985. if (!ExternCContext)
  986. ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
  987. return ExternCContext;
  988. }
  989. BuiltinTemplateDecl *
  990. ASTContext::buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
  991. const IdentifierInfo *II) const {
  992. auto *BuiltinTemplate = BuiltinTemplateDecl::Create(*this, TUDecl, II, BTK);
  993. BuiltinTemplate->setImplicit();
  994. TUDecl->addDecl(BuiltinTemplate);
  995. return BuiltinTemplate;
  996. }
  997. BuiltinTemplateDecl *
  998. ASTContext::getMakeIntegerSeqDecl() const {
  999. if (!MakeIntegerSeqDecl)
  1000. MakeIntegerSeqDecl = buildBuiltinTemplateDecl(BTK__make_integer_seq,
  1001. getMakeIntegerSeqName());
  1002. return MakeIntegerSeqDecl;
  1003. }
  1004. BuiltinTemplateDecl *
  1005. ASTContext::getTypePackElementDecl() const {
  1006. if (!TypePackElementDecl)
  1007. TypePackElementDecl = buildBuiltinTemplateDecl(BTK__type_pack_element,
  1008. getTypePackElementName());
  1009. return TypePackElementDecl;
  1010. }
  1011. RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
  1012. RecordDecl::TagKind TK) const {
  1013. SourceLocation Loc;
  1014. RecordDecl *NewDecl;
  1015. if (getLangOpts().CPlusPlus)
  1016. NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
  1017. Loc, &Idents.get(Name));
  1018. else
  1019. NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
  1020. &Idents.get(Name));
  1021. NewDecl->setImplicit();
  1022. NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
  1023. const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
  1024. return NewDecl;
  1025. }
  1026. TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
  1027. StringRef Name) const {
  1028. TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
  1029. TypedefDecl *NewDecl = TypedefDecl::Create(
  1030. const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
  1031. SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
  1032. NewDecl->setImplicit();
  1033. return NewDecl;
  1034. }
  1035. TypedefDecl *ASTContext::getInt128Decl() const {
  1036. if (!Int128Decl)
  1037. Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
  1038. return Int128Decl;
  1039. }
  1040. TypedefDecl *ASTContext::getUInt128Decl() const {
  1041. if (!UInt128Decl)
  1042. UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
  1043. return UInt128Decl;
  1044. }
  1045. void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
  1046. auto *Ty = new (*this, TypeAlignment) BuiltinType(K);
  1047. R = CanQualType::CreateUnsafe(QualType(Ty, 0));
  1048. Types.push_back(Ty);
  1049. }
  1050. void ASTContext::InitBuiltinTypes(const TargetInfo &Target,
  1051. const TargetInfo *AuxTarget) {
  1052. assert((!this->Target || this->Target == &Target) &&
  1053. "Incorrect target reinitialization");
  1054. assert(VoidTy.isNull() && "Context reinitialized?");
  1055. this->Target = &Target;
  1056. this->AuxTarget = AuxTarget;
  1057. ABI.reset(createCXXABI(Target));
  1058. AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
  1059. AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
  1060. // C99 6.2.5p19.
  1061. InitBuiltinType(VoidTy, BuiltinType::Void);
  1062. // C99 6.2.5p2.
  1063. InitBuiltinType(BoolTy, BuiltinType::Bool);
  1064. // C99 6.2.5p3.
  1065. if (LangOpts.CharIsSigned)
  1066. InitBuiltinType(CharTy, BuiltinType::Char_S);
  1067. else
  1068. InitBuiltinType(CharTy, BuiltinType::Char_U);
  1069. // C99 6.2.5p4.
  1070. InitBuiltinType(SignedCharTy, BuiltinType::SChar);
  1071. InitBuiltinType(ShortTy, BuiltinType::Short);
  1072. InitBuiltinType(IntTy, BuiltinType::Int);
  1073. InitBuiltinType(LongTy, BuiltinType::Long);
  1074. InitBuiltinType(LongLongTy, BuiltinType::LongLong);
  1075. // C99 6.2.5p6.
  1076. InitBuiltinType(UnsignedCharTy, BuiltinType::UChar);
  1077. InitBuiltinType(UnsignedShortTy, BuiltinType::UShort);
  1078. InitBuiltinType(UnsignedIntTy, BuiltinType::UInt);
  1079. InitBuiltinType(UnsignedLongTy, BuiltinType::ULong);
  1080. InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong);
  1081. // C99 6.2.5p10.
  1082. InitBuiltinType(FloatTy, BuiltinType::Float);
  1083. InitBuiltinType(DoubleTy, BuiltinType::Double);
  1084. InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble);
  1085. // GNU extension, __float128 for IEEE quadruple precision
  1086. InitBuiltinType(Float128Ty, BuiltinType::Float128);
  1087. // C11 extension ISO/IEC TS 18661-3
  1088. InitBuiltinType(Float16Ty, BuiltinType::Float16);
  1089. // ISO/IEC JTC1 SC22 WG14 N1169 Extension
  1090. InitBuiltinType(ShortAccumTy, BuiltinType::ShortAccum);
  1091. InitBuiltinType(AccumTy, BuiltinType::Accum);
  1092. InitBuiltinType(LongAccumTy, BuiltinType::LongAccum);
  1093. InitBuiltinType(UnsignedShortAccumTy, BuiltinType::UShortAccum);
  1094. InitBuiltinType(UnsignedAccumTy, BuiltinType::UAccum);
  1095. InitBuiltinType(UnsignedLongAccumTy, BuiltinType::ULongAccum);
  1096. InitBuiltinType(ShortFractTy, BuiltinType::ShortFract);
  1097. InitBuiltinType(FractTy, BuiltinType::Fract);
  1098. InitBuiltinType(LongFractTy, BuiltinType::LongFract);
  1099. InitBuiltinType(UnsignedShortFractTy, BuiltinType::UShortFract);
  1100. InitBuiltinType(UnsignedFractTy, BuiltinType::UFract);
  1101. InitBuiltinType(UnsignedLongFractTy, BuiltinType::ULongFract);
  1102. InitBuiltinType(SatShortAccumTy, BuiltinType::SatShortAccum);
  1103. InitBuiltinType(SatAccumTy, BuiltinType::SatAccum);
  1104. InitBuiltinType(SatLongAccumTy, BuiltinType::SatLongAccum);
  1105. InitBuiltinType(SatUnsignedShortAccumTy, BuiltinType::SatUShortAccum);
  1106. InitBuiltinType(SatUnsignedAccumTy, BuiltinType::SatUAccum);
  1107. InitBuiltinType(SatUnsignedLongAccumTy, BuiltinType::SatULongAccum);
  1108. InitBuiltinType(SatShortFractTy, BuiltinType::SatShortFract);
  1109. InitBuiltinType(SatFractTy, BuiltinType::SatFract);
  1110. InitBuiltinType(SatLongFractTy, BuiltinType::SatLongFract);
  1111. InitBuiltinType(SatUnsignedShortFractTy, BuiltinType::SatUShortFract);
  1112. InitBuiltinType(SatUnsignedFractTy, BuiltinType::SatUFract);
  1113. InitBuiltinType(SatUnsignedLongFractTy, BuiltinType::SatULongFract);
  1114. // GNU extension, 128-bit integers.
  1115. InitBuiltinType(Int128Ty, BuiltinType::Int128);
  1116. InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128);
  1117. // C++ 3.9.1p5
  1118. if (TargetInfo::isTypeSigned(Target.getWCharType()))
  1119. InitBuiltinType(WCharTy, BuiltinType::WChar_S);
  1120. else // -fshort-wchar makes wchar_t be unsigned.
  1121. InitBuiltinType(WCharTy, BuiltinType::WChar_U);
  1122. if (LangOpts.CPlusPlus && LangOpts.WChar)
  1123. WideCharTy = WCharTy;
  1124. else {
  1125. // C99 (or C++ using -fno-wchar).
  1126. WideCharTy = getFromTargetType(Target.getWCharType());
  1127. }
  1128. WIntTy = getFromTargetType(Target.getWIntType());
  1129. // C++20 (proposed)
  1130. InitBuiltinType(Char8Ty, BuiltinType::Char8);
  1131. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1132. InitBuiltinType(Char16Ty, BuiltinType::Char16);
  1133. else // C99
  1134. Char16Ty = getFromTargetType(Target.getChar16Type());
  1135. if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
  1136. InitBuiltinType(Char32Ty, BuiltinType::Char32);
  1137. else // C99
  1138. Char32Ty = getFromTargetType(Target.getChar32Type());
  1139. // Placeholder type for type-dependent expressions whose type is
  1140. // completely unknown. No code should ever check a type against
  1141. // DependentTy and users should never see it; however, it is here to
  1142. // help diagnose failures to properly check for type-dependent
  1143. // expressions.
  1144. InitBuiltinType(DependentTy, BuiltinType::Dependent);
  1145. // Placeholder type for functions.
  1146. InitBuiltinType(OverloadTy, BuiltinType::Overload);
  1147. // Placeholder type for bound members.
  1148. InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember);
  1149. // Placeholder type for pseudo-objects.
  1150. InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject);
  1151. // "any" type; useful for debugger-like clients.
  1152. InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny);
  1153. // Placeholder type for unbridged ARC casts.
  1154. InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast);
  1155. // Placeholder type for builtin functions.
  1156. InitBuiltinType(BuiltinFnTy, BuiltinType::BuiltinFn);
  1157. // Placeholder type for OMP array sections.
  1158. if (LangOpts.OpenMP)
  1159. InitBuiltinType(OMPArraySectionTy, BuiltinType::OMPArraySection);
  1160. // C99 6.2.5p11.
  1161. FloatComplexTy = getComplexType(FloatTy);
  1162. DoubleComplexTy = getComplexType(DoubleTy);
  1163. LongDoubleComplexTy = getComplexType(LongDoubleTy);
  1164. Float128ComplexTy = getComplexType(Float128Ty);
  1165. // Builtin types for 'id', 'Class', and 'SEL'.
  1166. InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
  1167. InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
  1168. InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
  1169. if (LangOpts.OpenCL) {
  1170. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1171. InitBuiltinType(SingletonId, BuiltinType::Id);
  1172. #include "clang/Basic/OpenCLImageTypes.def"
  1173. InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
  1174. InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
  1175. InitBuiltinType(OCLClkEventTy, BuiltinType::OCLClkEvent);
  1176. InitBuiltinType(OCLQueueTy, BuiltinType::OCLQueue);
  1177. InitBuiltinType(OCLReserveIDTy, BuiltinType::OCLReserveID);
  1178. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1179. InitBuiltinType(Id##Ty, BuiltinType::Id);
  1180. #include "clang/Basic/OpenCLExtensionTypes.def"
  1181. }
  1182. if (Target.hasAArch64SVETypes()) {
  1183. #define SVE_TYPE(Name, Id, SingletonId) \
  1184. InitBuiltinType(SingletonId, BuiltinType::Id);
  1185. #include "clang/Basic/AArch64SVEACLETypes.def"
  1186. }
  1187. // Builtin type for __objc_yes and __objc_no
  1188. ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
  1189. SignedCharTy : BoolTy);
  1190. ObjCConstantStringType = QualType();
  1191. ObjCSuperType = QualType();
  1192. // void * type
  1193. if (LangOpts.OpenCLVersion >= 200) {
  1194. auto Q = VoidTy.getQualifiers();
  1195. Q.setAddressSpace(LangAS::opencl_generic);
  1196. VoidPtrTy = getPointerType(getCanonicalType(
  1197. getQualifiedType(VoidTy.getUnqualifiedType(), Q)));
  1198. } else {
  1199. VoidPtrTy = getPointerType(VoidTy);
  1200. }
  1201. // nullptr type (C++0x 2.14.7)
  1202. InitBuiltinType(NullPtrTy, BuiltinType::NullPtr);
  1203. // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
  1204. InitBuiltinType(HalfTy, BuiltinType::Half);
  1205. // Builtin type used to help define __builtin_va_list.
  1206. VaListTagDecl = nullptr;
  1207. }
  1208. DiagnosticsEngine &ASTContext::getDiagnostics() const {
  1209. return SourceMgr.getDiagnostics();
  1210. }
  1211. AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
  1212. AttrVec *&Result = DeclAttrs[D];
  1213. if (!Result) {
  1214. void *Mem = Allocate(sizeof(AttrVec));
  1215. Result = new (Mem) AttrVec;
  1216. }
  1217. return *Result;
  1218. }
  1219. /// Erase the attributes corresponding to the given declaration.
  1220. void ASTContext::eraseDeclAttrs(const Decl *D) {
  1221. llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
  1222. if (Pos != DeclAttrs.end()) {
  1223. Pos->second->~AttrVec();
  1224. DeclAttrs.erase(Pos);
  1225. }
  1226. }
  1227. // FIXME: Remove ?
  1228. MemberSpecializationInfo *
  1229. ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
  1230. assert(Var->isStaticDataMember() && "Not a static data member");
  1231. return getTemplateOrSpecializationInfo(Var)
  1232. .dyn_cast<MemberSpecializationInfo *>();
  1233. }
  1234. ASTContext::TemplateOrSpecializationInfo
  1235. ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
  1236. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
  1237. TemplateOrInstantiation.find(Var);
  1238. if (Pos == TemplateOrInstantiation.end())
  1239. return {};
  1240. return Pos->second;
  1241. }
  1242. void
  1243. ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  1244. TemplateSpecializationKind TSK,
  1245. SourceLocation PointOfInstantiation) {
  1246. assert(Inst->isStaticDataMember() && "Not a static data member");
  1247. assert(Tmpl->isStaticDataMember() && "Not a static data member");
  1248. setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
  1249. Tmpl, TSK, PointOfInstantiation));
  1250. }
  1251. void
  1252. ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
  1253. TemplateOrSpecializationInfo TSI) {
  1254. assert(!TemplateOrInstantiation[Inst] &&
  1255. "Already noted what the variable was instantiated from");
  1256. TemplateOrInstantiation[Inst] = TSI;
  1257. }
  1258. NamedDecl *
  1259. ASTContext::getInstantiatedFromUsingDecl(NamedDecl *UUD) {
  1260. auto Pos = InstantiatedFromUsingDecl.find(UUD);
  1261. if (Pos == InstantiatedFromUsingDecl.end())
  1262. return nullptr;
  1263. return Pos->second;
  1264. }
  1265. void
  1266. ASTContext::setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern) {
  1267. assert((isa<UsingDecl>(Pattern) ||
  1268. isa<UnresolvedUsingValueDecl>(Pattern) ||
  1269. isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
  1270. "pattern decl is not a using decl");
  1271. assert((isa<UsingDecl>(Inst) ||
  1272. isa<UnresolvedUsingValueDecl>(Inst) ||
  1273. isa<UnresolvedUsingTypenameDecl>(Inst)) &&
  1274. "instantiation did not produce a using decl");
  1275. assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
  1276. InstantiatedFromUsingDecl[Inst] = Pattern;
  1277. }
  1278. UsingShadowDecl *
  1279. ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
  1280. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
  1281. = InstantiatedFromUsingShadowDecl.find(Inst);
  1282. if (Pos == InstantiatedFromUsingShadowDecl.end())
  1283. return nullptr;
  1284. return Pos->second;
  1285. }
  1286. void
  1287. ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  1288. UsingShadowDecl *Pattern) {
  1289. assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
  1290. InstantiatedFromUsingShadowDecl[Inst] = Pattern;
  1291. }
  1292. FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
  1293. llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
  1294. = InstantiatedFromUnnamedFieldDecl.find(Field);
  1295. if (Pos == InstantiatedFromUnnamedFieldDecl.end())
  1296. return nullptr;
  1297. return Pos->second;
  1298. }
  1299. void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
  1300. FieldDecl *Tmpl) {
  1301. assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
  1302. assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
  1303. assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
  1304. "Already noted what unnamed field was instantiated from");
  1305. InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
  1306. }
  1307. ASTContext::overridden_cxx_method_iterator
  1308. ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
  1309. return overridden_methods(Method).begin();
  1310. }
  1311. ASTContext::overridden_cxx_method_iterator
  1312. ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
  1313. return overridden_methods(Method).end();
  1314. }
  1315. unsigned
  1316. ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
  1317. auto Range = overridden_methods(Method);
  1318. return Range.end() - Range.begin();
  1319. }
  1320. ASTContext::overridden_method_range
  1321. ASTContext::overridden_methods(const CXXMethodDecl *Method) const {
  1322. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos =
  1323. OverriddenMethods.find(Method->getCanonicalDecl());
  1324. if (Pos == OverriddenMethods.end())
  1325. return overridden_method_range(nullptr, nullptr);
  1326. return overridden_method_range(Pos->second.begin(), Pos->second.end());
  1327. }
  1328. void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
  1329. const CXXMethodDecl *Overridden) {
  1330. assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
  1331. OverriddenMethods[Method].push_back(Overridden);
  1332. }
  1333. void ASTContext::getOverriddenMethods(
  1334. const NamedDecl *D,
  1335. SmallVectorImpl<const NamedDecl *> &Overridden) const {
  1336. assert(D);
  1337. if (const auto *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
  1338. Overridden.append(overridden_methods_begin(CXXMethod),
  1339. overridden_methods_end(CXXMethod));
  1340. return;
  1341. }
  1342. const auto *Method = dyn_cast<ObjCMethodDecl>(D);
  1343. if (!Method)
  1344. return;
  1345. SmallVector<const ObjCMethodDecl *, 8> OverDecls;
  1346. Method->getOverriddenMethods(OverDecls);
  1347. Overridden.append(OverDecls.begin(), OverDecls.end());
  1348. }
  1349. void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
  1350. assert(!Import->NextLocalImport && "Import declaration already in the chain");
  1351. assert(!Import->isFromASTFile() && "Non-local import declaration");
  1352. if (!FirstLocalImport) {
  1353. FirstLocalImport = Import;
  1354. LastLocalImport = Import;
  1355. return;
  1356. }
  1357. LastLocalImport->NextLocalImport = Import;
  1358. LastLocalImport = Import;
  1359. }
  1360. //===----------------------------------------------------------------------===//
  1361. // Type Sizing and Analysis
  1362. //===----------------------------------------------------------------------===//
  1363. /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
  1364. /// scalar floating point type.
  1365. const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
  1366. switch (T->castAs<BuiltinType>()->getKind()) {
  1367. default:
  1368. llvm_unreachable("Not a floating point type!");
  1369. case BuiltinType::Float16:
  1370. case BuiltinType::Half:
  1371. return Target->getHalfFormat();
  1372. case BuiltinType::Float: return Target->getFloatFormat();
  1373. case BuiltinType::Double: return Target->getDoubleFormat();
  1374. case BuiltinType::LongDouble:
  1375. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1376. return AuxTarget->getLongDoubleFormat();
  1377. return Target->getLongDoubleFormat();
  1378. case BuiltinType::Float128:
  1379. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice)
  1380. return AuxTarget->getFloat128Format();
  1381. return Target->getFloat128Format();
  1382. }
  1383. }
  1384. CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
  1385. unsigned Align = Target->getCharWidth();
  1386. bool UseAlignAttrOnly = false;
  1387. if (unsigned AlignFromAttr = D->getMaxAlignment()) {
  1388. Align = AlignFromAttr;
  1389. // __attribute__((aligned)) can increase or decrease alignment
  1390. // *except* on a struct or struct member, where it only increases
  1391. // alignment unless 'packed' is also specified.
  1392. //
  1393. // It is an error for alignas to decrease alignment, so we can
  1394. // ignore that possibility; Sema should diagnose it.
  1395. if (isa<FieldDecl>(D)) {
  1396. UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
  1397. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1398. } else {
  1399. UseAlignAttrOnly = true;
  1400. }
  1401. }
  1402. else if (isa<FieldDecl>(D))
  1403. UseAlignAttrOnly =
  1404. D->hasAttr<PackedAttr>() ||
  1405. cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
  1406. // If we're using the align attribute only, just ignore everything
  1407. // else about the declaration and its type.
  1408. if (UseAlignAttrOnly) {
  1409. // do nothing
  1410. } else if (const auto *VD = dyn_cast<ValueDecl>(D)) {
  1411. QualType T = VD->getType();
  1412. if (const auto *RT = T->getAs<ReferenceType>()) {
  1413. if (ForAlignof)
  1414. T = RT->getPointeeType();
  1415. else
  1416. T = getPointerType(RT->getPointeeType());
  1417. }
  1418. QualType BaseT = getBaseElementType(T);
  1419. if (T->isFunctionType())
  1420. Align = getTypeInfoImpl(T.getTypePtr()).Align;
  1421. else if (!BaseT->isIncompleteType()) {
  1422. // Adjust alignments of declarations with array type by the
  1423. // large-array alignment on the target.
  1424. if (const ArrayType *arrayType = getAsArrayType(T)) {
  1425. unsigned MinWidth = Target->getLargeArrayMinWidth();
  1426. if (!ForAlignof && MinWidth) {
  1427. if (isa<VariableArrayType>(arrayType))
  1428. Align = std::max(Align, Target->getLargeArrayAlign());
  1429. else if (isa<ConstantArrayType>(arrayType) &&
  1430. MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
  1431. Align = std::max(Align, Target->getLargeArrayAlign());
  1432. }
  1433. }
  1434. Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
  1435. if (BaseT.getQualifiers().hasUnaligned())
  1436. Align = Target->getCharWidth();
  1437. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  1438. if (VD->hasGlobalStorage() && !ForAlignof) {
  1439. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  1440. Align = std::max(Align, getTargetInfo().getMinGlobalAlign(TypeSize));
  1441. }
  1442. }
  1443. }
  1444. // Fields can be subject to extra alignment constraints, like if
  1445. // the field is packed, the struct is packed, or the struct has a
  1446. // a max-field-alignment constraint (#pragma pack). So calculate
  1447. // the actual alignment of the field within the struct, and then
  1448. // (as we're expected to) constrain that by the alignment of the type.
  1449. if (const auto *Field = dyn_cast<FieldDecl>(VD)) {
  1450. const RecordDecl *Parent = Field->getParent();
  1451. // We can only produce a sensible answer if the record is valid.
  1452. if (!Parent->isInvalidDecl()) {
  1453. const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
  1454. // Start with the record's overall alignment.
  1455. unsigned FieldAlign = toBits(Layout.getAlignment());
  1456. // Use the GCD of that and the offset within the record.
  1457. uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
  1458. if (Offset > 0) {
  1459. // Alignment is always a power of 2, so the GCD will be a power of 2,
  1460. // which means we get to do this crazy thing instead of Euclid's.
  1461. uint64_t LowBitOfOffset = Offset & (~Offset + 1);
  1462. if (LowBitOfOffset < FieldAlign)
  1463. FieldAlign = static_cast<unsigned>(LowBitOfOffset);
  1464. }
  1465. Align = std::min(Align, FieldAlign);
  1466. }
  1467. }
  1468. }
  1469. return toCharUnitsFromBits(Align);
  1470. }
  1471. // getTypeInfoDataSizeInChars - Return the size of a type, in
  1472. // chars. If the type is a record, its data size is returned. This is
  1473. // the size of the memcpy that's performed when assigning this type
  1474. // using a trivial copy/move assignment operator.
  1475. std::pair<CharUnits, CharUnits>
  1476. ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
  1477. std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
  1478. // In C++, objects can sometimes be allocated into the tail padding
  1479. // of a base-class subobject. We decide whether that's possible
  1480. // during class layout, so here we can just trust the layout results.
  1481. if (getLangOpts().CPlusPlus) {
  1482. if (const auto *RT = T->getAs<RecordType>()) {
  1483. const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
  1484. sizeAndAlign.first = layout.getDataSize();
  1485. }
  1486. }
  1487. return sizeAndAlign;
  1488. }
  1489. /// getConstantArrayInfoInChars - Performing the computation in CharUnits
  1490. /// instead of in bits prevents overflowing the uint64_t for some large arrays.
  1491. std::pair<CharUnits, CharUnits>
  1492. static getConstantArrayInfoInChars(const ASTContext &Context,
  1493. const ConstantArrayType *CAT) {
  1494. std::pair<CharUnits, CharUnits> EltInfo =
  1495. Context.getTypeInfoInChars(CAT->getElementType());
  1496. uint64_t Size = CAT->getSize().getZExtValue();
  1497. assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
  1498. (uint64_t)(-1)/Size) &&
  1499. "Overflow in array type char size evaluation");
  1500. uint64_t Width = EltInfo.first.getQuantity() * Size;
  1501. unsigned Align = EltInfo.second.getQuantity();
  1502. if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
  1503. Context.getTargetInfo().getPointerWidth(0) == 64)
  1504. Width = llvm::alignTo(Width, Align);
  1505. return std::make_pair(CharUnits::fromQuantity(Width),
  1506. CharUnits::fromQuantity(Align));
  1507. }
  1508. std::pair<CharUnits, CharUnits>
  1509. ASTContext::getTypeInfoInChars(const Type *T) const {
  1510. if (const auto *CAT = dyn_cast<ConstantArrayType>(T))
  1511. return getConstantArrayInfoInChars(*this, CAT);
  1512. TypeInfo Info = getTypeInfo(T);
  1513. return std::make_pair(toCharUnitsFromBits(Info.Width),
  1514. toCharUnitsFromBits(Info.Align));
  1515. }
  1516. std::pair<CharUnits, CharUnits>
  1517. ASTContext::getTypeInfoInChars(QualType T) const {
  1518. return getTypeInfoInChars(T.getTypePtr());
  1519. }
  1520. bool ASTContext::isAlignmentRequired(const Type *T) const {
  1521. return getTypeInfo(T).AlignIsRequired;
  1522. }
  1523. bool ASTContext::isAlignmentRequired(QualType T) const {
  1524. return isAlignmentRequired(T.getTypePtr());
  1525. }
  1526. unsigned ASTContext::getTypeAlignIfKnown(QualType T) const {
  1527. // An alignment on a typedef overrides anything else.
  1528. if (const auto *TT = T->getAs<TypedefType>())
  1529. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1530. return Align;
  1531. // If we have an (array of) complete type, we're done.
  1532. T = getBaseElementType(T);
  1533. if (!T->isIncompleteType())
  1534. return getTypeAlign(T);
  1535. // If we had an array type, its element type might be a typedef
  1536. // type with an alignment attribute.
  1537. if (const auto *TT = T->getAs<TypedefType>())
  1538. if (unsigned Align = TT->getDecl()->getMaxAlignment())
  1539. return Align;
  1540. // Otherwise, see if the declaration of the type had an attribute.
  1541. if (const auto *TT = T->getAs<TagType>())
  1542. return TT->getDecl()->getMaxAlignment();
  1543. return 0;
  1544. }
  1545. TypeInfo ASTContext::getTypeInfo(const Type *T) const {
  1546. TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
  1547. if (I != MemoizedTypeInfo.end())
  1548. return I->second;
  1549. // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
  1550. TypeInfo TI = getTypeInfoImpl(T);
  1551. MemoizedTypeInfo[T] = TI;
  1552. return TI;
  1553. }
  1554. /// getTypeInfoImpl - Return the size of the specified type, in bits. This
  1555. /// method does not work on incomplete types.
  1556. ///
  1557. /// FIXME: Pointers into different addr spaces could have different sizes and
  1558. /// alignment requirements: getPointerInfo should take an AddrSpace, this
  1559. /// should take a QualType, &c.
  1560. TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
  1561. uint64_t Width = 0;
  1562. unsigned Align = 8;
  1563. bool AlignIsRequired = false;
  1564. unsigned AS = 0;
  1565. switch (T->getTypeClass()) {
  1566. #define TYPE(Class, Base)
  1567. #define ABSTRACT_TYPE(Class, Base)
  1568. #define NON_CANONICAL_TYPE(Class, Base)
  1569. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1570. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) \
  1571. case Type::Class: \
  1572. assert(!T->isDependentType() && "should not see dependent types here"); \
  1573. return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
  1574. #include "clang/AST/TypeNodes.inc"
  1575. llvm_unreachable("Should not see dependent types");
  1576. case Type::FunctionNoProto:
  1577. case Type::FunctionProto:
  1578. // GCC extension: alignof(function) = 32 bits
  1579. Width = 0;
  1580. Align = 32;
  1581. break;
  1582. case Type::IncompleteArray:
  1583. case Type::VariableArray:
  1584. Width = 0;
  1585. Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
  1586. break;
  1587. case Type::ConstantArray: {
  1588. const auto *CAT = cast<ConstantArrayType>(T);
  1589. TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
  1590. uint64_t Size = CAT->getSize().getZExtValue();
  1591. assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
  1592. "Overflow in array type bit size evaluation");
  1593. Width = EltInfo.Width * Size;
  1594. Align = EltInfo.Align;
  1595. if (!getTargetInfo().getCXXABI().isMicrosoft() ||
  1596. getTargetInfo().getPointerWidth(0) == 64)
  1597. Width = llvm::alignTo(Width, Align);
  1598. break;
  1599. }
  1600. case Type::ExtVector:
  1601. case Type::Vector: {
  1602. const auto *VT = cast<VectorType>(T);
  1603. TypeInfo EltInfo = getTypeInfo(VT->getElementType());
  1604. Width = EltInfo.Width * VT->getNumElements();
  1605. Align = Width;
  1606. // If the alignment is not a power of 2, round up to the next power of 2.
  1607. // This happens for non-power-of-2 length vectors.
  1608. if (Align & (Align-1)) {
  1609. Align = llvm::NextPowerOf2(Align);
  1610. Width = llvm::alignTo(Width, Align);
  1611. }
  1612. // Adjust the alignment based on the target max.
  1613. uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
  1614. if (TargetVectorAlign && TargetVectorAlign < Align)
  1615. Align = TargetVectorAlign;
  1616. break;
  1617. }
  1618. case Type::Builtin:
  1619. switch (cast<BuiltinType>(T)->getKind()) {
  1620. default: llvm_unreachable("Unknown builtin type!");
  1621. case BuiltinType::Void:
  1622. // GCC extension: alignof(void) = 8 bits.
  1623. Width = 0;
  1624. Align = 8;
  1625. break;
  1626. case BuiltinType::Bool:
  1627. Width = Target->getBoolWidth();
  1628. Align = Target->getBoolAlign();
  1629. break;
  1630. case BuiltinType::Char_S:
  1631. case BuiltinType::Char_U:
  1632. case BuiltinType::UChar:
  1633. case BuiltinType::SChar:
  1634. case BuiltinType::Char8:
  1635. Width = Target->getCharWidth();
  1636. Align = Target->getCharAlign();
  1637. break;
  1638. case BuiltinType::WChar_S:
  1639. case BuiltinType::WChar_U:
  1640. Width = Target->getWCharWidth();
  1641. Align = Target->getWCharAlign();
  1642. break;
  1643. case BuiltinType::Char16:
  1644. Width = Target->getChar16Width();
  1645. Align = Target->getChar16Align();
  1646. break;
  1647. case BuiltinType::Char32:
  1648. Width = Target->getChar32Width();
  1649. Align = Target->getChar32Align();
  1650. break;
  1651. case BuiltinType::UShort:
  1652. case BuiltinType::Short:
  1653. Width = Target->getShortWidth();
  1654. Align = Target->getShortAlign();
  1655. break;
  1656. case BuiltinType::UInt:
  1657. case BuiltinType::Int:
  1658. Width = Target->getIntWidth();
  1659. Align = Target->getIntAlign();
  1660. break;
  1661. case BuiltinType::ULong:
  1662. case BuiltinType::Long:
  1663. Width = Target->getLongWidth();
  1664. Align = Target->getLongAlign();
  1665. break;
  1666. case BuiltinType::ULongLong:
  1667. case BuiltinType::LongLong:
  1668. Width = Target->getLongLongWidth();
  1669. Align = Target->getLongLongAlign();
  1670. break;
  1671. case BuiltinType::Int128:
  1672. case BuiltinType::UInt128:
  1673. Width = 128;
  1674. Align = 128; // int128_t is 128-bit aligned on all targets.
  1675. break;
  1676. case BuiltinType::ShortAccum:
  1677. case BuiltinType::UShortAccum:
  1678. case BuiltinType::SatShortAccum:
  1679. case BuiltinType::SatUShortAccum:
  1680. Width = Target->getShortAccumWidth();
  1681. Align = Target->getShortAccumAlign();
  1682. break;
  1683. case BuiltinType::Accum:
  1684. case BuiltinType::UAccum:
  1685. case BuiltinType::SatAccum:
  1686. case BuiltinType::SatUAccum:
  1687. Width = Target->getAccumWidth();
  1688. Align = Target->getAccumAlign();
  1689. break;
  1690. case BuiltinType::LongAccum:
  1691. case BuiltinType::ULongAccum:
  1692. case BuiltinType::SatLongAccum:
  1693. case BuiltinType::SatULongAccum:
  1694. Width = Target->getLongAccumWidth();
  1695. Align = Target->getLongAccumAlign();
  1696. break;
  1697. case BuiltinType::ShortFract:
  1698. case BuiltinType::UShortFract:
  1699. case BuiltinType::SatShortFract:
  1700. case BuiltinType::SatUShortFract:
  1701. Width = Target->getShortFractWidth();
  1702. Align = Target->getShortFractAlign();
  1703. break;
  1704. case BuiltinType::Fract:
  1705. case BuiltinType::UFract:
  1706. case BuiltinType::SatFract:
  1707. case BuiltinType::SatUFract:
  1708. Width = Target->getFractWidth();
  1709. Align = Target->getFractAlign();
  1710. break;
  1711. case BuiltinType::LongFract:
  1712. case BuiltinType::ULongFract:
  1713. case BuiltinType::SatLongFract:
  1714. case BuiltinType::SatULongFract:
  1715. Width = Target->getLongFractWidth();
  1716. Align = Target->getLongFractAlign();
  1717. break;
  1718. case BuiltinType::Float16:
  1719. case BuiltinType::Half:
  1720. if (Target->hasFloat16Type() || !getLangOpts().OpenMP ||
  1721. !getLangOpts().OpenMPIsDevice) {
  1722. Width = Target->getHalfWidth();
  1723. Align = Target->getHalfAlign();
  1724. } else {
  1725. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1726. "Expected OpenMP device compilation.");
  1727. Width = AuxTarget->getHalfWidth();
  1728. Align = AuxTarget->getHalfAlign();
  1729. }
  1730. break;
  1731. case BuiltinType::Float:
  1732. Width = Target->getFloatWidth();
  1733. Align = Target->getFloatAlign();
  1734. break;
  1735. case BuiltinType::Double:
  1736. Width = Target->getDoubleWidth();
  1737. Align = Target->getDoubleAlign();
  1738. break;
  1739. case BuiltinType::LongDouble:
  1740. if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1741. (Target->getLongDoubleWidth() != AuxTarget->getLongDoubleWidth() ||
  1742. Target->getLongDoubleAlign() != AuxTarget->getLongDoubleAlign())) {
  1743. Width = AuxTarget->getLongDoubleWidth();
  1744. Align = AuxTarget->getLongDoubleAlign();
  1745. } else {
  1746. Width = Target->getLongDoubleWidth();
  1747. Align = Target->getLongDoubleAlign();
  1748. }
  1749. break;
  1750. case BuiltinType::Float128:
  1751. if (Target->hasFloat128Type() || !getLangOpts().OpenMP ||
  1752. !getLangOpts().OpenMPIsDevice) {
  1753. Width = Target->getFloat128Width();
  1754. Align = Target->getFloat128Align();
  1755. } else {
  1756. assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
  1757. "Expected OpenMP device compilation.");
  1758. Width = AuxTarget->getFloat128Width();
  1759. Align = AuxTarget->getFloat128Align();
  1760. }
  1761. break;
  1762. case BuiltinType::NullPtr:
  1763. Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
  1764. Align = Target->getPointerAlign(0); // == sizeof(void*)
  1765. break;
  1766. case BuiltinType::ObjCId:
  1767. case BuiltinType::ObjCClass:
  1768. case BuiltinType::ObjCSel:
  1769. Width = Target->getPointerWidth(0);
  1770. Align = Target->getPointerAlign(0);
  1771. break;
  1772. case BuiltinType::OCLSampler:
  1773. case BuiltinType::OCLEvent:
  1774. case BuiltinType::OCLClkEvent:
  1775. case BuiltinType::OCLQueue:
  1776. case BuiltinType::OCLReserveID:
  1777. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  1778. case BuiltinType::Id:
  1779. #include "clang/Basic/OpenCLImageTypes.def"
  1780. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  1781. case BuiltinType::Id:
  1782. #include "clang/Basic/OpenCLExtensionTypes.def"
  1783. AS = getTargetAddressSpace(
  1784. Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T)));
  1785. Width = Target->getPointerWidth(AS);
  1786. Align = Target->getPointerAlign(AS);
  1787. break;
  1788. // The SVE types are effectively target-specific. The length of an
  1789. // SVE_VECTOR_TYPE is only known at runtime, but it is always a multiple
  1790. // of 128 bits. There is one predicate bit for each vector byte, so the
  1791. // length of an SVE_PREDICATE_TYPE is always a multiple of 16 bits.
  1792. //
  1793. // Because the length is only known at runtime, we use a dummy value
  1794. // of 0 for the static length. The alignment values are those defined
  1795. // by the Procedure Call Standard for the Arm Architecture.
  1796. #define SVE_VECTOR_TYPE(Name, Id, SingletonId, ElKind, ElBits, IsSigned, IsFP)\
  1797. case BuiltinType::Id: \
  1798. Width = 0; \
  1799. Align = 128; \
  1800. break;
  1801. #define SVE_PREDICATE_TYPE(Name, Id, SingletonId, ElKind) \
  1802. case BuiltinType::Id: \
  1803. Width = 0; \
  1804. Align = 16; \
  1805. break;
  1806. #include "clang/Basic/AArch64SVEACLETypes.def"
  1807. }
  1808. break;
  1809. case Type::ObjCObjectPointer:
  1810. Width = Target->getPointerWidth(0);
  1811. Align = Target->getPointerAlign(0);
  1812. break;
  1813. case Type::BlockPointer:
  1814. AS = getTargetAddressSpace(cast<BlockPointerType>(T)->getPointeeType());
  1815. Width = Target->getPointerWidth(AS);
  1816. Align = Target->getPointerAlign(AS);
  1817. break;
  1818. case Type::LValueReference:
  1819. case Type::RValueReference:
  1820. // alignof and sizeof should never enter this code path here, so we go
  1821. // the pointer route.
  1822. AS = getTargetAddressSpace(cast<ReferenceType>(T)->getPointeeType());
  1823. Width = Target->getPointerWidth(AS);
  1824. Align = Target->getPointerAlign(AS);
  1825. break;
  1826. case Type::Pointer:
  1827. AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
  1828. Width = Target->getPointerWidth(AS);
  1829. Align = Target->getPointerAlign(AS);
  1830. break;
  1831. case Type::MemberPointer: {
  1832. const auto *MPT = cast<MemberPointerType>(T);
  1833. CXXABI::MemberPointerInfo MPI = ABI->getMemberPointerInfo(MPT);
  1834. Width = MPI.Width;
  1835. Align = MPI.Align;
  1836. break;
  1837. }
  1838. case Type::Complex: {
  1839. // Complex types have the same alignment as their elements, but twice the
  1840. // size.
  1841. TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
  1842. Width = EltInfo.Width * 2;
  1843. Align = EltInfo.Align;
  1844. break;
  1845. }
  1846. case Type::ObjCObject:
  1847. return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
  1848. case Type::Adjusted:
  1849. case Type::Decayed:
  1850. return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
  1851. case Type::ObjCInterface: {
  1852. const auto *ObjCI = cast<ObjCInterfaceType>(T);
  1853. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1854. Width = toBits(Layout.getSize());
  1855. Align = toBits(Layout.getAlignment());
  1856. break;
  1857. }
  1858. case Type::Record:
  1859. case Type::Enum: {
  1860. const auto *TT = cast<TagType>(T);
  1861. if (TT->getDecl()->isInvalidDecl()) {
  1862. Width = 8;
  1863. Align = 8;
  1864. break;
  1865. }
  1866. if (const auto *ET = dyn_cast<EnumType>(TT)) {
  1867. const EnumDecl *ED = ET->getDecl();
  1868. TypeInfo Info =
  1869. getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
  1870. if (unsigned AttrAlign = ED->getMaxAlignment()) {
  1871. Info.Align = AttrAlign;
  1872. Info.AlignIsRequired = true;
  1873. }
  1874. return Info;
  1875. }
  1876. const auto *RT = cast<RecordType>(TT);
  1877. const RecordDecl *RD = RT->getDecl();
  1878. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1879. Width = toBits(Layout.getSize());
  1880. Align = toBits(Layout.getAlignment());
  1881. AlignIsRequired = RD->hasAttr<AlignedAttr>();
  1882. break;
  1883. }
  1884. case Type::SubstTemplateTypeParm:
  1885. return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
  1886. getReplacementType().getTypePtr());
  1887. case Type::Auto:
  1888. case Type::DeducedTemplateSpecialization: {
  1889. const auto *A = cast<DeducedType>(T);
  1890. assert(!A->getDeducedType().isNull() &&
  1891. "cannot request the size of an undeduced or dependent auto type");
  1892. return getTypeInfo(A->getDeducedType().getTypePtr());
  1893. }
  1894. case Type::Paren:
  1895. return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
  1896. case Type::MacroQualified:
  1897. return getTypeInfo(
  1898. cast<MacroQualifiedType>(T)->getUnderlyingType().getTypePtr());
  1899. case Type::ObjCTypeParam:
  1900. return getTypeInfo(cast<ObjCTypeParamType>(T)->desugar().getTypePtr());
  1901. case Type::Typedef: {
  1902. const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
  1903. TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
  1904. // If the typedef has an aligned attribute on it, it overrides any computed
  1905. // alignment we have. This violates the GCC documentation (which says that
  1906. // attribute(aligned) can only round up) but matches its implementation.
  1907. if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
  1908. Align = AttrAlign;
  1909. AlignIsRequired = true;
  1910. } else {
  1911. Align = Info.Align;
  1912. AlignIsRequired = Info.AlignIsRequired;
  1913. }
  1914. Width = Info.Width;
  1915. break;
  1916. }
  1917. case Type::Elaborated:
  1918. return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
  1919. case Type::Attributed:
  1920. return getTypeInfo(
  1921. cast<AttributedType>(T)->getEquivalentType().getTypePtr());
  1922. case Type::Atomic: {
  1923. // Start with the base type information.
  1924. TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
  1925. Width = Info.Width;
  1926. Align = Info.Align;
  1927. if (!Width) {
  1928. // An otherwise zero-sized type should still generate an
  1929. // atomic operation.
  1930. Width = Target->getCharWidth();
  1931. assert(Align);
  1932. } else if (Width <= Target->getMaxAtomicPromoteWidth()) {
  1933. // If the size of the type doesn't exceed the platform's max
  1934. // atomic promotion width, make the size and alignment more
  1935. // favorable to atomic operations:
  1936. // Round the size up to a power of 2.
  1937. if (!llvm::isPowerOf2_64(Width))
  1938. Width = llvm::NextPowerOf2(Width);
  1939. // Set the alignment equal to the size.
  1940. Align = static_cast<unsigned>(Width);
  1941. }
  1942. }
  1943. break;
  1944. case Type::Pipe:
  1945. Width = Target->getPointerWidth(getTargetAddressSpace(LangAS::opencl_global));
  1946. Align = Target->getPointerAlign(getTargetAddressSpace(LangAS::opencl_global));
  1947. break;
  1948. }
  1949. assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
  1950. return TypeInfo(Width, Align, AlignIsRequired);
  1951. }
  1952. unsigned ASTContext::getTypeUnadjustedAlign(const Type *T) const {
  1953. UnadjustedAlignMap::iterator I = MemoizedUnadjustedAlign.find(T);
  1954. if (I != MemoizedUnadjustedAlign.end())
  1955. return I->second;
  1956. unsigned UnadjustedAlign;
  1957. if (const auto *RT = T->getAs<RecordType>()) {
  1958. const RecordDecl *RD = RT->getDecl();
  1959. const ASTRecordLayout &Layout = getASTRecordLayout(RD);
  1960. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  1961. } else if (const auto *ObjCI = T->getAs<ObjCInterfaceType>()) {
  1962. const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
  1963. UnadjustedAlign = toBits(Layout.getUnadjustedAlignment());
  1964. } else {
  1965. UnadjustedAlign = getTypeAlign(T->getUnqualifiedDesugaredType());
  1966. }
  1967. MemoizedUnadjustedAlign[T] = UnadjustedAlign;
  1968. return UnadjustedAlign;
  1969. }
  1970. unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
  1971. unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
  1972. // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
  1973. if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
  1974. getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
  1975. getTargetInfo().getABI() == "elfv1-qpx" &&
  1976. T->isSpecificBuiltinType(BuiltinType::Double))
  1977. SimdAlign = 256;
  1978. return SimdAlign;
  1979. }
  1980. /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
  1981. CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
  1982. return CharUnits::fromQuantity(BitSize / getCharWidth());
  1983. }
  1984. /// toBits - Convert a size in characters to a size in characters.
  1985. int64_t ASTContext::toBits(CharUnits CharSize) const {
  1986. return CharSize.getQuantity() * getCharWidth();
  1987. }
  1988. /// getTypeSizeInChars - Return the size of the specified type, in characters.
  1989. /// This method does not work on incomplete types.
  1990. CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
  1991. return getTypeInfoInChars(T).first;
  1992. }
  1993. CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
  1994. return getTypeInfoInChars(T).first;
  1995. }
  1996. /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
  1997. /// characters. This method does not work on incomplete types.
  1998. CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
  1999. return toCharUnitsFromBits(getTypeAlign(T));
  2000. }
  2001. CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
  2002. return toCharUnitsFromBits(getTypeAlign(T));
  2003. }
  2004. /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a
  2005. /// type, in characters, before alignment adustments. This method does
  2006. /// not work on incomplete types.
  2007. CharUnits ASTContext::getTypeUnadjustedAlignInChars(QualType T) const {
  2008. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2009. }
  2010. CharUnits ASTContext::getTypeUnadjustedAlignInChars(const Type *T) const {
  2011. return toCharUnitsFromBits(getTypeUnadjustedAlign(T));
  2012. }
  2013. /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
  2014. /// type for the current target in bits. This can be different than the ABI
  2015. /// alignment in cases where it is beneficial for performance to overalign
  2016. /// a data type.
  2017. unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
  2018. TypeInfo TI = getTypeInfo(T);
  2019. unsigned ABIAlign = TI.Align;
  2020. T = T->getBaseElementTypeUnsafe();
  2021. // The preferred alignment of member pointers is that of a pointer.
  2022. if (T->isMemberPointerType())
  2023. return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
  2024. if (!Target->allowsLargerPreferedTypeAlignment())
  2025. return ABIAlign;
  2026. // Double and long long should be naturally aligned if possible.
  2027. if (const auto *CT = T->getAs<ComplexType>())
  2028. T = CT->getElementType().getTypePtr();
  2029. if (const auto *ET = T->getAs<EnumType>())
  2030. T = ET->getDecl()->getIntegerType().getTypePtr();
  2031. if (T->isSpecificBuiltinType(BuiltinType::Double) ||
  2032. T->isSpecificBuiltinType(BuiltinType::LongLong) ||
  2033. T->isSpecificBuiltinType(BuiltinType::ULongLong))
  2034. // Don't increase the alignment if an alignment attribute was specified on a
  2035. // typedef declaration.
  2036. if (!TI.AlignIsRequired)
  2037. return std::max(ABIAlign, (unsigned)getTypeSize(T));
  2038. return ABIAlign;
  2039. }
  2040. /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
  2041. /// for __attribute__((aligned)) on this target, to be used if no alignment
  2042. /// value is specified.
  2043. unsigned ASTContext::getTargetDefaultAlignForAttributeAligned() const {
  2044. return getTargetInfo().getDefaultAlignForAttributeAligned();
  2045. }
  2046. /// getAlignOfGlobalVar - Return the alignment in bits that should be given
  2047. /// to a global variable of the specified type.
  2048. unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
  2049. uint64_t TypeSize = getTypeSize(T.getTypePtr());
  2050. return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign(TypeSize));
  2051. }
  2052. /// getAlignOfGlobalVarInChars - Return the alignment in characters that
  2053. /// should be given to a global variable of the specified type.
  2054. CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
  2055. return toCharUnitsFromBits(getAlignOfGlobalVar(T));
  2056. }
  2057. CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
  2058. CharUnits Offset = CharUnits::Zero();
  2059. const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
  2060. while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
  2061. Offset += Layout->getBaseClassOffset(Base);
  2062. Layout = &getASTRecordLayout(Base);
  2063. }
  2064. return Offset;
  2065. }
  2066. /// DeepCollectObjCIvars -
  2067. /// This routine first collects all declared, but not synthesized, ivars in
  2068. /// super class and then collects all ivars, including those synthesized for
  2069. /// current class. This routine is used for implementation of current class
  2070. /// when all ivars, declared and synthesized are known.
  2071. void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
  2072. bool leafClass,
  2073. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
  2074. if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
  2075. DeepCollectObjCIvars(SuperClass, false, Ivars);
  2076. if (!leafClass) {
  2077. for (const auto *I : OI->ivars())
  2078. Ivars.push_back(I);
  2079. } else {
  2080. auto *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
  2081. for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
  2082. Iv= Iv->getNextIvar())
  2083. Ivars.push_back(Iv);
  2084. }
  2085. }
  2086. /// CollectInheritedProtocols - Collect all protocols in current class and
  2087. /// those inherited by it.
  2088. void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
  2089. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
  2090. if (const auto *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
  2091. // We can use protocol_iterator here instead of
  2092. // all_referenced_protocol_iterator since we are walking all categories.
  2093. for (auto *Proto : OI->all_referenced_protocols()) {
  2094. CollectInheritedProtocols(Proto, Protocols);
  2095. }
  2096. // Categories of this Interface.
  2097. for (const auto *Cat : OI->visible_categories())
  2098. CollectInheritedProtocols(Cat, Protocols);
  2099. if (ObjCInterfaceDecl *SD = OI->getSuperClass())
  2100. while (SD) {
  2101. CollectInheritedProtocols(SD, Protocols);
  2102. SD = SD->getSuperClass();
  2103. }
  2104. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
  2105. for (auto *Proto : OC->protocols()) {
  2106. CollectInheritedProtocols(Proto, Protocols);
  2107. }
  2108. } else if (const auto *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
  2109. // Insert the protocol.
  2110. if (!Protocols.insert(
  2111. const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
  2112. return;
  2113. for (auto *Proto : OP->protocols())
  2114. CollectInheritedProtocols(Proto, Protocols);
  2115. }
  2116. }
  2117. static bool unionHasUniqueObjectRepresentations(const ASTContext &Context,
  2118. const RecordDecl *RD) {
  2119. assert(RD->isUnion() && "Must be union type");
  2120. CharUnits UnionSize = Context.getTypeSizeInChars(RD->getTypeForDecl());
  2121. for (const auto *Field : RD->fields()) {
  2122. if (!Context.hasUniqueObjectRepresentations(Field->getType()))
  2123. return false;
  2124. CharUnits FieldSize = Context.getTypeSizeInChars(Field->getType());
  2125. if (FieldSize != UnionSize)
  2126. return false;
  2127. }
  2128. return !RD->field_empty();
  2129. }
  2130. static bool isStructEmpty(QualType Ty) {
  2131. const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
  2132. if (!RD->field_empty())
  2133. return false;
  2134. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD))
  2135. return ClassDecl->isEmpty();
  2136. return true;
  2137. }
  2138. static llvm::Optional<int64_t>
  2139. structHasUniqueObjectRepresentations(const ASTContext &Context,
  2140. const RecordDecl *RD) {
  2141. assert(!RD->isUnion() && "Must be struct/class type");
  2142. const auto &Layout = Context.getASTRecordLayout(RD);
  2143. int64_t CurOffsetInBits = 0;
  2144. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RD)) {
  2145. if (ClassDecl->isDynamicClass())
  2146. return llvm::None;
  2147. SmallVector<std::pair<QualType, int64_t>, 4> Bases;
  2148. for (const auto Base : ClassDecl->bases()) {
  2149. // Empty types can be inherited from, and non-empty types can potentially
  2150. // have tail padding, so just make sure there isn't an error.
  2151. if (!isStructEmpty(Base.getType())) {
  2152. llvm::Optional<int64_t> Size = structHasUniqueObjectRepresentations(
  2153. Context, Base.getType()->castAs<RecordType>()->getDecl());
  2154. if (!Size)
  2155. return llvm::None;
  2156. Bases.emplace_back(Base.getType(), Size.getValue());
  2157. }
  2158. }
  2159. llvm::sort(Bases, [&](const std::pair<QualType, int64_t> &L,
  2160. const std::pair<QualType, int64_t> &R) {
  2161. return Layout.getBaseClassOffset(L.first->getAsCXXRecordDecl()) <
  2162. Layout.getBaseClassOffset(R.first->getAsCXXRecordDecl());
  2163. });
  2164. for (const auto Base : Bases) {
  2165. int64_t BaseOffset = Context.toBits(
  2166. Layout.getBaseClassOffset(Base.first->getAsCXXRecordDecl()));
  2167. int64_t BaseSize = Base.second;
  2168. if (BaseOffset != CurOffsetInBits)
  2169. return llvm::None;
  2170. CurOffsetInBits = BaseOffset + BaseSize;
  2171. }
  2172. }
  2173. for (const auto *Field : RD->fields()) {
  2174. if (!Field->getType()->isReferenceType() &&
  2175. !Context.hasUniqueObjectRepresentations(Field->getType()))
  2176. return llvm::None;
  2177. int64_t FieldSizeInBits =
  2178. Context.toBits(Context.getTypeSizeInChars(Field->getType()));
  2179. if (Field->isBitField()) {
  2180. int64_t BitfieldSize = Field->getBitWidthValue(Context);
  2181. if (BitfieldSize > FieldSizeInBits)
  2182. return llvm::None;
  2183. FieldSizeInBits = BitfieldSize;
  2184. }
  2185. int64_t FieldOffsetInBits = Context.getFieldOffset(Field);
  2186. if (FieldOffsetInBits != CurOffsetInBits)
  2187. return llvm::None;
  2188. CurOffsetInBits = FieldSizeInBits + FieldOffsetInBits;
  2189. }
  2190. return CurOffsetInBits;
  2191. }
  2192. bool ASTContext::hasUniqueObjectRepresentations(QualType Ty) const {
  2193. // C++17 [meta.unary.prop]:
  2194. // The predicate condition for a template specialization
  2195. // has_unique_object_representations<T> shall be
  2196. // satisfied if and only if:
  2197. // (9.1) - T is trivially copyable, and
  2198. // (9.2) - any two objects of type T with the same value have the same
  2199. // object representation, where two objects
  2200. // of array or non-union class type are considered to have the same value
  2201. // if their respective sequences of
  2202. // direct subobjects have the same values, and two objects of union type
  2203. // are considered to have the same
  2204. // value if they have the same active member and the corresponding members
  2205. // have the same value.
  2206. // The set of scalar types for which this condition holds is
  2207. // implementation-defined. [ Note: If a type has padding
  2208. // bits, the condition does not hold; otherwise, the condition holds true
  2209. // for unsigned integral types. -- end note ]
  2210. assert(!Ty.isNull() && "Null QualType sent to unique object rep check");
  2211. // Arrays are unique only if their element type is unique.
  2212. if (Ty->isArrayType())
  2213. return hasUniqueObjectRepresentations(getBaseElementType(Ty));
  2214. // (9.1) - T is trivially copyable...
  2215. if (!Ty.isTriviallyCopyableType(*this))
  2216. return false;
  2217. // All integrals and enums are unique.
  2218. if (Ty->isIntegralOrEnumerationType())
  2219. return true;
  2220. // All other pointers are unique.
  2221. if (Ty->isPointerType())
  2222. return true;
  2223. if (Ty->isMemberPointerType()) {
  2224. const auto *MPT = Ty->getAs<MemberPointerType>();
  2225. return !ABI->getMemberPointerInfo(MPT).HasPadding;
  2226. }
  2227. if (Ty->isRecordType()) {
  2228. const RecordDecl *Record = Ty->castAs<RecordType>()->getDecl();
  2229. if (Record->isInvalidDecl())
  2230. return false;
  2231. if (Record->isUnion())
  2232. return unionHasUniqueObjectRepresentations(*this, Record);
  2233. Optional<int64_t> StructSize =
  2234. structHasUniqueObjectRepresentations(*this, Record);
  2235. return StructSize &&
  2236. StructSize.getValue() == static_cast<int64_t>(getTypeSize(Ty));
  2237. }
  2238. // FIXME: More cases to handle here (list by rsmith):
  2239. // vectors (careful about, eg, vector of 3 foo)
  2240. // _Complex int and friends
  2241. // _Atomic T
  2242. // Obj-C block pointers
  2243. // Obj-C object pointers
  2244. // and perhaps OpenCL's various builtin types (pipe, sampler_t, event_t,
  2245. // clk_event_t, queue_t, reserve_id_t)
  2246. // There're also Obj-C class types and the Obj-C selector type, but I think it
  2247. // makes sense for those to return false here.
  2248. return false;
  2249. }
  2250. unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
  2251. unsigned count = 0;
  2252. // Count ivars declared in class extension.
  2253. for (const auto *Ext : OI->known_extensions())
  2254. count += Ext->ivar_size();
  2255. // Count ivar defined in this class's implementation. This
  2256. // includes synthesized ivars.
  2257. if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
  2258. count += ImplDecl->ivar_size();
  2259. return count;
  2260. }
  2261. bool ASTContext::isSentinelNullExpr(const Expr *E) {
  2262. if (!E)
  2263. return false;
  2264. // nullptr_t is always treated as null.
  2265. if (E->getType()->isNullPtrType()) return true;
  2266. if (E->getType()->isAnyPointerType() &&
  2267. E->IgnoreParenCasts()->isNullPointerConstant(*this,
  2268. Expr::NPC_ValueDependentIsNull))
  2269. return true;
  2270. // Unfortunately, __null has type 'int'.
  2271. if (isa<GNUNullExpr>(E)) return true;
  2272. return false;
  2273. }
  2274. /// Get the implementation of ObjCInterfaceDecl, or nullptr if none
  2275. /// exists.
  2276. ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
  2277. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2278. I = ObjCImpls.find(D);
  2279. if (I != ObjCImpls.end())
  2280. return cast<ObjCImplementationDecl>(I->second);
  2281. return nullptr;
  2282. }
  2283. /// Get the implementation of ObjCCategoryDecl, or nullptr if none
  2284. /// exists.
  2285. ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
  2286. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
  2287. I = ObjCImpls.find(D);
  2288. if (I != ObjCImpls.end())
  2289. return cast<ObjCCategoryImplDecl>(I->second);
  2290. return nullptr;
  2291. }
  2292. /// Set the implementation of ObjCInterfaceDecl.
  2293. void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  2294. ObjCImplementationDecl *ImplD) {
  2295. assert(IFaceD && ImplD && "Passed null params");
  2296. ObjCImpls[IFaceD] = ImplD;
  2297. }
  2298. /// Set the implementation of ObjCCategoryDecl.
  2299. void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
  2300. ObjCCategoryImplDecl *ImplD) {
  2301. assert(CatD && ImplD && "Passed null params");
  2302. ObjCImpls[CatD] = ImplD;
  2303. }
  2304. const ObjCMethodDecl *
  2305. ASTContext::getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const {
  2306. return ObjCMethodRedecls.lookup(MD);
  2307. }
  2308. void ASTContext::setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
  2309. const ObjCMethodDecl *Redecl) {
  2310. assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
  2311. ObjCMethodRedecls[MD] = Redecl;
  2312. }
  2313. const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
  2314. const NamedDecl *ND) const {
  2315. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
  2316. return ID;
  2317. if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
  2318. return CD->getClassInterface();
  2319. if (const auto *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
  2320. return IMD->getClassInterface();
  2321. return nullptr;
  2322. }
  2323. /// Get the copy initialization expression of VarDecl, or nullptr if
  2324. /// none exists.
  2325. ASTContext::BlockVarCopyInit
  2326. ASTContext::getBlockVarCopyInit(const VarDecl*VD) const {
  2327. assert(VD && "Passed null params");
  2328. assert(VD->hasAttr<BlocksAttr>() &&
  2329. "getBlockVarCopyInits - not __block var");
  2330. auto I = BlockVarCopyInits.find(VD);
  2331. if (I != BlockVarCopyInits.end())
  2332. return I->second;
  2333. return {nullptr, false};
  2334. }
  2335. /// Set the copy initialization expression of a block var decl.
  2336. void ASTContext::setBlockVarCopyInit(const VarDecl*VD, Expr *CopyExpr,
  2337. bool CanThrow) {
  2338. assert(VD && CopyExpr && "Passed null params");
  2339. assert(VD->hasAttr<BlocksAttr>() &&
  2340. "setBlockVarCopyInits - not __block var");
  2341. BlockVarCopyInits[VD].setExprAndFlag(CopyExpr, CanThrow);
  2342. }
  2343. TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
  2344. unsigned DataSize) const {
  2345. if (!DataSize)
  2346. DataSize = TypeLoc::getFullDataSizeForType(T);
  2347. else
  2348. assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
  2349. "incorrect data size provided to CreateTypeSourceInfo!");
  2350. auto *TInfo =
  2351. (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
  2352. new (TInfo) TypeSourceInfo(T);
  2353. return TInfo;
  2354. }
  2355. TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
  2356. SourceLocation L) const {
  2357. TypeSourceInfo *DI = CreateTypeSourceInfo(T);
  2358. DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
  2359. return DI;
  2360. }
  2361. const ASTRecordLayout &
  2362. ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
  2363. return getObjCLayout(D, nullptr);
  2364. }
  2365. const ASTRecordLayout &
  2366. ASTContext::getASTObjCImplementationLayout(
  2367. const ObjCImplementationDecl *D) const {
  2368. return getObjCLayout(D->getClassInterface(), D);
  2369. }
  2370. //===----------------------------------------------------------------------===//
  2371. // Type creation/memoization methods
  2372. //===----------------------------------------------------------------------===//
  2373. QualType
  2374. ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
  2375. unsigned fastQuals = quals.getFastQualifiers();
  2376. quals.removeFastQualifiers();
  2377. // Check if we've already instantiated this type.
  2378. llvm::FoldingSetNodeID ID;
  2379. ExtQuals::Profile(ID, baseType, quals);
  2380. void *insertPos = nullptr;
  2381. if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
  2382. assert(eq->getQualifiers() == quals);
  2383. return QualType(eq, fastQuals);
  2384. }
  2385. // If the base type is not canonical, make the appropriate canonical type.
  2386. QualType canon;
  2387. if (!baseType->isCanonicalUnqualified()) {
  2388. SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
  2389. canonSplit.Quals.addConsistentQualifiers(quals);
  2390. canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
  2391. // Re-find the insert position.
  2392. (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
  2393. }
  2394. auto *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
  2395. ExtQualNodes.InsertNode(eq, insertPos);
  2396. return QualType(eq, fastQuals);
  2397. }
  2398. QualType ASTContext::getAddrSpaceQualType(QualType T,
  2399. LangAS AddressSpace) const {
  2400. QualType CanT = getCanonicalType(T);
  2401. if (CanT.getAddressSpace() == AddressSpace)
  2402. return T;
  2403. // If we are composing extended qualifiers together, merge together
  2404. // into one ExtQuals node.
  2405. QualifierCollector Quals;
  2406. const Type *TypeNode = Quals.strip(T);
  2407. // If this type already has an address space specified, it cannot get
  2408. // another one.
  2409. assert(!Quals.hasAddressSpace() &&
  2410. "Type cannot be in multiple addr spaces!");
  2411. Quals.addAddressSpace(AddressSpace);
  2412. return getExtQualType(TypeNode, Quals);
  2413. }
  2414. QualType ASTContext::removeAddrSpaceQualType(QualType T) const {
  2415. // If we are composing extended qualifiers together, merge together
  2416. // into one ExtQuals node.
  2417. QualifierCollector Quals;
  2418. const Type *TypeNode = Quals.strip(T);
  2419. // If the qualifier doesn't have an address space just return it.
  2420. if (!Quals.hasAddressSpace())
  2421. return T;
  2422. Quals.removeAddressSpace();
  2423. // Removal of the address space can mean there are no longer any
  2424. // non-fast qualifiers, so creating an ExtQualType isn't possible (asserts)
  2425. // or required.
  2426. if (Quals.hasNonFastQualifiers())
  2427. return getExtQualType(TypeNode, Quals);
  2428. else
  2429. return QualType(TypeNode, Quals.getFastQualifiers());
  2430. }
  2431. QualType ASTContext::getObjCGCQualType(QualType T,
  2432. Qualifiers::GC GCAttr) const {
  2433. QualType CanT = getCanonicalType(T);
  2434. if (CanT.getObjCGCAttr() == GCAttr)
  2435. return T;
  2436. if (const auto *ptr = T->getAs<PointerType>()) {
  2437. QualType Pointee = ptr->getPointeeType();
  2438. if (Pointee->isAnyPointerType()) {
  2439. QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
  2440. return getPointerType(ResultType);
  2441. }
  2442. }
  2443. // If we are composing extended qualifiers together, merge together
  2444. // into one ExtQuals node.
  2445. QualifierCollector Quals;
  2446. const Type *TypeNode = Quals.strip(T);
  2447. // If this type already has an ObjCGC specified, it cannot get
  2448. // another one.
  2449. assert(!Quals.hasObjCGCAttr() &&
  2450. "Type cannot have multiple ObjCGCs!");
  2451. Quals.addObjCGCAttr(GCAttr);
  2452. return getExtQualType(TypeNode, Quals);
  2453. }
  2454. const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
  2455. FunctionType::ExtInfo Info) {
  2456. if (T->getExtInfo() == Info)
  2457. return T;
  2458. QualType Result;
  2459. if (const auto *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
  2460. Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
  2461. } else {
  2462. const auto *FPT = cast<FunctionProtoType>(T);
  2463. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2464. EPI.ExtInfo = Info;
  2465. Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
  2466. }
  2467. return cast<FunctionType>(Result.getTypePtr());
  2468. }
  2469. void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
  2470. QualType ResultType) {
  2471. FD = FD->getMostRecentDecl();
  2472. while (true) {
  2473. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  2474. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  2475. FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
  2476. if (FunctionDecl *Next = FD->getPreviousDecl())
  2477. FD = Next;
  2478. else
  2479. break;
  2480. }
  2481. if (ASTMutationListener *L = getASTMutationListener())
  2482. L->DeducedReturnType(FD, ResultType);
  2483. }
  2484. /// Get a function type and produce the equivalent function type with the
  2485. /// specified exception specification. Type sugar that can be present on a
  2486. /// declaration of a function with an exception specification is permitted
  2487. /// and preserved. Other type sugar (for instance, typedefs) is not.
  2488. QualType ASTContext::getFunctionTypeWithExceptionSpec(
  2489. QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) {
  2490. // Might have some parens.
  2491. if (const auto *PT = dyn_cast<ParenType>(Orig))
  2492. return getParenType(
  2493. getFunctionTypeWithExceptionSpec(PT->getInnerType(), ESI));
  2494. // Might be wrapped in a macro qualified type.
  2495. if (const auto *MQT = dyn_cast<MacroQualifiedType>(Orig))
  2496. return getMacroQualifiedType(
  2497. getFunctionTypeWithExceptionSpec(MQT->getUnderlyingType(), ESI),
  2498. MQT->getMacroIdentifier());
  2499. // Might have a calling-convention attribute.
  2500. if (const auto *AT = dyn_cast<AttributedType>(Orig))
  2501. return getAttributedType(
  2502. AT->getAttrKind(),
  2503. getFunctionTypeWithExceptionSpec(AT->getModifiedType(), ESI),
  2504. getFunctionTypeWithExceptionSpec(AT->getEquivalentType(), ESI));
  2505. // Anything else must be a function type. Rebuild it with the new exception
  2506. // specification.
  2507. const auto *Proto = Orig->castAs<FunctionProtoType>();
  2508. return getFunctionType(
  2509. Proto->getReturnType(), Proto->getParamTypes(),
  2510. Proto->getExtProtoInfo().withExceptionSpec(ESI));
  2511. }
  2512. bool ASTContext::hasSameFunctionTypeIgnoringExceptionSpec(QualType T,
  2513. QualType U) {
  2514. return hasSameType(T, U) ||
  2515. (getLangOpts().CPlusPlus17 &&
  2516. hasSameType(getFunctionTypeWithExceptionSpec(T, EST_None),
  2517. getFunctionTypeWithExceptionSpec(U, EST_None)));
  2518. }
  2519. void ASTContext::adjustExceptionSpec(
  2520. FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
  2521. bool AsWritten) {
  2522. // Update the type.
  2523. QualType Updated =
  2524. getFunctionTypeWithExceptionSpec(FD->getType(), ESI);
  2525. FD->setType(Updated);
  2526. if (!AsWritten)
  2527. return;
  2528. // Update the type in the type source information too.
  2529. if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
  2530. // If the type and the type-as-written differ, we may need to update
  2531. // the type-as-written too.
  2532. if (TSInfo->getType() != FD->getType())
  2533. Updated = getFunctionTypeWithExceptionSpec(TSInfo->getType(), ESI);
  2534. // FIXME: When we get proper type location information for exceptions,
  2535. // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
  2536. // up the TypeSourceInfo;
  2537. assert(TypeLoc::getFullDataSizeForType(Updated) ==
  2538. TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
  2539. "TypeLoc size mismatch from updating exception specification");
  2540. TSInfo->overrideType(Updated);
  2541. }
  2542. }
  2543. /// getComplexType - Return the uniqued reference to the type for a complex
  2544. /// number with the specified element type.
  2545. QualType ASTContext::getComplexType(QualType T) const {
  2546. // Unique pointers, to guarantee there is only one pointer of a particular
  2547. // structure.
  2548. llvm::FoldingSetNodeID ID;
  2549. ComplexType::Profile(ID, T);
  2550. void *InsertPos = nullptr;
  2551. if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
  2552. return QualType(CT, 0);
  2553. // If the pointee type isn't canonical, this won't be a canonical type either,
  2554. // so fill in the canonical type field.
  2555. QualType Canonical;
  2556. if (!T.isCanonical()) {
  2557. Canonical = getComplexType(getCanonicalType(T));
  2558. // Get the new insert position for the node we care about.
  2559. ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
  2560. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2561. }
  2562. auto *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
  2563. Types.push_back(New);
  2564. ComplexTypes.InsertNode(New, InsertPos);
  2565. return QualType(New, 0);
  2566. }
  2567. /// getPointerType - Return the uniqued reference to the type for a pointer to
  2568. /// the specified type.
  2569. QualType ASTContext::getPointerType(QualType T) const {
  2570. // Unique pointers, to guarantee there is only one pointer of a particular
  2571. // structure.
  2572. llvm::FoldingSetNodeID ID;
  2573. PointerType::Profile(ID, T);
  2574. void *InsertPos = nullptr;
  2575. if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2576. return QualType(PT, 0);
  2577. // If the pointee type isn't canonical, this won't be a canonical type either,
  2578. // so fill in the canonical type field.
  2579. QualType Canonical;
  2580. if (!T.isCanonical()) {
  2581. Canonical = getPointerType(getCanonicalType(T));
  2582. // Get the new insert position for the node we care about.
  2583. PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2584. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2585. }
  2586. auto *New = new (*this, TypeAlignment) PointerType(T, Canonical);
  2587. Types.push_back(New);
  2588. PointerTypes.InsertNode(New, InsertPos);
  2589. return QualType(New, 0);
  2590. }
  2591. QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
  2592. llvm::FoldingSetNodeID ID;
  2593. AdjustedType::Profile(ID, Orig, New);
  2594. void *InsertPos = nullptr;
  2595. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2596. if (AT)
  2597. return QualType(AT, 0);
  2598. QualType Canonical = getCanonicalType(New);
  2599. // Get the new insert position for the node we care about.
  2600. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2601. assert(!AT && "Shouldn't be in the map!");
  2602. AT = new (*this, TypeAlignment)
  2603. AdjustedType(Type::Adjusted, Orig, New, Canonical);
  2604. Types.push_back(AT);
  2605. AdjustedTypes.InsertNode(AT, InsertPos);
  2606. return QualType(AT, 0);
  2607. }
  2608. QualType ASTContext::getDecayedType(QualType T) const {
  2609. assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
  2610. QualType Decayed;
  2611. // C99 6.7.5.3p7:
  2612. // A declaration of a parameter as "array of type" shall be
  2613. // adjusted to "qualified pointer to type", where the type
  2614. // qualifiers (if any) are those specified within the [ and ] of
  2615. // the array type derivation.
  2616. if (T->isArrayType())
  2617. Decayed = getArrayDecayedType(T);
  2618. // C99 6.7.5.3p8:
  2619. // A declaration of a parameter as "function returning type"
  2620. // shall be adjusted to "pointer to function returning type", as
  2621. // in 6.3.2.1.
  2622. if (T->isFunctionType())
  2623. Decayed = getPointerType(T);
  2624. llvm::FoldingSetNodeID ID;
  2625. AdjustedType::Profile(ID, T, Decayed);
  2626. void *InsertPos = nullptr;
  2627. AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2628. if (AT)
  2629. return QualType(AT, 0);
  2630. QualType Canonical = getCanonicalType(Decayed);
  2631. // Get the new insert position for the node we care about.
  2632. AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
  2633. assert(!AT && "Shouldn't be in the map!");
  2634. AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
  2635. Types.push_back(AT);
  2636. AdjustedTypes.InsertNode(AT, InsertPos);
  2637. return QualType(AT, 0);
  2638. }
  2639. /// getBlockPointerType - Return the uniqued reference to the type for
  2640. /// a pointer to the specified block.
  2641. QualType ASTContext::getBlockPointerType(QualType T) const {
  2642. assert(T->isFunctionType() && "block of function types only");
  2643. // Unique pointers, to guarantee there is only one block of a particular
  2644. // structure.
  2645. llvm::FoldingSetNodeID ID;
  2646. BlockPointerType::Profile(ID, T);
  2647. void *InsertPos = nullptr;
  2648. if (BlockPointerType *PT =
  2649. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2650. return QualType(PT, 0);
  2651. // If the block pointee type isn't canonical, this won't be a canonical
  2652. // type either so fill in the canonical type field.
  2653. QualType Canonical;
  2654. if (!T.isCanonical()) {
  2655. Canonical = getBlockPointerType(getCanonicalType(T));
  2656. // Get the new insert position for the node we care about.
  2657. BlockPointerType *NewIP =
  2658. BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2659. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2660. }
  2661. auto *New = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
  2662. Types.push_back(New);
  2663. BlockPointerTypes.InsertNode(New, InsertPos);
  2664. return QualType(New, 0);
  2665. }
  2666. /// getLValueReferenceType - Return the uniqued reference to the type for an
  2667. /// lvalue reference to the specified type.
  2668. QualType
  2669. ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
  2670. assert(getCanonicalType(T) != OverloadTy &&
  2671. "Unresolved overloaded function type");
  2672. // Unique pointers, to guarantee there is only one pointer of a particular
  2673. // structure.
  2674. llvm::FoldingSetNodeID ID;
  2675. ReferenceType::Profile(ID, T, SpelledAsLValue);
  2676. void *InsertPos = nullptr;
  2677. if (LValueReferenceType *RT =
  2678. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2679. return QualType(RT, 0);
  2680. const auto *InnerRef = T->getAs<ReferenceType>();
  2681. // If the referencee type isn't canonical, this won't be a canonical type
  2682. // either, so fill in the canonical type field.
  2683. QualType Canonical;
  2684. if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
  2685. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2686. Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
  2687. // Get the new insert position for the node we care about.
  2688. LValueReferenceType *NewIP =
  2689. LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2690. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2691. }
  2692. auto *New = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
  2693. SpelledAsLValue);
  2694. Types.push_back(New);
  2695. LValueReferenceTypes.InsertNode(New, InsertPos);
  2696. return QualType(New, 0);
  2697. }
  2698. /// getRValueReferenceType - Return the uniqued reference to the type for an
  2699. /// rvalue reference to the specified type.
  2700. QualType ASTContext::getRValueReferenceType(QualType T) const {
  2701. // Unique pointers, to guarantee there is only one pointer of a particular
  2702. // structure.
  2703. llvm::FoldingSetNodeID ID;
  2704. ReferenceType::Profile(ID, T, false);
  2705. void *InsertPos = nullptr;
  2706. if (RValueReferenceType *RT =
  2707. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
  2708. return QualType(RT, 0);
  2709. const auto *InnerRef = T->getAs<ReferenceType>();
  2710. // If the referencee type isn't canonical, this won't be a canonical type
  2711. // either, so fill in the canonical type field.
  2712. QualType Canonical;
  2713. if (InnerRef || !T.isCanonical()) {
  2714. QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
  2715. Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
  2716. // Get the new insert position for the node we care about.
  2717. RValueReferenceType *NewIP =
  2718. RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
  2719. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2720. }
  2721. auto *New = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
  2722. Types.push_back(New);
  2723. RValueReferenceTypes.InsertNode(New, InsertPos);
  2724. return QualType(New, 0);
  2725. }
  2726. /// getMemberPointerType - Return the uniqued reference to the type for a
  2727. /// member pointer to the specified type, in the specified class.
  2728. QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
  2729. // Unique pointers, to guarantee there is only one pointer of a particular
  2730. // structure.
  2731. llvm::FoldingSetNodeID ID;
  2732. MemberPointerType::Profile(ID, T, Cls);
  2733. void *InsertPos = nullptr;
  2734. if (MemberPointerType *PT =
  2735. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  2736. return QualType(PT, 0);
  2737. // If the pointee or class type isn't canonical, this won't be a canonical
  2738. // type either, so fill in the canonical type field.
  2739. QualType Canonical;
  2740. if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
  2741. Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
  2742. // Get the new insert position for the node we care about.
  2743. MemberPointerType *NewIP =
  2744. MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  2745. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2746. }
  2747. auto *New = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
  2748. Types.push_back(New);
  2749. MemberPointerTypes.InsertNode(New, InsertPos);
  2750. return QualType(New, 0);
  2751. }
  2752. /// getConstantArrayType - Return the unique reference to the type for an
  2753. /// array of the specified element type.
  2754. QualType ASTContext::getConstantArrayType(QualType EltTy,
  2755. const llvm::APInt &ArySizeIn,
  2756. const Expr *SizeExpr,
  2757. ArrayType::ArraySizeModifier ASM,
  2758. unsigned IndexTypeQuals) const {
  2759. assert((EltTy->isDependentType() ||
  2760. EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
  2761. "Constant array of VLAs is illegal!");
  2762. // We only need the size as part of the type if it's instantiation-dependent.
  2763. if (SizeExpr && !SizeExpr->isInstantiationDependent())
  2764. SizeExpr = nullptr;
  2765. // Convert the array size into a canonical width matching the pointer size for
  2766. // the target.
  2767. llvm::APInt ArySize(ArySizeIn);
  2768. ArySize = ArySize.zextOrTrunc(Target->getMaxPointerWidth());
  2769. llvm::FoldingSetNodeID ID;
  2770. ConstantArrayType::Profile(ID, *this, EltTy, ArySize, SizeExpr, ASM,
  2771. IndexTypeQuals);
  2772. void *InsertPos = nullptr;
  2773. if (ConstantArrayType *ATP =
  2774. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
  2775. return QualType(ATP, 0);
  2776. // If the element type isn't canonical or has qualifiers, or the array bound
  2777. // is instantiation-dependent, this won't be a canonical type either, so fill
  2778. // in the canonical type field.
  2779. QualType Canon;
  2780. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers() || SizeExpr) {
  2781. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2782. Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, nullptr,
  2783. ASM, IndexTypeQuals);
  2784. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2785. // Get the new insert position for the node we care about.
  2786. ConstantArrayType *NewIP =
  2787. ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
  2788. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  2789. }
  2790. void *Mem = Allocate(
  2791. ConstantArrayType::totalSizeToAlloc<const Expr *>(SizeExpr ? 1 : 0),
  2792. TypeAlignment);
  2793. auto *New = new (Mem)
  2794. ConstantArrayType(EltTy, Canon, ArySize, SizeExpr, ASM, IndexTypeQuals);
  2795. ConstantArrayTypes.InsertNode(New, InsertPos);
  2796. Types.push_back(New);
  2797. return QualType(New, 0);
  2798. }
  2799. /// getVariableArrayDecayedType - Turns the given type, which may be
  2800. /// variably-modified, into the corresponding type with all the known
  2801. /// sizes replaced with [*].
  2802. QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
  2803. // Vastly most common case.
  2804. if (!type->isVariablyModifiedType()) return type;
  2805. QualType result;
  2806. SplitQualType split = type.getSplitDesugaredType();
  2807. const Type *ty = split.Ty;
  2808. switch (ty->getTypeClass()) {
  2809. #define TYPE(Class, Base)
  2810. #define ABSTRACT_TYPE(Class, Base)
  2811. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  2812. #include "clang/AST/TypeNodes.inc"
  2813. llvm_unreachable("didn't desugar past all non-canonical types?");
  2814. // These types should never be variably-modified.
  2815. case Type::Builtin:
  2816. case Type::Complex:
  2817. case Type::Vector:
  2818. case Type::DependentVector:
  2819. case Type::ExtVector:
  2820. case Type::DependentSizedExtVector:
  2821. case Type::DependentAddressSpace:
  2822. case Type::ObjCObject:
  2823. case Type::ObjCInterface:
  2824. case Type::ObjCObjectPointer:
  2825. case Type::Record:
  2826. case Type::Enum:
  2827. case Type::UnresolvedUsing:
  2828. case Type::TypeOfExpr:
  2829. case Type::TypeOf:
  2830. case Type::Decltype:
  2831. case Type::UnaryTransform:
  2832. case Type::DependentName:
  2833. case Type::InjectedClassName:
  2834. case Type::TemplateSpecialization:
  2835. case Type::DependentTemplateSpecialization:
  2836. case Type::TemplateTypeParm:
  2837. case Type::SubstTemplateTypeParmPack:
  2838. case Type::Auto:
  2839. case Type::DeducedTemplateSpecialization:
  2840. case Type::PackExpansion:
  2841. llvm_unreachable("type should never be variably-modified");
  2842. // These types can be variably-modified but should never need to
  2843. // further decay.
  2844. case Type::FunctionNoProto:
  2845. case Type::FunctionProto:
  2846. case Type::BlockPointer:
  2847. case Type::MemberPointer:
  2848. case Type::Pipe:
  2849. return type;
  2850. // These types can be variably-modified. All these modifications
  2851. // preserve structure except as noted by comments.
  2852. // TODO: if we ever care about optimizing VLAs, there are no-op
  2853. // optimizations available here.
  2854. case Type::Pointer:
  2855. result = getPointerType(getVariableArrayDecayedType(
  2856. cast<PointerType>(ty)->getPointeeType()));
  2857. break;
  2858. case Type::LValueReference: {
  2859. const auto *lv = cast<LValueReferenceType>(ty);
  2860. result = getLValueReferenceType(
  2861. getVariableArrayDecayedType(lv->getPointeeType()),
  2862. lv->isSpelledAsLValue());
  2863. break;
  2864. }
  2865. case Type::RValueReference: {
  2866. const auto *lv = cast<RValueReferenceType>(ty);
  2867. result = getRValueReferenceType(
  2868. getVariableArrayDecayedType(lv->getPointeeType()));
  2869. break;
  2870. }
  2871. case Type::Atomic: {
  2872. const auto *at = cast<AtomicType>(ty);
  2873. result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
  2874. break;
  2875. }
  2876. case Type::ConstantArray: {
  2877. const auto *cat = cast<ConstantArrayType>(ty);
  2878. result = getConstantArrayType(
  2879. getVariableArrayDecayedType(cat->getElementType()),
  2880. cat->getSize(),
  2881. cat->getSizeExpr(),
  2882. cat->getSizeModifier(),
  2883. cat->getIndexTypeCVRQualifiers());
  2884. break;
  2885. }
  2886. case Type::DependentSizedArray: {
  2887. const auto *dat = cast<DependentSizedArrayType>(ty);
  2888. result = getDependentSizedArrayType(
  2889. getVariableArrayDecayedType(dat->getElementType()),
  2890. dat->getSizeExpr(),
  2891. dat->getSizeModifier(),
  2892. dat->getIndexTypeCVRQualifiers(),
  2893. dat->getBracketsRange());
  2894. break;
  2895. }
  2896. // Turn incomplete types into [*] types.
  2897. case Type::IncompleteArray: {
  2898. const auto *iat = cast<IncompleteArrayType>(ty);
  2899. result = getVariableArrayType(
  2900. getVariableArrayDecayedType(iat->getElementType()),
  2901. /*size*/ nullptr,
  2902. ArrayType::Normal,
  2903. iat->getIndexTypeCVRQualifiers(),
  2904. SourceRange());
  2905. break;
  2906. }
  2907. // Turn VLA types into [*] types.
  2908. case Type::VariableArray: {
  2909. const auto *vat = cast<VariableArrayType>(ty);
  2910. result = getVariableArrayType(
  2911. getVariableArrayDecayedType(vat->getElementType()),
  2912. /*size*/ nullptr,
  2913. ArrayType::Star,
  2914. vat->getIndexTypeCVRQualifiers(),
  2915. vat->getBracketsRange());
  2916. break;
  2917. }
  2918. }
  2919. // Apply the top-level qualifiers from the original.
  2920. return getQualifiedType(result, split.Quals);
  2921. }
  2922. /// getVariableArrayType - Returns a non-unique reference to the type for a
  2923. /// variable array of the specified element type.
  2924. QualType ASTContext::getVariableArrayType(QualType EltTy,
  2925. Expr *NumElts,
  2926. ArrayType::ArraySizeModifier ASM,
  2927. unsigned IndexTypeQuals,
  2928. SourceRange Brackets) const {
  2929. // Since we don't unique expressions, it isn't possible to unique VLA's
  2930. // that have an expression provided for their size.
  2931. QualType Canon;
  2932. // Be sure to pull qualifiers off the element type.
  2933. if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
  2934. SplitQualType canonSplit = getCanonicalType(EltTy).split();
  2935. Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
  2936. IndexTypeQuals, Brackets);
  2937. Canon = getQualifiedType(Canon, canonSplit.Quals);
  2938. }
  2939. auto *New = new (*this, TypeAlignment)
  2940. VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
  2941. VariableArrayTypes.push_back(New);
  2942. Types.push_back(New);
  2943. return QualType(New, 0);
  2944. }
  2945. /// getDependentSizedArrayType - Returns a non-unique reference to
  2946. /// the type for a dependently-sized array of the specified element
  2947. /// type.
  2948. QualType ASTContext::getDependentSizedArrayType(QualType elementType,
  2949. Expr *numElements,
  2950. ArrayType::ArraySizeModifier ASM,
  2951. unsigned elementTypeQuals,
  2952. SourceRange brackets) const {
  2953. assert((!numElements || numElements->isTypeDependent() ||
  2954. numElements->isValueDependent()) &&
  2955. "Size must be type- or value-dependent!");
  2956. // Dependently-sized array types that do not have a specified number
  2957. // of elements will have their sizes deduced from a dependent
  2958. // initializer. We do no canonicalization here at all, which is okay
  2959. // because they can't be used in most locations.
  2960. if (!numElements) {
  2961. auto *newType
  2962. = new (*this, TypeAlignment)
  2963. DependentSizedArrayType(*this, elementType, QualType(),
  2964. numElements, ASM, elementTypeQuals,
  2965. brackets);
  2966. Types.push_back(newType);
  2967. return QualType(newType, 0);
  2968. }
  2969. // Otherwise, we actually build a new type every time, but we
  2970. // also build a canonical type.
  2971. SplitQualType canonElementType = getCanonicalType(elementType).split();
  2972. void *insertPos = nullptr;
  2973. llvm::FoldingSetNodeID ID;
  2974. DependentSizedArrayType::Profile(ID, *this,
  2975. QualType(canonElementType.Ty, 0),
  2976. ASM, elementTypeQuals, numElements);
  2977. // Look for an existing type with these properties.
  2978. DependentSizedArrayType *canonTy =
  2979. DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  2980. // If we don't have one, build one.
  2981. if (!canonTy) {
  2982. canonTy = new (*this, TypeAlignment)
  2983. DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
  2984. QualType(), numElements, ASM, elementTypeQuals,
  2985. brackets);
  2986. DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
  2987. Types.push_back(canonTy);
  2988. }
  2989. // Apply qualifiers from the element type to the array.
  2990. QualType canon = getQualifiedType(QualType(canonTy,0),
  2991. canonElementType.Quals);
  2992. // If we didn't need extra canonicalization for the element type or the size
  2993. // expression, then just use that as our result.
  2994. if (QualType(canonElementType.Ty, 0) == elementType &&
  2995. canonTy->getSizeExpr() == numElements)
  2996. return canon;
  2997. // Otherwise, we need to build a type which follows the spelling
  2998. // of the element type.
  2999. auto *sugaredType
  3000. = new (*this, TypeAlignment)
  3001. DependentSizedArrayType(*this, elementType, canon, numElements,
  3002. ASM, elementTypeQuals, brackets);
  3003. Types.push_back(sugaredType);
  3004. return QualType(sugaredType, 0);
  3005. }
  3006. QualType ASTContext::getIncompleteArrayType(QualType elementType,
  3007. ArrayType::ArraySizeModifier ASM,
  3008. unsigned elementTypeQuals) const {
  3009. llvm::FoldingSetNodeID ID;
  3010. IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
  3011. void *insertPos = nullptr;
  3012. if (IncompleteArrayType *iat =
  3013. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
  3014. return QualType(iat, 0);
  3015. // If the element type isn't canonical, this won't be a canonical type
  3016. // either, so fill in the canonical type field. We also have to pull
  3017. // qualifiers off the element type.
  3018. QualType canon;
  3019. if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
  3020. SplitQualType canonSplit = getCanonicalType(elementType).split();
  3021. canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
  3022. ASM, elementTypeQuals);
  3023. canon = getQualifiedType(canon, canonSplit.Quals);
  3024. // Get the new insert position for the node we care about.
  3025. IncompleteArrayType *existing =
  3026. IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
  3027. assert(!existing && "Shouldn't be in the map!"); (void) existing;
  3028. }
  3029. auto *newType = new (*this, TypeAlignment)
  3030. IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
  3031. IncompleteArrayTypes.InsertNode(newType, insertPos);
  3032. Types.push_back(newType);
  3033. return QualType(newType, 0);
  3034. }
  3035. /// getVectorType - Return the unique reference to a vector type of
  3036. /// the specified element type and size. VectorType must be a built-in type.
  3037. QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
  3038. VectorType::VectorKind VecKind) const {
  3039. assert(vecType->isBuiltinType());
  3040. // Check if we've already instantiated a vector of this type.
  3041. llvm::FoldingSetNodeID ID;
  3042. VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
  3043. void *InsertPos = nullptr;
  3044. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3045. return QualType(VTP, 0);
  3046. // If the element type isn't canonical, this won't be a canonical type either,
  3047. // so fill in the canonical type field.
  3048. QualType Canonical;
  3049. if (!vecType.isCanonical()) {
  3050. Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
  3051. // Get the new insert position for the node we care about.
  3052. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3053. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3054. }
  3055. auto *New = new (*this, TypeAlignment)
  3056. VectorType(vecType, NumElts, Canonical, VecKind);
  3057. VectorTypes.InsertNode(New, InsertPos);
  3058. Types.push_back(New);
  3059. return QualType(New, 0);
  3060. }
  3061. QualType
  3062. ASTContext::getDependentVectorType(QualType VecType, Expr *SizeExpr,
  3063. SourceLocation AttrLoc,
  3064. VectorType::VectorKind VecKind) const {
  3065. llvm::FoldingSetNodeID ID;
  3066. DependentVectorType::Profile(ID, *this, getCanonicalType(VecType), SizeExpr,
  3067. VecKind);
  3068. void *InsertPos = nullptr;
  3069. DependentVectorType *Canon =
  3070. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3071. DependentVectorType *New;
  3072. if (Canon) {
  3073. New = new (*this, TypeAlignment) DependentVectorType(
  3074. *this, VecType, QualType(Canon, 0), SizeExpr, AttrLoc, VecKind);
  3075. } else {
  3076. QualType CanonVecTy = getCanonicalType(VecType);
  3077. if (CanonVecTy == VecType) {
  3078. New = new (*this, TypeAlignment) DependentVectorType(
  3079. *this, VecType, QualType(), SizeExpr, AttrLoc, VecKind);
  3080. DependentVectorType *CanonCheck =
  3081. DependentVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3082. assert(!CanonCheck &&
  3083. "Dependent-sized vector_size canonical type broken");
  3084. (void)CanonCheck;
  3085. DependentVectorTypes.InsertNode(New, InsertPos);
  3086. } else {
  3087. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  3088. SourceLocation());
  3089. New = new (*this, TypeAlignment) DependentVectorType(
  3090. *this, VecType, Canon, SizeExpr, AttrLoc, VecKind);
  3091. }
  3092. }
  3093. Types.push_back(New);
  3094. return QualType(New, 0);
  3095. }
  3096. /// getExtVectorType - Return the unique reference to an extended vector type of
  3097. /// the specified element type and size. VectorType must be a built-in type.
  3098. QualType
  3099. ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
  3100. assert(vecType->isBuiltinType() || vecType->isDependentType());
  3101. // Check if we've already instantiated a vector of this type.
  3102. llvm::FoldingSetNodeID ID;
  3103. VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
  3104. VectorType::GenericVector);
  3105. void *InsertPos = nullptr;
  3106. if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
  3107. return QualType(VTP, 0);
  3108. // If the element type isn't canonical, this won't be a canonical type either,
  3109. // so fill in the canonical type field.
  3110. QualType Canonical;
  3111. if (!vecType.isCanonical()) {
  3112. Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
  3113. // Get the new insert position for the node we care about.
  3114. VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3115. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3116. }
  3117. auto *New = new (*this, TypeAlignment)
  3118. ExtVectorType(vecType, NumElts, Canonical);
  3119. VectorTypes.InsertNode(New, InsertPos);
  3120. Types.push_back(New);
  3121. return QualType(New, 0);
  3122. }
  3123. QualType
  3124. ASTContext::getDependentSizedExtVectorType(QualType vecType,
  3125. Expr *SizeExpr,
  3126. SourceLocation AttrLoc) const {
  3127. llvm::FoldingSetNodeID ID;
  3128. DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
  3129. SizeExpr);
  3130. void *InsertPos = nullptr;
  3131. DependentSizedExtVectorType *Canon
  3132. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3133. DependentSizedExtVectorType *New;
  3134. if (Canon) {
  3135. // We already have a canonical version of this array type; use it as
  3136. // the canonical type for a newly-built type.
  3137. New = new (*this, TypeAlignment)
  3138. DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
  3139. SizeExpr, AttrLoc);
  3140. } else {
  3141. QualType CanonVecTy = getCanonicalType(vecType);
  3142. if (CanonVecTy == vecType) {
  3143. New = new (*this, TypeAlignment)
  3144. DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
  3145. AttrLoc);
  3146. DependentSizedExtVectorType *CanonCheck
  3147. = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
  3148. assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
  3149. (void)CanonCheck;
  3150. DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
  3151. } else {
  3152. QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
  3153. SourceLocation());
  3154. New = new (*this, TypeAlignment)
  3155. DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
  3156. }
  3157. }
  3158. Types.push_back(New);
  3159. return QualType(New, 0);
  3160. }
  3161. QualType ASTContext::getDependentAddressSpaceType(QualType PointeeType,
  3162. Expr *AddrSpaceExpr,
  3163. SourceLocation AttrLoc) const {
  3164. assert(AddrSpaceExpr->isInstantiationDependent());
  3165. QualType canonPointeeType = getCanonicalType(PointeeType);
  3166. void *insertPos = nullptr;
  3167. llvm::FoldingSetNodeID ID;
  3168. DependentAddressSpaceType::Profile(ID, *this, canonPointeeType,
  3169. AddrSpaceExpr);
  3170. DependentAddressSpaceType *canonTy =
  3171. DependentAddressSpaceTypes.FindNodeOrInsertPos(ID, insertPos);
  3172. if (!canonTy) {
  3173. canonTy = new (*this, TypeAlignment)
  3174. DependentAddressSpaceType(*this, canonPointeeType,
  3175. QualType(), AddrSpaceExpr, AttrLoc);
  3176. DependentAddressSpaceTypes.InsertNode(canonTy, insertPos);
  3177. Types.push_back(canonTy);
  3178. }
  3179. if (canonPointeeType == PointeeType &&
  3180. canonTy->getAddrSpaceExpr() == AddrSpaceExpr)
  3181. return QualType(canonTy, 0);
  3182. auto *sugaredType
  3183. = new (*this, TypeAlignment)
  3184. DependentAddressSpaceType(*this, PointeeType, QualType(canonTy, 0),
  3185. AddrSpaceExpr, AttrLoc);
  3186. Types.push_back(sugaredType);
  3187. return QualType(sugaredType, 0);
  3188. }
  3189. /// Determine whether \p T is canonical as the result type of a function.
  3190. static bool isCanonicalResultType(QualType T) {
  3191. return T.isCanonical() &&
  3192. (T.getObjCLifetime() == Qualifiers::OCL_None ||
  3193. T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
  3194. }
  3195. /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
  3196. QualType
  3197. ASTContext::getFunctionNoProtoType(QualType ResultTy,
  3198. const FunctionType::ExtInfo &Info) const {
  3199. // Unique functions, to guarantee there is only one function of a particular
  3200. // structure.
  3201. llvm::FoldingSetNodeID ID;
  3202. FunctionNoProtoType::Profile(ID, ResultTy, Info);
  3203. void *InsertPos = nullptr;
  3204. if (FunctionNoProtoType *FT =
  3205. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
  3206. return QualType(FT, 0);
  3207. QualType Canonical;
  3208. if (!isCanonicalResultType(ResultTy)) {
  3209. Canonical =
  3210. getFunctionNoProtoType(getCanonicalFunctionResultType(ResultTy), Info);
  3211. // Get the new insert position for the node we care about.
  3212. FunctionNoProtoType *NewIP =
  3213. FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3214. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3215. }
  3216. auto *New = new (*this, TypeAlignment)
  3217. FunctionNoProtoType(ResultTy, Canonical, Info);
  3218. Types.push_back(New);
  3219. FunctionNoProtoTypes.InsertNode(New, InsertPos);
  3220. return QualType(New, 0);
  3221. }
  3222. CanQualType
  3223. ASTContext::getCanonicalFunctionResultType(QualType ResultType) const {
  3224. CanQualType CanResultType = getCanonicalType(ResultType);
  3225. // Canonical result types do not have ARC lifetime qualifiers.
  3226. if (CanResultType.getQualifiers().hasObjCLifetime()) {
  3227. Qualifiers Qs = CanResultType.getQualifiers();
  3228. Qs.removeObjCLifetime();
  3229. return CanQualType::CreateUnsafe(
  3230. getQualifiedType(CanResultType.getUnqualifiedType(), Qs));
  3231. }
  3232. return CanResultType;
  3233. }
  3234. static bool isCanonicalExceptionSpecification(
  3235. const FunctionProtoType::ExceptionSpecInfo &ESI, bool NoexceptInType) {
  3236. if (ESI.Type == EST_None)
  3237. return true;
  3238. if (!NoexceptInType)
  3239. return false;
  3240. // C++17 onwards: exception specification is part of the type, as a simple
  3241. // boolean "can this function type throw".
  3242. if (ESI.Type == EST_BasicNoexcept)
  3243. return true;
  3244. // A noexcept(expr) specification is (possibly) canonical if expr is
  3245. // value-dependent.
  3246. if (ESI.Type == EST_DependentNoexcept)
  3247. return true;
  3248. // A dynamic exception specification is canonical if it only contains pack
  3249. // expansions (so we can't tell whether it's non-throwing) and all its
  3250. // contained types are canonical.
  3251. if (ESI.Type == EST_Dynamic) {
  3252. bool AnyPackExpansions = false;
  3253. for (QualType ET : ESI.Exceptions) {
  3254. if (!ET.isCanonical())
  3255. return false;
  3256. if (ET->getAs<PackExpansionType>())
  3257. AnyPackExpansions = true;
  3258. }
  3259. return AnyPackExpansions;
  3260. }
  3261. return false;
  3262. }
  3263. QualType ASTContext::getFunctionTypeInternal(
  3264. QualType ResultTy, ArrayRef<QualType> ArgArray,
  3265. const FunctionProtoType::ExtProtoInfo &EPI, bool OnlyWantCanonical) const {
  3266. size_t NumArgs = ArgArray.size();
  3267. // Unique functions, to guarantee there is only one function of a particular
  3268. // structure.
  3269. llvm::FoldingSetNodeID ID;
  3270. FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
  3271. *this, true);
  3272. QualType Canonical;
  3273. bool Unique = false;
  3274. void *InsertPos = nullptr;
  3275. if (FunctionProtoType *FPT =
  3276. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) {
  3277. QualType Existing = QualType(FPT, 0);
  3278. // If we find a pre-existing equivalent FunctionProtoType, we can just reuse
  3279. // it so long as our exception specification doesn't contain a dependent
  3280. // noexcept expression, or we're just looking for a canonical type.
  3281. // Otherwise, we're going to need to create a type
  3282. // sugar node to hold the concrete expression.
  3283. if (OnlyWantCanonical || !isComputedNoexcept(EPI.ExceptionSpec.Type) ||
  3284. EPI.ExceptionSpec.NoexceptExpr == FPT->getNoexceptExpr())
  3285. return Existing;
  3286. // We need a new type sugar node for this one, to hold the new noexcept
  3287. // expression. We do no canonicalization here, but that's OK since we don't
  3288. // expect to see the same noexcept expression much more than once.
  3289. Canonical = getCanonicalType(Existing);
  3290. Unique = true;
  3291. }
  3292. bool NoexceptInType = getLangOpts().CPlusPlus17;
  3293. bool IsCanonicalExceptionSpec =
  3294. isCanonicalExceptionSpecification(EPI.ExceptionSpec, NoexceptInType);
  3295. // Determine whether the type being created is already canonical or not.
  3296. bool isCanonical = !Unique && IsCanonicalExceptionSpec &&
  3297. isCanonicalResultType(ResultTy) && !EPI.HasTrailingReturn;
  3298. for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
  3299. if (!ArgArray[i].isCanonicalAsParam())
  3300. isCanonical = false;
  3301. if (OnlyWantCanonical)
  3302. assert(isCanonical &&
  3303. "given non-canonical parameters constructing canonical type");
  3304. // If this type isn't canonical, get the canonical version of it if we don't
  3305. // already have it. The exception spec is only partially part of the
  3306. // canonical type, and only in C++17 onwards.
  3307. if (!isCanonical && Canonical.isNull()) {
  3308. SmallVector<QualType, 16> CanonicalArgs;
  3309. CanonicalArgs.reserve(NumArgs);
  3310. for (unsigned i = 0; i != NumArgs; ++i)
  3311. CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
  3312. llvm::SmallVector<QualType, 8> ExceptionTypeStorage;
  3313. FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
  3314. CanonicalEPI.HasTrailingReturn = false;
  3315. if (IsCanonicalExceptionSpec) {
  3316. // Exception spec is already OK.
  3317. } else if (NoexceptInType) {
  3318. switch (EPI.ExceptionSpec.Type) {
  3319. case EST_Unparsed: case EST_Unevaluated: case EST_Uninstantiated:
  3320. // We don't know yet. It shouldn't matter what we pick here; no-one
  3321. // should ever look at this.
  3322. LLVM_FALLTHROUGH;
  3323. case EST_None: case EST_MSAny: case EST_NoexceptFalse:
  3324. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3325. break;
  3326. // A dynamic exception specification is almost always "not noexcept",
  3327. // with the exception that a pack expansion might expand to no types.
  3328. case EST_Dynamic: {
  3329. bool AnyPacks = false;
  3330. for (QualType ET : EPI.ExceptionSpec.Exceptions) {
  3331. if (ET->getAs<PackExpansionType>())
  3332. AnyPacks = true;
  3333. ExceptionTypeStorage.push_back(getCanonicalType(ET));
  3334. }
  3335. if (!AnyPacks)
  3336. CanonicalEPI.ExceptionSpec.Type = EST_None;
  3337. else {
  3338. CanonicalEPI.ExceptionSpec.Type = EST_Dynamic;
  3339. CanonicalEPI.ExceptionSpec.Exceptions = ExceptionTypeStorage;
  3340. }
  3341. break;
  3342. }
  3343. case EST_DynamicNone:
  3344. case EST_BasicNoexcept:
  3345. case EST_NoexceptTrue:
  3346. case EST_NoThrow:
  3347. CanonicalEPI.ExceptionSpec.Type = EST_BasicNoexcept;
  3348. break;
  3349. case EST_DependentNoexcept:
  3350. llvm_unreachable("dependent noexcept is already canonical");
  3351. }
  3352. } else {
  3353. CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
  3354. }
  3355. // Adjust the canonical function result type.
  3356. CanQualType CanResultTy = getCanonicalFunctionResultType(ResultTy);
  3357. Canonical =
  3358. getFunctionTypeInternal(CanResultTy, CanonicalArgs, CanonicalEPI, true);
  3359. // Get the new insert position for the node we care about.
  3360. FunctionProtoType *NewIP =
  3361. FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
  3362. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  3363. }
  3364. // Compute the needed size to hold this FunctionProtoType and the
  3365. // various trailing objects.
  3366. auto ESH = FunctionProtoType::getExceptionSpecSize(
  3367. EPI.ExceptionSpec.Type, EPI.ExceptionSpec.Exceptions.size());
  3368. size_t Size = FunctionProtoType::totalSizeToAlloc<
  3369. QualType, FunctionType::FunctionTypeExtraBitfields,
  3370. FunctionType::ExceptionType, Expr *, FunctionDecl *,
  3371. FunctionProtoType::ExtParameterInfo, Qualifiers>(
  3372. NumArgs, FunctionProtoType::hasExtraBitfields(EPI.ExceptionSpec.Type),
  3373. ESH.NumExceptionType, ESH.NumExprPtr, ESH.NumFunctionDeclPtr,
  3374. EPI.ExtParameterInfos ? NumArgs : 0,
  3375. EPI.TypeQuals.hasNonFastQualifiers() ? 1 : 0);
  3376. auto *FTP = (FunctionProtoType *)Allocate(Size, TypeAlignment);
  3377. FunctionProtoType::ExtProtoInfo newEPI = EPI;
  3378. new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
  3379. Types.push_back(FTP);
  3380. if (!Unique)
  3381. FunctionProtoTypes.InsertNode(FTP, InsertPos);
  3382. return QualType(FTP, 0);
  3383. }
  3384. QualType ASTContext::getPipeType(QualType T, bool ReadOnly) const {
  3385. llvm::FoldingSetNodeID ID;
  3386. PipeType::Profile(ID, T, ReadOnly);
  3387. void *InsertPos = nullptr;
  3388. if (PipeType *PT = PipeTypes.FindNodeOrInsertPos(ID, InsertPos))
  3389. return QualType(PT, 0);
  3390. // If the pipe element type isn't canonical, this won't be a canonical type
  3391. // either, so fill in the canonical type field.
  3392. QualType Canonical;
  3393. if (!T.isCanonical()) {
  3394. Canonical = getPipeType(getCanonicalType(T), ReadOnly);
  3395. // Get the new insert position for the node we care about.
  3396. PipeType *NewIP = PipeTypes.FindNodeOrInsertPos(ID, InsertPos);
  3397. assert(!NewIP && "Shouldn't be in the map!");
  3398. (void)NewIP;
  3399. }
  3400. auto *New = new (*this, TypeAlignment) PipeType(T, Canonical, ReadOnly);
  3401. Types.push_back(New);
  3402. PipeTypes.InsertNode(New, InsertPos);
  3403. return QualType(New, 0);
  3404. }
  3405. QualType ASTContext::adjustStringLiteralBaseType(QualType Ty) const {
  3406. // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
  3407. return LangOpts.OpenCL ? getAddrSpaceQualType(Ty, LangAS::opencl_constant)
  3408. : Ty;
  3409. }
  3410. QualType ASTContext::getReadPipeType(QualType T) const {
  3411. return getPipeType(T, true);
  3412. }
  3413. QualType ASTContext::getWritePipeType(QualType T) const {
  3414. return getPipeType(T, false);
  3415. }
  3416. #ifndef NDEBUG
  3417. static bool NeedsInjectedClassNameType(const RecordDecl *D) {
  3418. if (!isa<CXXRecordDecl>(D)) return false;
  3419. const auto *RD = cast<CXXRecordDecl>(D);
  3420. if (isa<ClassTemplatePartialSpecializationDecl>(RD))
  3421. return true;
  3422. if (RD->getDescribedClassTemplate() &&
  3423. !isa<ClassTemplateSpecializationDecl>(RD))
  3424. return true;
  3425. return false;
  3426. }
  3427. #endif
  3428. /// getInjectedClassNameType - Return the unique reference to the
  3429. /// injected class name type for the specified templated declaration.
  3430. QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
  3431. QualType TST) const {
  3432. assert(NeedsInjectedClassNameType(Decl));
  3433. if (Decl->TypeForDecl) {
  3434. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3435. } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
  3436. assert(PrevDecl->TypeForDecl && "previous declaration has no type");
  3437. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  3438. assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
  3439. } else {
  3440. Type *newType =
  3441. new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
  3442. Decl->TypeForDecl = newType;
  3443. Types.push_back(newType);
  3444. }
  3445. return QualType(Decl->TypeForDecl, 0);
  3446. }
  3447. /// getTypeDeclType - Return the unique reference to the type for the
  3448. /// specified type declaration.
  3449. QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
  3450. assert(Decl && "Passed null for Decl param");
  3451. assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
  3452. if (const auto *Typedef = dyn_cast<TypedefNameDecl>(Decl))
  3453. return getTypedefType(Typedef);
  3454. assert(!isa<TemplateTypeParmDecl>(Decl) &&
  3455. "Template type parameter types are always available.");
  3456. if (const auto *Record = dyn_cast<RecordDecl>(Decl)) {
  3457. assert(Record->isFirstDecl() && "struct/union has previous declaration");
  3458. assert(!NeedsInjectedClassNameType(Record));
  3459. return getRecordType(Record);
  3460. } else if (const auto *Enum = dyn_cast<EnumDecl>(Decl)) {
  3461. assert(Enum->isFirstDecl() && "enum has previous declaration");
  3462. return getEnumType(Enum);
  3463. } else if (const auto *Using = dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
  3464. Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
  3465. Decl->TypeForDecl = newType;
  3466. Types.push_back(newType);
  3467. } else
  3468. llvm_unreachable("TypeDecl without a type?");
  3469. return QualType(Decl->TypeForDecl, 0);
  3470. }
  3471. /// getTypedefType - Return the unique reference to the type for the
  3472. /// specified typedef name decl.
  3473. QualType
  3474. ASTContext::getTypedefType(const TypedefNameDecl *Decl,
  3475. QualType Canonical) const {
  3476. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3477. if (Canonical.isNull())
  3478. Canonical = getCanonicalType(Decl->getUnderlyingType());
  3479. auto *newType = new (*this, TypeAlignment)
  3480. TypedefType(Type::Typedef, Decl, Canonical);
  3481. Decl->TypeForDecl = newType;
  3482. Types.push_back(newType);
  3483. return QualType(newType, 0);
  3484. }
  3485. QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
  3486. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3487. if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
  3488. if (PrevDecl->TypeForDecl)
  3489. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  3490. auto *newType = new (*this, TypeAlignment) RecordType(Decl);
  3491. Decl->TypeForDecl = newType;
  3492. Types.push_back(newType);
  3493. return QualType(newType, 0);
  3494. }
  3495. QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
  3496. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  3497. if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
  3498. if (PrevDecl->TypeForDecl)
  3499. return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
  3500. auto *newType = new (*this, TypeAlignment) EnumType(Decl);
  3501. Decl->TypeForDecl = newType;
  3502. Types.push_back(newType);
  3503. return QualType(newType, 0);
  3504. }
  3505. QualType ASTContext::getAttributedType(attr::Kind attrKind,
  3506. QualType modifiedType,
  3507. QualType equivalentType) {
  3508. llvm::FoldingSetNodeID id;
  3509. AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
  3510. void *insertPos = nullptr;
  3511. AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
  3512. if (type) return QualType(type, 0);
  3513. QualType canon = getCanonicalType(equivalentType);
  3514. type = new (*this, TypeAlignment)
  3515. AttributedType(canon, attrKind, modifiedType, equivalentType);
  3516. Types.push_back(type);
  3517. AttributedTypes.InsertNode(type, insertPos);
  3518. return QualType(type, 0);
  3519. }
  3520. /// Retrieve a substitution-result type.
  3521. QualType
  3522. ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
  3523. QualType Replacement) const {
  3524. assert(Replacement.isCanonical()
  3525. && "replacement types must always be canonical");
  3526. llvm::FoldingSetNodeID ID;
  3527. SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
  3528. void *InsertPos = nullptr;
  3529. SubstTemplateTypeParmType *SubstParm
  3530. = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3531. if (!SubstParm) {
  3532. SubstParm = new (*this, TypeAlignment)
  3533. SubstTemplateTypeParmType(Parm, Replacement);
  3534. Types.push_back(SubstParm);
  3535. SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
  3536. }
  3537. return QualType(SubstParm, 0);
  3538. }
  3539. /// Retrieve a
  3540. QualType ASTContext::getSubstTemplateTypeParmPackType(
  3541. const TemplateTypeParmType *Parm,
  3542. const TemplateArgument &ArgPack) {
  3543. #ifndef NDEBUG
  3544. for (const auto &P : ArgPack.pack_elements()) {
  3545. assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
  3546. assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
  3547. }
  3548. #endif
  3549. llvm::FoldingSetNodeID ID;
  3550. SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
  3551. void *InsertPos = nullptr;
  3552. if (SubstTemplateTypeParmPackType *SubstParm
  3553. = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
  3554. return QualType(SubstParm, 0);
  3555. QualType Canon;
  3556. if (!Parm->isCanonicalUnqualified()) {
  3557. Canon = getCanonicalType(QualType(Parm, 0));
  3558. Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
  3559. ArgPack);
  3560. SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
  3561. }
  3562. auto *SubstParm
  3563. = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
  3564. ArgPack);
  3565. Types.push_back(SubstParm);
  3566. SubstTemplateTypeParmPackTypes.InsertNode(SubstParm, InsertPos);
  3567. return QualType(SubstParm, 0);
  3568. }
  3569. /// Retrieve the template type parameter type for a template
  3570. /// parameter or parameter pack with the given depth, index, and (optionally)
  3571. /// name.
  3572. QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
  3573. bool ParameterPack,
  3574. TemplateTypeParmDecl *TTPDecl) const {
  3575. llvm::FoldingSetNodeID ID;
  3576. TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
  3577. void *InsertPos = nullptr;
  3578. TemplateTypeParmType *TypeParm
  3579. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3580. if (TypeParm)
  3581. return QualType(TypeParm, 0);
  3582. if (TTPDecl) {
  3583. QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
  3584. TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
  3585. TemplateTypeParmType *TypeCheck
  3586. = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
  3587. assert(!TypeCheck && "Template type parameter canonical type broken");
  3588. (void)TypeCheck;
  3589. } else
  3590. TypeParm = new (*this, TypeAlignment)
  3591. TemplateTypeParmType(Depth, Index, ParameterPack);
  3592. Types.push_back(TypeParm);
  3593. TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
  3594. return QualType(TypeParm, 0);
  3595. }
  3596. TypeSourceInfo *
  3597. ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
  3598. SourceLocation NameLoc,
  3599. const TemplateArgumentListInfo &Args,
  3600. QualType Underlying) const {
  3601. assert(!Name.getAsDependentTemplateName() &&
  3602. "No dependent template names here!");
  3603. QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
  3604. TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
  3605. TemplateSpecializationTypeLoc TL =
  3606. DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
  3607. TL.setTemplateKeywordLoc(SourceLocation());
  3608. TL.setTemplateNameLoc(NameLoc);
  3609. TL.setLAngleLoc(Args.getLAngleLoc());
  3610. TL.setRAngleLoc(Args.getRAngleLoc());
  3611. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  3612. TL.setArgLocInfo(i, Args[i].getLocInfo());
  3613. return DI;
  3614. }
  3615. QualType
  3616. ASTContext::getTemplateSpecializationType(TemplateName Template,
  3617. const TemplateArgumentListInfo &Args,
  3618. QualType Underlying) const {
  3619. assert(!Template.getAsDependentTemplateName() &&
  3620. "No dependent template names here!");
  3621. SmallVector<TemplateArgument, 4> ArgVec;
  3622. ArgVec.reserve(Args.size());
  3623. for (const TemplateArgumentLoc &Arg : Args.arguments())
  3624. ArgVec.push_back(Arg.getArgument());
  3625. return getTemplateSpecializationType(Template, ArgVec, Underlying);
  3626. }
  3627. #ifndef NDEBUG
  3628. static bool hasAnyPackExpansions(ArrayRef<TemplateArgument> Args) {
  3629. for (const TemplateArgument &Arg : Args)
  3630. if (Arg.isPackExpansion())
  3631. return true;
  3632. return true;
  3633. }
  3634. #endif
  3635. QualType
  3636. ASTContext::getTemplateSpecializationType(TemplateName Template,
  3637. ArrayRef<TemplateArgument> Args,
  3638. QualType Underlying) const {
  3639. assert(!Template.getAsDependentTemplateName() &&
  3640. "No dependent template names here!");
  3641. // Look through qualified template names.
  3642. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  3643. Template = TemplateName(QTN->getTemplateDecl());
  3644. bool IsTypeAlias =
  3645. Template.getAsTemplateDecl() &&
  3646. isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
  3647. QualType CanonType;
  3648. if (!Underlying.isNull())
  3649. CanonType = getCanonicalType(Underlying);
  3650. else {
  3651. // We can get here with an alias template when the specialization contains
  3652. // a pack expansion that does not match up with a parameter pack.
  3653. assert((!IsTypeAlias || hasAnyPackExpansions(Args)) &&
  3654. "Caller must compute aliased type");
  3655. IsTypeAlias = false;
  3656. CanonType = getCanonicalTemplateSpecializationType(Template, Args);
  3657. }
  3658. // Allocate the (non-canonical) template specialization type, but don't
  3659. // try to unique it: these types typically have location information that
  3660. // we don't unique and don't want to lose.
  3661. void *Mem = Allocate(sizeof(TemplateSpecializationType) +
  3662. sizeof(TemplateArgument) * Args.size() +
  3663. (IsTypeAlias? sizeof(QualType) : 0),
  3664. TypeAlignment);
  3665. auto *Spec
  3666. = new (Mem) TemplateSpecializationType(Template, Args, CanonType,
  3667. IsTypeAlias ? Underlying : QualType());
  3668. Types.push_back(Spec);
  3669. return QualType(Spec, 0);
  3670. }
  3671. QualType ASTContext::getCanonicalTemplateSpecializationType(
  3672. TemplateName Template, ArrayRef<TemplateArgument> Args) const {
  3673. assert(!Template.getAsDependentTemplateName() &&
  3674. "No dependent template names here!");
  3675. // Look through qualified template names.
  3676. if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
  3677. Template = TemplateName(QTN->getTemplateDecl());
  3678. // Build the canonical template specialization type.
  3679. TemplateName CanonTemplate = getCanonicalTemplateName(Template);
  3680. SmallVector<TemplateArgument, 4> CanonArgs;
  3681. unsigned NumArgs = Args.size();
  3682. CanonArgs.reserve(NumArgs);
  3683. for (const TemplateArgument &Arg : Args)
  3684. CanonArgs.push_back(getCanonicalTemplateArgument(Arg));
  3685. // Determine whether this canonical template specialization type already
  3686. // exists.
  3687. llvm::FoldingSetNodeID ID;
  3688. TemplateSpecializationType::Profile(ID, CanonTemplate,
  3689. CanonArgs, *this);
  3690. void *InsertPos = nullptr;
  3691. TemplateSpecializationType *Spec
  3692. = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3693. if (!Spec) {
  3694. // Allocate a new canonical template specialization type.
  3695. void *Mem = Allocate((sizeof(TemplateSpecializationType) +
  3696. sizeof(TemplateArgument) * NumArgs),
  3697. TypeAlignment);
  3698. Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
  3699. CanonArgs,
  3700. QualType(), QualType());
  3701. Types.push_back(Spec);
  3702. TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
  3703. }
  3704. assert(Spec->isDependentType() &&
  3705. "Non-dependent template-id type must have a canonical type");
  3706. return QualType(Spec, 0);
  3707. }
  3708. QualType ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
  3709. NestedNameSpecifier *NNS,
  3710. QualType NamedType,
  3711. TagDecl *OwnedTagDecl) const {
  3712. llvm::FoldingSetNodeID ID;
  3713. ElaboratedType::Profile(ID, Keyword, NNS, NamedType, OwnedTagDecl);
  3714. void *InsertPos = nullptr;
  3715. ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3716. if (T)
  3717. return QualType(T, 0);
  3718. QualType Canon = NamedType;
  3719. if (!Canon.isCanonical()) {
  3720. Canon = getCanonicalType(NamedType);
  3721. ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
  3722. assert(!CheckT && "Elaborated canonical type broken");
  3723. (void)CheckT;
  3724. }
  3725. void *Mem = Allocate(ElaboratedType::totalSizeToAlloc<TagDecl *>(!!OwnedTagDecl),
  3726. TypeAlignment);
  3727. T = new (Mem) ElaboratedType(Keyword, NNS, NamedType, Canon, OwnedTagDecl);
  3728. Types.push_back(T);
  3729. ElaboratedTypes.InsertNode(T, InsertPos);
  3730. return QualType(T, 0);
  3731. }
  3732. QualType
  3733. ASTContext::getParenType(QualType InnerType) const {
  3734. llvm::FoldingSetNodeID ID;
  3735. ParenType::Profile(ID, InnerType);
  3736. void *InsertPos = nullptr;
  3737. ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3738. if (T)
  3739. return QualType(T, 0);
  3740. QualType Canon = InnerType;
  3741. if (!Canon.isCanonical()) {
  3742. Canon = getCanonicalType(InnerType);
  3743. ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
  3744. assert(!CheckT && "Paren canonical type broken");
  3745. (void)CheckT;
  3746. }
  3747. T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
  3748. Types.push_back(T);
  3749. ParenTypes.InsertNode(T, InsertPos);
  3750. return QualType(T, 0);
  3751. }
  3752. QualType
  3753. ASTContext::getMacroQualifiedType(QualType UnderlyingTy,
  3754. const IdentifierInfo *MacroII) const {
  3755. QualType Canon = UnderlyingTy;
  3756. if (!Canon.isCanonical())
  3757. Canon = getCanonicalType(UnderlyingTy);
  3758. auto *newType = new (*this, TypeAlignment)
  3759. MacroQualifiedType(UnderlyingTy, Canon, MacroII);
  3760. Types.push_back(newType);
  3761. return QualType(newType, 0);
  3762. }
  3763. QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
  3764. NestedNameSpecifier *NNS,
  3765. const IdentifierInfo *Name,
  3766. QualType Canon) const {
  3767. if (Canon.isNull()) {
  3768. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3769. if (CanonNNS != NNS)
  3770. Canon = getDependentNameType(Keyword, CanonNNS, Name);
  3771. }
  3772. llvm::FoldingSetNodeID ID;
  3773. DependentNameType::Profile(ID, Keyword, NNS, Name);
  3774. void *InsertPos = nullptr;
  3775. DependentNameType *T
  3776. = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
  3777. if (T)
  3778. return QualType(T, 0);
  3779. T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
  3780. Types.push_back(T);
  3781. DependentNameTypes.InsertNode(T, InsertPos);
  3782. return QualType(T, 0);
  3783. }
  3784. QualType
  3785. ASTContext::getDependentTemplateSpecializationType(
  3786. ElaboratedTypeKeyword Keyword,
  3787. NestedNameSpecifier *NNS,
  3788. const IdentifierInfo *Name,
  3789. const TemplateArgumentListInfo &Args) const {
  3790. // TODO: avoid this copy
  3791. SmallVector<TemplateArgument, 16> ArgCopy;
  3792. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  3793. ArgCopy.push_back(Args[I].getArgument());
  3794. return getDependentTemplateSpecializationType(Keyword, NNS, Name, ArgCopy);
  3795. }
  3796. QualType
  3797. ASTContext::getDependentTemplateSpecializationType(
  3798. ElaboratedTypeKeyword Keyword,
  3799. NestedNameSpecifier *NNS,
  3800. const IdentifierInfo *Name,
  3801. ArrayRef<TemplateArgument> Args) const {
  3802. assert((!NNS || NNS->isDependent()) &&
  3803. "nested-name-specifier must be dependent");
  3804. llvm::FoldingSetNodeID ID;
  3805. DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
  3806. Name, Args);
  3807. void *InsertPos = nullptr;
  3808. DependentTemplateSpecializationType *T
  3809. = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3810. if (T)
  3811. return QualType(T, 0);
  3812. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  3813. ElaboratedTypeKeyword CanonKeyword = Keyword;
  3814. if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
  3815. bool AnyNonCanonArgs = false;
  3816. unsigned NumArgs = Args.size();
  3817. SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
  3818. for (unsigned I = 0; I != NumArgs; ++I) {
  3819. CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
  3820. if (!CanonArgs[I].structurallyEquals(Args[I]))
  3821. AnyNonCanonArgs = true;
  3822. }
  3823. QualType Canon;
  3824. if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
  3825. Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
  3826. Name,
  3827. CanonArgs);
  3828. // Find the insert position again.
  3829. DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
  3830. }
  3831. void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
  3832. sizeof(TemplateArgument) * NumArgs),
  3833. TypeAlignment);
  3834. T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
  3835. Name, Args, Canon);
  3836. Types.push_back(T);
  3837. DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
  3838. return QualType(T, 0);
  3839. }
  3840. TemplateArgument ASTContext::getInjectedTemplateArg(NamedDecl *Param) {
  3841. TemplateArgument Arg;
  3842. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
  3843. QualType ArgType = getTypeDeclType(TTP);
  3844. if (TTP->isParameterPack())
  3845. ArgType = getPackExpansionType(ArgType, None);
  3846. Arg = TemplateArgument(ArgType);
  3847. } else if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3848. Expr *E = new (*this) DeclRefExpr(
  3849. *this, NTTP, /*enclosing*/ false,
  3850. NTTP->getType().getNonLValueExprType(*this),
  3851. Expr::getValueKindForType(NTTP->getType()), NTTP->getLocation());
  3852. if (NTTP->isParameterPack())
  3853. E = new (*this) PackExpansionExpr(DependentTy, E, NTTP->getLocation(),
  3854. None);
  3855. Arg = TemplateArgument(E);
  3856. } else {
  3857. auto *TTP = cast<TemplateTemplateParmDecl>(Param);
  3858. if (TTP->isParameterPack())
  3859. Arg = TemplateArgument(TemplateName(TTP), Optional<unsigned>());
  3860. else
  3861. Arg = TemplateArgument(TemplateName(TTP));
  3862. }
  3863. if (Param->isTemplateParameterPack())
  3864. Arg = TemplateArgument::CreatePackCopy(*this, Arg);
  3865. return Arg;
  3866. }
  3867. void
  3868. ASTContext::getInjectedTemplateArgs(const TemplateParameterList *Params,
  3869. SmallVectorImpl<TemplateArgument> &Args) {
  3870. Args.reserve(Args.size() + Params->size());
  3871. for (NamedDecl *Param : *Params)
  3872. Args.push_back(getInjectedTemplateArg(Param));
  3873. }
  3874. QualType ASTContext::getPackExpansionType(QualType Pattern,
  3875. Optional<unsigned> NumExpansions) {
  3876. llvm::FoldingSetNodeID ID;
  3877. PackExpansionType::Profile(ID, Pattern, NumExpansions);
  3878. // A deduced type can deduce to a pack, eg
  3879. // auto ...x = some_pack;
  3880. // That declaration isn't (yet) valid, but is created as part of building an
  3881. // init-capture pack:
  3882. // [...x = some_pack] {}
  3883. assert((Pattern->containsUnexpandedParameterPack() ||
  3884. Pattern->getContainedDeducedType()) &&
  3885. "Pack expansions must expand one or more parameter packs");
  3886. void *InsertPos = nullptr;
  3887. PackExpansionType *T
  3888. = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3889. if (T)
  3890. return QualType(T, 0);
  3891. QualType Canon;
  3892. if (!Pattern.isCanonical()) {
  3893. Canon = getCanonicalType(Pattern);
  3894. // The canonical type might not contain an unexpanded parameter pack, if it
  3895. // contains an alias template specialization which ignores one of its
  3896. // parameters.
  3897. if (Canon->containsUnexpandedParameterPack()) {
  3898. Canon = getPackExpansionType(Canon, NumExpansions);
  3899. // Find the insert position again, in case we inserted an element into
  3900. // PackExpansionTypes and invalidated our insert position.
  3901. PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
  3902. }
  3903. }
  3904. T = new (*this, TypeAlignment)
  3905. PackExpansionType(Pattern, Canon, NumExpansions);
  3906. Types.push_back(T);
  3907. PackExpansionTypes.InsertNode(T, InsertPos);
  3908. return QualType(T, 0);
  3909. }
  3910. /// CmpProtocolNames - Comparison predicate for sorting protocols
  3911. /// alphabetically.
  3912. static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
  3913. ObjCProtocolDecl *const *RHS) {
  3914. return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
  3915. }
  3916. static bool areSortedAndUniqued(ArrayRef<ObjCProtocolDecl *> Protocols) {
  3917. if (Protocols.empty()) return true;
  3918. if (Protocols[0]->getCanonicalDecl() != Protocols[0])
  3919. return false;
  3920. for (unsigned i = 1; i != Protocols.size(); ++i)
  3921. if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
  3922. Protocols[i]->getCanonicalDecl() != Protocols[i])
  3923. return false;
  3924. return true;
  3925. }
  3926. static void
  3927. SortAndUniqueProtocols(SmallVectorImpl<ObjCProtocolDecl *> &Protocols) {
  3928. // Sort protocols, keyed by name.
  3929. llvm::array_pod_sort(Protocols.begin(), Protocols.end(), CmpProtocolNames);
  3930. // Canonicalize.
  3931. for (ObjCProtocolDecl *&P : Protocols)
  3932. P = P->getCanonicalDecl();
  3933. // Remove duplicates.
  3934. auto ProtocolsEnd = std::unique(Protocols.begin(), Protocols.end());
  3935. Protocols.erase(ProtocolsEnd, Protocols.end());
  3936. }
  3937. QualType ASTContext::getObjCObjectType(QualType BaseType,
  3938. ObjCProtocolDecl * const *Protocols,
  3939. unsigned NumProtocols) const {
  3940. return getObjCObjectType(BaseType, {},
  3941. llvm::makeArrayRef(Protocols, NumProtocols),
  3942. /*isKindOf=*/false);
  3943. }
  3944. QualType ASTContext::getObjCObjectType(
  3945. QualType baseType,
  3946. ArrayRef<QualType> typeArgs,
  3947. ArrayRef<ObjCProtocolDecl *> protocols,
  3948. bool isKindOf) const {
  3949. // If the base type is an interface and there aren't any protocols or
  3950. // type arguments to add, then the interface type will do just fine.
  3951. if (typeArgs.empty() && protocols.empty() && !isKindOf &&
  3952. isa<ObjCInterfaceType>(baseType))
  3953. return baseType;
  3954. // Look in the folding set for an existing type.
  3955. llvm::FoldingSetNodeID ID;
  3956. ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
  3957. void *InsertPos = nullptr;
  3958. if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
  3959. return QualType(QT, 0);
  3960. // Determine the type arguments to be used for canonicalization,
  3961. // which may be explicitly specified here or written on the base
  3962. // type.
  3963. ArrayRef<QualType> effectiveTypeArgs = typeArgs;
  3964. if (effectiveTypeArgs.empty()) {
  3965. if (const auto *baseObject = baseType->getAs<ObjCObjectType>())
  3966. effectiveTypeArgs = baseObject->getTypeArgs();
  3967. }
  3968. // Build the canonical type, which has the canonical base type and a
  3969. // sorted-and-uniqued list of protocols and the type arguments
  3970. // canonicalized.
  3971. QualType canonical;
  3972. bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
  3973. effectiveTypeArgs.end(),
  3974. [&](QualType type) {
  3975. return type.isCanonical();
  3976. });
  3977. bool protocolsSorted = areSortedAndUniqued(protocols);
  3978. if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
  3979. // Determine the canonical type arguments.
  3980. ArrayRef<QualType> canonTypeArgs;
  3981. SmallVector<QualType, 4> canonTypeArgsVec;
  3982. if (!typeArgsAreCanonical) {
  3983. canonTypeArgsVec.reserve(effectiveTypeArgs.size());
  3984. for (auto typeArg : effectiveTypeArgs)
  3985. canonTypeArgsVec.push_back(getCanonicalType(typeArg));
  3986. canonTypeArgs = canonTypeArgsVec;
  3987. } else {
  3988. canonTypeArgs = effectiveTypeArgs;
  3989. }
  3990. ArrayRef<ObjCProtocolDecl *> canonProtocols;
  3991. SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
  3992. if (!protocolsSorted) {
  3993. canonProtocolsVec.append(protocols.begin(), protocols.end());
  3994. SortAndUniqueProtocols(canonProtocolsVec);
  3995. canonProtocols = canonProtocolsVec;
  3996. } else {
  3997. canonProtocols = protocols;
  3998. }
  3999. canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
  4000. canonProtocols, isKindOf);
  4001. // Regenerate InsertPos.
  4002. ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
  4003. }
  4004. unsigned size = sizeof(ObjCObjectTypeImpl);
  4005. size += typeArgs.size() * sizeof(QualType);
  4006. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4007. void *mem = Allocate(size, TypeAlignment);
  4008. auto *T =
  4009. new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
  4010. isKindOf);
  4011. Types.push_back(T);
  4012. ObjCObjectTypes.InsertNode(T, InsertPos);
  4013. return QualType(T, 0);
  4014. }
  4015. /// Apply Objective-C protocol qualifiers to the given type.
  4016. /// If this is for the canonical type of a type parameter, we can apply
  4017. /// protocol qualifiers on the ObjCObjectPointerType.
  4018. QualType
  4019. ASTContext::applyObjCProtocolQualifiers(QualType type,
  4020. ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
  4021. bool allowOnPointerType) const {
  4022. hasError = false;
  4023. if (const auto *objT = dyn_cast<ObjCTypeParamType>(type.getTypePtr())) {
  4024. return getObjCTypeParamType(objT->getDecl(), protocols);
  4025. }
  4026. // Apply protocol qualifiers to ObjCObjectPointerType.
  4027. if (allowOnPointerType) {
  4028. if (const auto *objPtr =
  4029. dyn_cast<ObjCObjectPointerType>(type.getTypePtr())) {
  4030. const ObjCObjectType *objT = objPtr->getObjectType();
  4031. // Merge protocol lists and construct ObjCObjectType.
  4032. SmallVector<ObjCProtocolDecl*, 8> protocolsVec;
  4033. protocolsVec.append(objT->qual_begin(),
  4034. objT->qual_end());
  4035. protocolsVec.append(protocols.begin(), protocols.end());
  4036. ArrayRef<ObjCProtocolDecl *> protocols = protocolsVec;
  4037. type = getObjCObjectType(
  4038. objT->getBaseType(),
  4039. objT->getTypeArgsAsWritten(),
  4040. protocols,
  4041. objT->isKindOfTypeAsWritten());
  4042. return getObjCObjectPointerType(type);
  4043. }
  4044. }
  4045. // Apply protocol qualifiers to ObjCObjectType.
  4046. if (const auto *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
  4047. // FIXME: Check for protocols to which the class type is already
  4048. // known to conform.
  4049. return getObjCObjectType(objT->getBaseType(),
  4050. objT->getTypeArgsAsWritten(),
  4051. protocols,
  4052. objT->isKindOfTypeAsWritten());
  4053. }
  4054. // If the canonical type is ObjCObjectType, ...
  4055. if (type->isObjCObjectType()) {
  4056. // Silently overwrite any existing protocol qualifiers.
  4057. // TODO: determine whether that's the right thing to do.
  4058. // FIXME: Check for protocols to which the class type is already
  4059. // known to conform.
  4060. return getObjCObjectType(type, {}, protocols, false);
  4061. }
  4062. // id<protocol-list>
  4063. if (type->isObjCIdType()) {
  4064. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4065. type = getObjCObjectType(ObjCBuiltinIdTy, {}, protocols,
  4066. objPtr->isKindOfType());
  4067. return getObjCObjectPointerType(type);
  4068. }
  4069. // Class<protocol-list>
  4070. if (type->isObjCClassType()) {
  4071. const auto *objPtr = type->castAs<ObjCObjectPointerType>();
  4072. type = getObjCObjectType(ObjCBuiltinClassTy, {}, protocols,
  4073. objPtr->isKindOfType());
  4074. return getObjCObjectPointerType(type);
  4075. }
  4076. hasError = true;
  4077. return type;
  4078. }
  4079. QualType
  4080. ASTContext::getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  4081. ArrayRef<ObjCProtocolDecl *> protocols,
  4082. QualType Canonical) const {
  4083. // Look in the folding set for an existing type.
  4084. llvm::FoldingSetNodeID ID;
  4085. ObjCTypeParamType::Profile(ID, Decl, protocols);
  4086. void *InsertPos = nullptr;
  4087. if (ObjCTypeParamType *TypeParam =
  4088. ObjCTypeParamTypes.FindNodeOrInsertPos(ID, InsertPos))
  4089. return QualType(TypeParam, 0);
  4090. if (Canonical.isNull()) {
  4091. // We canonicalize to the underlying type.
  4092. Canonical = getCanonicalType(Decl->getUnderlyingType());
  4093. if (!protocols.empty()) {
  4094. // Apply the protocol qualifers.
  4095. bool hasError;
  4096. Canonical = getCanonicalType(applyObjCProtocolQualifiers(
  4097. Canonical, protocols, hasError, true /*allowOnPointerType*/));
  4098. assert(!hasError && "Error when apply protocol qualifier to bound type");
  4099. }
  4100. }
  4101. unsigned size = sizeof(ObjCTypeParamType);
  4102. size += protocols.size() * sizeof(ObjCProtocolDecl *);
  4103. void *mem = Allocate(size, TypeAlignment);
  4104. auto *newType = new (mem) ObjCTypeParamType(Decl, Canonical, protocols);
  4105. Types.push_back(newType);
  4106. ObjCTypeParamTypes.InsertNode(newType, InsertPos);
  4107. return QualType(newType, 0);
  4108. }
  4109. /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
  4110. /// protocol list adopt all protocols in QT's qualified-id protocol
  4111. /// list.
  4112. bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
  4113. ObjCInterfaceDecl *IC) {
  4114. if (!QT->isObjCQualifiedIdType())
  4115. return false;
  4116. if (const auto *OPT = QT->getAs<ObjCObjectPointerType>()) {
  4117. // If both the right and left sides have qualifiers.
  4118. for (auto *Proto : OPT->quals()) {
  4119. if (!IC->ClassImplementsProtocol(Proto, false))
  4120. return false;
  4121. }
  4122. return true;
  4123. }
  4124. return false;
  4125. }
  4126. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  4127. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  4128. /// of protocols.
  4129. bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  4130. ObjCInterfaceDecl *IDecl) {
  4131. if (!QT->isObjCQualifiedIdType())
  4132. return false;
  4133. const auto *OPT = QT->getAs<ObjCObjectPointerType>();
  4134. if (!OPT)
  4135. return false;
  4136. if (!IDecl->hasDefinition())
  4137. return false;
  4138. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
  4139. CollectInheritedProtocols(IDecl, InheritedProtocols);
  4140. if (InheritedProtocols.empty())
  4141. return false;
  4142. // Check that if every protocol in list of id<plist> conforms to a protocol
  4143. // of IDecl's, then bridge casting is ok.
  4144. bool Conforms = false;
  4145. for (auto *Proto : OPT->quals()) {
  4146. Conforms = false;
  4147. for (auto *PI : InheritedProtocols) {
  4148. if (ProtocolCompatibleWithProtocol(Proto, PI)) {
  4149. Conforms = true;
  4150. break;
  4151. }
  4152. }
  4153. if (!Conforms)
  4154. break;
  4155. }
  4156. if (Conforms)
  4157. return true;
  4158. for (auto *PI : InheritedProtocols) {
  4159. // If both the right and left sides have qualifiers.
  4160. bool Adopts = false;
  4161. for (auto *Proto : OPT->quals()) {
  4162. // return 'true' if 'PI' is in the inheritance hierarchy of Proto
  4163. if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
  4164. break;
  4165. }
  4166. if (!Adopts)
  4167. return false;
  4168. }
  4169. return true;
  4170. }
  4171. /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
  4172. /// the given object type.
  4173. QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
  4174. llvm::FoldingSetNodeID ID;
  4175. ObjCObjectPointerType::Profile(ID, ObjectT);
  4176. void *InsertPos = nullptr;
  4177. if (ObjCObjectPointerType *QT =
  4178. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
  4179. return QualType(QT, 0);
  4180. // Find the canonical object type.
  4181. QualType Canonical;
  4182. if (!ObjectT.isCanonical()) {
  4183. Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
  4184. // Regenerate InsertPos.
  4185. ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
  4186. }
  4187. // No match.
  4188. void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
  4189. auto *QType =
  4190. new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
  4191. Types.push_back(QType);
  4192. ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
  4193. return QualType(QType, 0);
  4194. }
  4195. /// getObjCInterfaceType - Return the unique reference to the type for the
  4196. /// specified ObjC interface decl. The list of protocols is optional.
  4197. QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  4198. ObjCInterfaceDecl *PrevDecl) const {
  4199. if (Decl->TypeForDecl)
  4200. return QualType(Decl->TypeForDecl, 0);
  4201. if (PrevDecl) {
  4202. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  4203. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  4204. return QualType(PrevDecl->TypeForDecl, 0);
  4205. }
  4206. // Prefer the definition, if there is one.
  4207. if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
  4208. Decl = Def;
  4209. void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
  4210. auto *T = new (Mem) ObjCInterfaceType(Decl);
  4211. Decl->TypeForDecl = T;
  4212. Types.push_back(T);
  4213. return QualType(T, 0);
  4214. }
  4215. /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
  4216. /// TypeOfExprType AST's (since expression's are never shared). For example,
  4217. /// multiple declarations that refer to "typeof(x)" all contain different
  4218. /// DeclRefExpr's. This doesn't effect the type checker, since it operates
  4219. /// on canonical type's (which are always unique).
  4220. QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
  4221. TypeOfExprType *toe;
  4222. if (tofExpr->isTypeDependent()) {
  4223. llvm::FoldingSetNodeID ID;
  4224. DependentTypeOfExprType::Profile(ID, *this, tofExpr);
  4225. void *InsertPos = nullptr;
  4226. DependentTypeOfExprType *Canon
  4227. = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
  4228. if (Canon) {
  4229. // We already have a "canonical" version of an identical, dependent
  4230. // typeof(expr) type. Use that as our canonical type.
  4231. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
  4232. QualType((TypeOfExprType*)Canon, 0));
  4233. } else {
  4234. // Build a new, canonical typeof(expr) type.
  4235. Canon
  4236. = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
  4237. DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
  4238. toe = Canon;
  4239. }
  4240. } else {
  4241. QualType Canonical = getCanonicalType(tofExpr->getType());
  4242. toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
  4243. }
  4244. Types.push_back(toe);
  4245. return QualType(toe, 0);
  4246. }
  4247. /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique
  4248. /// TypeOfType nodes. The only motivation to unique these nodes would be
  4249. /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
  4250. /// an issue. This doesn't affect the type checker, since it operates
  4251. /// on canonical types (which are always unique).
  4252. QualType ASTContext::getTypeOfType(QualType tofType) const {
  4253. QualType Canonical = getCanonicalType(tofType);
  4254. auto *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
  4255. Types.push_back(tot);
  4256. return QualType(tot, 0);
  4257. }
  4258. /// Unlike many "get<Type>" functions, we don't unique DecltypeType
  4259. /// nodes. This would never be helpful, since each such type has its own
  4260. /// expression, and would not give a significant memory saving, since there
  4261. /// is an Expr tree under each such type.
  4262. QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
  4263. DecltypeType *dt;
  4264. // C++11 [temp.type]p2:
  4265. // If an expression e involves a template parameter, decltype(e) denotes a
  4266. // unique dependent type. Two such decltype-specifiers refer to the same
  4267. // type only if their expressions are equivalent (14.5.6.1).
  4268. if (e->isInstantiationDependent()) {
  4269. llvm::FoldingSetNodeID ID;
  4270. DependentDecltypeType::Profile(ID, *this, e);
  4271. void *InsertPos = nullptr;
  4272. DependentDecltypeType *Canon
  4273. = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
  4274. if (!Canon) {
  4275. // Build a new, canonical decltype(expr) type.
  4276. Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
  4277. DependentDecltypeTypes.InsertNode(Canon, InsertPos);
  4278. }
  4279. dt = new (*this, TypeAlignment)
  4280. DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
  4281. } else {
  4282. dt = new (*this, TypeAlignment)
  4283. DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
  4284. }
  4285. Types.push_back(dt);
  4286. return QualType(dt, 0);
  4287. }
  4288. /// getUnaryTransformationType - We don't unique these, since the memory
  4289. /// savings are minimal and these are rare.
  4290. QualType ASTContext::getUnaryTransformType(QualType BaseType,
  4291. QualType UnderlyingType,
  4292. UnaryTransformType::UTTKind Kind)
  4293. const {
  4294. UnaryTransformType *ut = nullptr;
  4295. if (BaseType->isDependentType()) {
  4296. // Look in the folding set for an existing type.
  4297. llvm::FoldingSetNodeID ID;
  4298. DependentUnaryTransformType::Profile(ID, getCanonicalType(BaseType), Kind);
  4299. void *InsertPos = nullptr;
  4300. DependentUnaryTransformType *Canon
  4301. = DependentUnaryTransformTypes.FindNodeOrInsertPos(ID, InsertPos);
  4302. if (!Canon) {
  4303. // Build a new, canonical __underlying_type(type) type.
  4304. Canon = new (*this, TypeAlignment)
  4305. DependentUnaryTransformType(*this, getCanonicalType(BaseType),
  4306. Kind);
  4307. DependentUnaryTransformTypes.InsertNode(Canon, InsertPos);
  4308. }
  4309. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4310. QualType(), Kind,
  4311. QualType(Canon, 0));
  4312. } else {
  4313. QualType CanonType = getCanonicalType(UnderlyingType);
  4314. ut = new (*this, TypeAlignment) UnaryTransformType (BaseType,
  4315. UnderlyingType, Kind,
  4316. CanonType);
  4317. }
  4318. Types.push_back(ut);
  4319. return QualType(ut, 0);
  4320. }
  4321. /// getAutoType - Return the uniqued reference to the 'auto' type which has been
  4322. /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
  4323. /// canonical deduced-but-dependent 'auto' type.
  4324. QualType ASTContext::getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
  4325. bool IsDependent, bool IsPack) const {
  4326. assert((!IsPack || IsDependent) && "only use IsPack for a dependent pack");
  4327. if (DeducedType.isNull() && Keyword == AutoTypeKeyword::Auto && !IsDependent)
  4328. return getAutoDeductType();
  4329. // Look in the folding set for an existing type.
  4330. void *InsertPos = nullptr;
  4331. llvm::FoldingSetNodeID ID;
  4332. AutoType::Profile(ID, DeducedType, Keyword, IsDependent, IsPack);
  4333. if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
  4334. return QualType(AT, 0);
  4335. auto *AT = new (*this, TypeAlignment)
  4336. AutoType(DeducedType, Keyword, IsDependent, IsPack);
  4337. Types.push_back(AT);
  4338. if (InsertPos)
  4339. AutoTypes.InsertNode(AT, InsertPos);
  4340. return QualType(AT, 0);
  4341. }
  4342. /// Return the uniqued reference to the deduced template specialization type
  4343. /// which has been deduced to the given type, or to the canonical undeduced
  4344. /// such type, or the canonical deduced-but-dependent such type.
  4345. QualType ASTContext::getDeducedTemplateSpecializationType(
  4346. TemplateName Template, QualType DeducedType, bool IsDependent) const {
  4347. // Look in the folding set for an existing type.
  4348. void *InsertPos = nullptr;
  4349. llvm::FoldingSetNodeID ID;
  4350. DeducedTemplateSpecializationType::Profile(ID, Template, DeducedType,
  4351. IsDependent);
  4352. if (DeducedTemplateSpecializationType *DTST =
  4353. DeducedTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos))
  4354. return QualType(DTST, 0);
  4355. auto *DTST = new (*this, TypeAlignment)
  4356. DeducedTemplateSpecializationType(Template, DeducedType, IsDependent);
  4357. Types.push_back(DTST);
  4358. if (InsertPos)
  4359. DeducedTemplateSpecializationTypes.InsertNode(DTST, InsertPos);
  4360. return QualType(DTST, 0);
  4361. }
  4362. /// getAtomicType - Return the uniqued reference to the atomic type for
  4363. /// the given value type.
  4364. QualType ASTContext::getAtomicType(QualType T) const {
  4365. // Unique pointers, to guarantee there is only one pointer of a particular
  4366. // structure.
  4367. llvm::FoldingSetNodeID ID;
  4368. AtomicType::Profile(ID, T);
  4369. void *InsertPos = nullptr;
  4370. if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
  4371. return QualType(AT, 0);
  4372. // If the atomic value type isn't canonical, this won't be a canonical type
  4373. // either, so fill in the canonical type field.
  4374. QualType Canonical;
  4375. if (!T.isCanonical()) {
  4376. Canonical = getAtomicType(getCanonicalType(T));
  4377. // Get the new insert position for the node we care about.
  4378. AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
  4379. assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
  4380. }
  4381. auto *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
  4382. Types.push_back(New);
  4383. AtomicTypes.InsertNode(New, InsertPos);
  4384. return QualType(New, 0);
  4385. }
  4386. /// getAutoDeductType - Get type pattern for deducing against 'auto'.
  4387. QualType ASTContext::getAutoDeductType() const {
  4388. if (AutoDeductTy.isNull())
  4389. AutoDeductTy = QualType(
  4390. new (*this, TypeAlignment) AutoType(QualType(), AutoTypeKeyword::Auto,
  4391. /*dependent*/false, /*pack*/false),
  4392. 0);
  4393. return AutoDeductTy;
  4394. }
  4395. /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
  4396. QualType ASTContext::getAutoRRefDeductType() const {
  4397. if (AutoRRefDeductTy.isNull())
  4398. AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
  4399. assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
  4400. return AutoRRefDeductTy;
  4401. }
  4402. /// getTagDeclType - Return the unique reference to the type for the
  4403. /// specified TagDecl (struct/union/class/enum) decl.
  4404. QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
  4405. assert(Decl);
  4406. // FIXME: What is the design on getTagDeclType when it requires casting
  4407. // away const? mutable?
  4408. return getTypeDeclType(const_cast<TagDecl*>(Decl));
  4409. }
  4410. /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
  4411. /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
  4412. /// needs to agree with the definition in <stddef.h>.
  4413. CanQualType ASTContext::getSizeType() const {
  4414. return getFromTargetType(Target->getSizeType());
  4415. }
  4416. /// Return the unique signed counterpart of the integer type
  4417. /// corresponding to size_t.
  4418. CanQualType ASTContext::getSignedSizeType() const {
  4419. return getFromTargetType(Target->getSignedSizeType());
  4420. }
  4421. /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
  4422. CanQualType ASTContext::getIntMaxType() const {
  4423. return getFromTargetType(Target->getIntMaxType());
  4424. }
  4425. /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
  4426. CanQualType ASTContext::getUIntMaxType() const {
  4427. return getFromTargetType(Target->getUIntMaxType());
  4428. }
  4429. /// getSignedWCharType - Return the type of "signed wchar_t".
  4430. /// Used when in C++, as a GCC extension.
  4431. QualType ASTContext::getSignedWCharType() const {
  4432. // FIXME: derive from "Target" ?
  4433. return WCharTy;
  4434. }
  4435. /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
  4436. /// Used when in C++, as a GCC extension.
  4437. QualType ASTContext::getUnsignedWCharType() const {
  4438. // FIXME: derive from "Target" ?
  4439. return UnsignedIntTy;
  4440. }
  4441. QualType ASTContext::getIntPtrType() const {
  4442. return getFromTargetType(Target->getIntPtrType());
  4443. }
  4444. QualType ASTContext::getUIntPtrType() const {
  4445. return getCorrespondingUnsignedType(getIntPtrType());
  4446. }
  4447. /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
  4448. /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  4449. QualType ASTContext::getPointerDiffType() const {
  4450. return getFromTargetType(Target->getPtrDiffType(0));
  4451. }
  4452. /// Return the unique unsigned counterpart of "ptrdiff_t"
  4453. /// integer type. The standard (C11 7.21.6.1p7) refers to this type
  4454. /// in the definition of %tu format specifier.
  4455. QualType ASTContext::getUnsignedPointerDiffType() const {
  4456. return getFromTargetType(Target->getUnsignedPtrDiffType(0));
  4457. }
  4458. /// Return the unique type for "pid_t" defined in
  4459. /// <sys/types.h>. We need this to compute the correct type for vfork().
  4460. QualType ASTContext::getProcessIDType() const {
  4461. return getFromTargetType(Target->getProcessIDType());
  4462. }
  4463. //===----------------------------------------------------------------------===//
  4464. // Type Operators
  4465. //===----------------------------------------------------------------------===//
  4466. CanQualType ASTContext::getCanonicalParamType(QualType T) const {
  4467. // Push qualifiers into arrays, and then discard any remaining
  4468. // qualifiers.
  4469. T = getCanonicalType(T);
  4470. T = getVariableArrayDecayedType(T);
  4471. const Type *Ty = T.getTypePtr();
  4472. QualType Result;
  4473. if (isa<ArrayType>(Ty)) {
  4474. Result = getArrayDecayedType(QualType(Ty,0));
  4475. } else if (isa<FunctionType>(Ty)) {
  4476. Result = getPointerType(QualType(Ty, 0));
  4477. } else {
  4478. Result = QualType(Ty, 0);
  4479. }
  4480. return CanQualType::CreateUnsafe(Result);
  4481. }
  4482. QualType ASTContext::getUnqualifiedArrayType(QualType type,
  4483. Qualifiers &quals) {
  4484. SplitQualType splitType = type.getSplitUnqualifiedType();
  4485. // FIXME: getSplitUnqualifiedType() actually walks all the way to
  4486. // the unqualified desugared type and then drops it on the floor.
  4487. // We then have to strip that sugar back off with
  4488. // getUnqualifiedDesugaredType(), which is silly.
  4489. const auto *AT =
  4490. dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
  4491. // If we don't have an array, just use the results in splitType.
  4492. if (!AT) {
  4493. quals = splitType.Quals;
  4494. return QualType(splitType.Ty, 0);
  4495. }
  4496. // Otherwise, recurse on the array's element type.
  4497. QualType elementType = AT->getElementType();
  4498. QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
  4499. // If that didn't change the element type, AT has no qualifiers, so we
  4500. // can just use the results in splitType.
  4501. if (elementType == unqualElementType) {
  4502. assert(quals.empty()); // from the recursive call
  4503. quals = splitType.Quals;
  4504. return QualType(splitType.Ty, 0);
  4505. }
  4506. // Otherwise, add in the qualifiers from the outermost type, then
  4507. // build the type back up.
  4508. quals.addConsistentQualifiers(splitType.Quals);
  4509. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
  4510. return getConstantArrayType(unqualElementType, CAT->getSize(),
  4511. CAT->getSizeExpr(), CAT->getSizeModifier(), 0);
  4512. }
  4513. if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT)) {
  4514. return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
  4515. }
  4516. if (const auto *VAT = dyn_cast<VariableArrayType>(AT)) {
  4517. return getVariableArrayType(unqualElementType,
  4518. VAT->getSizeExpr(),
  4519. VAT->getSizeModifier(),
  4520. VAT->getIndexTypeCVRQualifiers(),
  4521. VAT->getBracketsRange());
  4522. }
  4523. const auto *DSAT = cast<DependentSizedArrayType>(AT);
  4524. return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
  4525. DSAT->getSizeModifier(), 0,
  4526. SourceRange());
  4527. }
  4528. /// Attempt to unwrap two types that may both be array types with the same bound
  4529. /// (or both be array types of unknown bound) for the purpose of comparing the
  4530. /// cv-decomposition of two types per C++ [conv.qual].
  4531. bool ASTContext::UnwrapSimilarArrayTypes(QualType &T1, QualType &T2) {
  4532. bool UnwrappedAny = false;
  4533. while (true) {
  4534. auto *AT1 = getAsArrayType(T1);
  4535. if (!AT1) return UnwrappedAny;
  4536. auto *AT2 = getAsArrayType(T2);
  4537. if (!AT2) return UnwrappedAny;
  4538. // If we don't have two array types with the same constant bound nor two
  4539. // incomplete array types, we've unwrapped everything we can.
  4540. if (auto *CAT1 = dyn_cast<ConstantArrayType>(AT1)) {
  4541. auto *CAT2 = dyn_cast<ConstantArrayType>(AT2);
  4542. if (!CAT2 || CAT1->getSize() != CAT2->getSize())
  4543. return UnwrappedAny;
  4544. } else if (!isa<IncompleteArrayType>(AT1) ||
  4545. !isa<IncompleteArrayType>(AT2)) {
  4546. return UnwrappedAny;
  4547. }
  4548. T1 = AT1->getElementType();
  4549. T2 = AT2->getElementType();
  4550. UnwrappedAny = true;
  4551. }
  4552. }
  4553. /// Attempt to unwrap two types that may be similar (C++ [conv.qual]).
  4554. ///
  4555. /// If T1 and T2 are both pointer types of the same kind, or both array types
  4556. /// with the same bound, unwraps layers from T1 and T2 until a pointer type is
  4557. /// unwrapped. Top-level qualifiers on T1 and T2 are ignored.
  4558. ///
  4559. /// This function will typically be called in a loop that successively
  4560. /// "unwraps" pointer and pointer-to-member types to compare them at each
  4561. /// level.
  4562. ///
  4563. /// \return \c true if a pointer type was unwrapped, \c false if we reached a
  4564. /// pair of types that can't be unwrapped further.
  4565. bool ASTContext::UnwrapSimilarTypes(QualType &T1, QualType &T2) {
  4566. UnwrapSimilarArrayTypes(T1, T2);
  4567. const auto *T1PtrType = T1->getAs<PointerType>();
  4568. const auto *T2PtrType = T2->getAs<PointerType>();
  4569. if (T1PtrType && T2PtrType) {
  4570. T1 = T1PtrType->getPointeeType();
  4571. T2 = T2PtrType->getPointeeType();
  4572. return true;
  4573. }
  4574. const auto *T1MPType = T1->getAs<MemberPointerType>();
  4575. const auto *T2MPType = T2->getAs<MemberPointerType>();
  4576. if (T1MPType && T2MPType &&
  4577. hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
  4578. QualType(T2MPType->getClass(), 0))) {
  4579. T1 = T1MPType->getPointeeType();
  4580. T2 = T2MPType->getPointeeType();
  4581. return true;
  4582. }
  4583. if (getLangOpts().ObjC) {
  4584. const auto *T1OPType = T1->getAs<ObjCObjectPointerType>();
  4585. const auto *T2OPType = T2->getAs<ObjCObjectPointerType>();
  4586. if (T1OPType && T2OPType) {
  4587. T1 = T1OPType->getPointeeType();
  4588. T2 = T2OPType->getPointeeType();
  4589. return true;
  4590. }
  4591. }
  4592. // FIXME: Block pointers, too?
  4593. return false;
  4594. }
  4595. bool ASTContext::hasSimilarType(QualType T1, QualType T2) {
  4596. while (true) {
  4597. Qualifiers Quals;
  4598. T1 = getUnqualifiedArrayType(T1, Quals);
  4599. T2 = getUnqualifiedArrayType(T2, Quals);
  4600. if (hasSameType(T1, T2))
  4601. return true;
  4602. if (!UnwrapSimilarTypes(T1, T2))
  4603. return false;
  4604. }
  4605. }
  4606. bool ASTContext::hasCvrSimilarType(QualType T1, QualType T2) {
  4607. while (true) {
  4608. Qualifiers Quals1, Quals2;
  4609. T1 = getUnqualifiedArrayType(T1, Quals1);
  4610. T2 = getUnqualifiedArrayType(T2, Quals2);
  4611. Quals1.removeCVRQualifiers();
  4612. Quals2.removeCVRQualifiers();
  4613. if (Quals1 != Quals2)
  4614. return false;
  4615. if (hasSameType(T1, T2))
  4616. return true;
  4617. if (!UnwrapSimilarTypes(T1, T2))
  4618. return false;
  4619. }
  4620. }
  4621. DeclarationNameInfo
  4622. ASTContext::getNameForTemplate(TemplateName Name,
  4623. SourceLocation NameLoc) const {
  4624. switch (Name.getKind()) {
  4625. case TemplateName::QualifiedTemplate:
  4626. case TemplateName::Template:
  4627. // DNInfo work in progress: CHECKME: what about DNLoc?
  4628. return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
  4629. NameLoc);
  4630. case TemplateName::OverloadedTemplate: {
  4631. OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
  4632. // DNInfo work in progress: CHECKME: what about DNLoc?
  4633. return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
  4634. }
  4635. case TemplateName::AssumedTemplate: {
  4636. AssumedTemplateStorage *Storage = Name.getAsAssumedTemplateName();
  4637. return DeclarationNameInfo(Storage->getDeclName(), NameLoc);
  4638. }
  4639. case TemplateName::DependentTemplate: {
  4640. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  4641. DeclarationName DName;
  4642. if (DTN->isIdentifier()) {
  4643. DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
  4644. return DeclarationNameInfo(DName, NameLoc);
  4645. } else {
  4646. DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
  4647. // DNInfo work in progress: FIXME: source locations?
  4648. DeclarationNameLoc DNLoc;
  4649. DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
  4650. DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
  4651. return DeclarationNameInfo(DName, NameLoc, DNLoc);
  4652. }
  4653. }
  4654. case TemplateName::SubstTemplateTemplateParm: {
  4655. SubstTemplateTemplateParmStorage *subst
  4656. = Name.getAsSubstTemplateTemplateParm();
  4657. return DeclarationNameInfo(subst->getParameter()->getDeclName(),
  4658. NameLoc);
  4659. }
  4660. case TemplateName::SubstTemplateTemplateParmPack: {
  4661. SubstTemplateTemplateParmPackStorage *subst
  4662. = Name.getAsSubstTemplateTemplateParmPack();
  4663. return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
  4664. NameLoc);
  4665. }
  4666. }
  4667. llvm_unreachable("bad template name kind!");
  4668. }
  4669. TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
  4670. switch (Name.getKind()) {
  4671. case TemplateName::QualifiedTemplate:
  4672. case TemplateName::Template: {
  4673. TemplateDecl *Template = Name.getAsTemplateDecl();
  4674. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Template))
  4675. Template = getCanonicalTemplateTemplateParmDecl(TTP);
  4676. // The canonical template name is the canonical template declaration.
  4677. return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
  4678. }
  4679. case TemplateName::OverloadedTemplate:
  4680. case TemplateName::AssumedTemplate:
  4681. llvm_unreachable("cannot canonicalize unresolved template");
  4682. case TemplateName::DependentTemplate: {
  4683. DependentTemplateName *DTN = Name.getAsDependentTemplateName();
  4684. assert(DTN && "Non-dependent template names must refer to template decls.");
  4685. return DTN->CanonicalTemplateName;
  4686. }
  4687. case TemplateName::SubstTemplateTemplateParm: {
  4688. SubstTemplateTemplateParmStorage *subst
  4689. = Name.getAsSubstTemplateTemplateParm();
  4690. return getCanonicalTemplateName(subst->getReplacement());
  4691. }
  4692. case TemplateName::SubstTemplateTemplateParmPack: {
  4693. SubstTemplateTemplateParmPackStorage *subst
  4694. = Name.getAsSubstTemplateTemplateParmPack();
  4695. TemplateTemplateParmDecl *canonParameter
  4696. = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
  4697. TemplateArgument canonArgPack
  4698. = getCanonicalTemplateArgument(subst->getArgumentPack());
  4699. return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
  4700. }
  4701. }
  4702. llvm_unreachable("bad template name!");
  4703. }
  4704. bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
  4705. X = getCanonicalTemplateName(X);
  4706. Y = getCanonicalTemplateName(Y);
  4707. return X.getAsVoidPointer() == Y.getAsVoidPointer();
  4708. }
  4709. TemplateArgument
  4710. ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
  4711. switch (Arg.getKind()) {
  4712. case TemplateArgument::Null:
  4713. return Arg;
  4714. case TemplateArgument::Expression:
  4715. return Arg;
  4716. case TemplateArgument::Declaration: {
  4717. auto *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
  4718. return TemplateArgument(D, Arg.getParamTypeForDecl());
  4719. }
  4720. case TemplateArgument::NullPtr:
  4721. return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
  4722. /*isNullPtr*/true);
  4723. case TemplateArgument::Template:
  4724. return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
  4725. case TemplateArgument::TemplateExpansion:
  4726. return TemplateArgument(getCanonicalTemplateName(
  4727. Arg.getAsTemplateOrTemplatePattern()),
  4728. Arg.getNumTemplateExpansions());
  4729. case TemplateArgument::Integral:
  4730. return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
  4731. case TemplateArgument::Type:
  4732. return TemplateArgument(getCanonicalType(Arg.getAsType()));
  4733. case TemplateArgument::Pack: {
  4734. if (Arg.pack_size() == 0)
  4735. return Arg;
  4736. auto *CanonArgs = new (*this) TemplateArgument[Arg.pack_size()];
  4737. unsigned Idx = 0;
  4738. for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
  4739. AEnd = Arg.pack_end();
  4740. A != AEnd; (void)++A, ++Idx)
  4741. CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
  4742. return TemplateArgument(llvm::makeArrayRef(CanonArgs, Arg.pack_size()));
  4743. }
  4744. }
  4745. // Silence GCC warning
  4746. llvm_unreachable("Unhandled template argument kind");
  4747. }
  4748. NestedNameSpecifier *
  4749. ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
  4750. if (!NNS)
  4751. return nullptr;
  4752. switch (NNS->getKind()) {
  4753. case NestedNameSpecifier::Identifier:
  4754. // Canonicalize the prefix but keep the identifier the same.
  4755. return NestedNameSpecifier::Create(*this,
  4756. getCanonicalNestedNameSpecifier(NNS->getPrefix()),
  4757. NNS->getAsIdentifier());
  4758. case NestedNameSpecifier::Namespace:
  4759. // A namespace is canonical; build a nested-name-specifier with
  4760. // this namespace and no prefix.
  4761. return NestedNameSpecifier::Create(*this, nullptr,
  4762. NNS->getAsNamespace()->getOriginalNamespace());
  4763. case NestedNameSpecifier::NamespaceAlias:
  4764. // A namespace is canonical; build a nested-name-specifier with
  4765. // this namespace and no prefix.
  4766. return NestedNameSpecifier::Create(*this, nullptr,
  4767. NNS->getAsNamespaceAlias()->getNamespace()
  4768. ->getOriginalNamespace());
  4769. case NestedNameSpecifier::TypeSpec:
  4770. case NestedNameSpecifier::TypeSpecWithTemplate: {
  4771. QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
  4772. // If we have some kind of dependent-named type (e.g., "typename T::type"),
  4773. // break it apart into its prefix and identifier, then reconsititute those
  4774. // as the canonical nested-name-specifier. This is required to canonicalize
  4775. // a dependent nested-name-specifier involving typedefs of dependent-name
  4776. // types, e.g.,
  4777. // typedef typename T::type T1;
  4778. // typedef typename T1::type T2;
  4779. if (const auto *DNT = T->getAs<DependentNameType>())
  4780. return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
  4781. const_cast<IdentifierInfo *>(DNT->getIdentifier()));
  4782. // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
  4783. // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
  4784. // first place?
  4785. return NestedNameSpecifier::Create(*this, nullptr, false,
  4786. const_cast<Type *>(T.getTypePtr()));
  4787. }
  4788. case NestedNameSpecifier::Global:
  4789. case NestedNameSpecifier::Super:
  4790. // The global specifier and __super specifer are canonical and unique.
  4791. return NNS;
  4792. }
  4793. llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
  4794. }
  4795. const ArrayType *ASTContext::getAsArrayType(QualType T) const {
  4796. // Handle the non-qualified case efficiently.
  4797. if (!T.hasLocalQualifiers()) {
  4798. // Handle the common positive case fast.
  4799. if (const auto *AT = dyn_cast<ArrayType>(T))
  4800. return AT;
  4801. }
  4802. // Handle the common negative case fast.
  4803. if (!isa<ArrayType>(T.getCanonicalType()))
  4804. return nullptr;
  4805. // Apply any qualifiers from the array type to the element type. This
  4806. // implements C99 6.7.3p8: "If the specification of an array type includes
  4807. // any type qualifiers, the element type is so qualified, not the array type."
  4808. // If we get here, we either have type qualifiers on the type, or we have
  4809. // sugar such as a typedef in the way. If we have type qualifiers on the type
  4810. // we must propagate them down into the element type.
  4811. SplitQualType split = T.getSplitDesugaredType();
  4812. Qualifiers qs = split.Quals;
  4813. // If we have a simple case, just return now.
  4814. const auto *ATy = dyn_cast<ArrayType>(split.Ty);
  4815. if (!ATy || qs.empty())
  4816. return ATy;
  4817. // Otherwise, we have an array and we have qualifiers on it. Push the
  4818. // qualifiers into the array element type and return a new array type.
  4819. QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
  4820. if (const auto *CAT = dyn_cast<ConstantArrayType>(ATy))
  4821. return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
  4822. CAT->getSizeExpr(),
  4823. CAT->getSizeModifier(),
  4824. CAT->getIndexTypeCVRQualifiers()));
  4825. if (const auto *IAT = dyn_cast<IncompleteArrayType>(ATy))
  4826. return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
  4827. IAT->getSizeModifier(),
  4828. IAT->getIndexTypeCVRQualifiers()));
  4829. if (const auto *DSAT = dyn_cast<DependentSizedArrayType>(ATy))
  4830. return cast<ArrayType>(
  4831. getDependentSizedArrayType(NewEltTy,
  4832. DSAT->getSizeExpr(),
  4833. DSAT->getSizeModifier(),
  4834. DSAT->getIndexTypeCVRQualifiers(),
  4835. DSAT->getBracketsRange()));
  4836. const auto *VAT = cast<VariableArrayType>(ATy);
  4837. return cast<ArrayType>(getVariableArrayType(NewEltTy,
  4838. VAT->getSizeExpr(),
  4839. VAT->getSizeModifier(),
  4840. VAT->getIndexTypeCVRQualifiers(),
  4841. VAT->getBracketsRange()));
  4842. }
  4843. QualType ASTContext::getAdjustedParameterType(QualType T) const {
  4844. if (T->isArrayType() || T->isFunctionType())
  4845. return getDecayedType(T);
  4846. return T;
  4847. }
  4848. QualType ASTContext::getSignatureParameterType(QualType T) const {
  4849. T = getVariableArrayDecayedType(T);
  4850. T = getAdjustedParameterType(T);
  4851. return T.getUnqualifiedType();
  4852. }
  4853. QualType ASTContext::getExceptionObjectType(QualType T) const {
  4854. // C++ [except.throw]p3:
  4855. // A throw-expression initializes a temporary object, called the exception
  4856. // object, the type of which is determined by removing any top-level
  4857. // cv-qualifiers from the static type of the operand of throw and adjusting
  4858. // the type from "array of T" or "function returning T" to "pointer to T"
  4859. // or "pointer to function returning T", [...]
  4860. T = getVariableArrayDecayedType(T);
  4861. if (T->isArrayType() || T->isFunctionType())
  4862. T = getDecayedType(T);
  4863. return T.getUnqualifiedType();
  4864. }
  4865. /// getArrayDecayedType - Return the properly qualified result of decaying the
  4866. /// specified array type to a pointer. This operation is non-trivial when
  4867. /// handling typedefs etc. The canonical type of "T" must be an array type,
  4868. /// this returns a pointer to a properly qualified element of the array.
  4869. ///
  4870. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  4871. QualType ASTContext::getArrayDecayedType(QualType Ty) const {
  4872. // Get the element type with 'getAsArrayType' so that we don't lose any
  4873. // typedefs in the element type of the array. This also handles propagation
  4874. // of type qualifiers from the array type into the element type if present
  4875. // (C99 6.7.3p8).
  4876. const ArrayType *PrettyArrayType = getAsArrayType(Ty);
  4877. assert(PrettyArrayType && "Not an array type!");
  4878. QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
  4879. // int x[restrict 4] -> int *restrict
  4880. QualType Result = getQualifiedType(PtrTy,
  4881. PrettyArrayType->getIndexTypeQualifiers());
  4882. // int x[_Nullable] -> int * _Nullable
  4883. if (auto Nullability = Ty->getNullability(*this)) {
  4884. Result = const_cast<ASTContext *>(this)->getAttributedType(
  4885. AttributedType::getNullabilityAttrKind(*Nullability), Result, Result);
  4886. }
  4887. return Result;
  4888. }
  4889. QualType ASTContext::getBaseElementType(const ArrayType *array) const {
  4890. return getBaseElementType(array->getElementType());
  4891. }
  4892. QualType ASTContext::getBaseElementType(QualType type) const {
  4893. Qualifiers qs;
  4894. while (true) {
  4895. SplitQualType split = type.getSplitDesugaredType();
  4896. const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
  4897. if (!array) break;
  4898. type = array->getElementType();
  4899. qs.addConsistentQualifiers(split.Quals);
  4900. }
  4901. return getQualifiedType(type, qs);
  4902. }
  4903. /// getConstantArrayElementCount - Returns number of constant array elements.
  4904. uint64_t
  4905. ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const {
  4906. uint64_t ElementCount = 1;
  4907. do {
  4908. ElementCount *= CA->getSize().getZExtValue();
  4909. CA = dyn_cast_or_null<ConstantArrayType>(
  4910. CA->getElementType()->getAsArrayTypeUnsafe());
  4911. } while (CA);
  4912. return ElementCount;
  4913. }
  4914. /// getFloatingRank - Return a relative rank for floating point types.
  4915. /// This routine will assert if passed a built-in type that isn't a float.
  4916. static FloatingRank getFloatingRank(QualType T) {
  4917. if (const auto *CT = T->getAs<ComplexType>())
  4918. return getFloatingRank(CT->getElementType());
  4919. switch (T->castAs<BuiltinType>()->getKind()) {
  4920. default: llvm_unreachable("getFloatingRank(): not a floating type");
  4921. case BuiltinType::Float16: return Float16Rank;
  4922. case BuiltinType::Half: return HalfRank;
  4923. case BuiltinType::Float: return FloatRank;
  4924. case BuiltinType::Double: return DoubleRank;
  4925. case BuiltinType::LongDouble: return LongDoubleRank;
  4926. case BuiltinType::Float128: return Float128Rank;
  4927. }
  4928. }
  4929. /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
  4930. /// point or a complex type (based on typeDomain/typeSize).
  4931. /// 'typeDomain' is a real floating point or complex type.
  4932. /// 'typeSize' is a real floating point or complex type.
  4933. QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
  4934. QualType Domain) const {
  4935. FloatingRank EltRank = getFloatingRank(Size);
  4936. if (Domain->isComplexType()) {
  4937. switch (EltRank) {
  4938. case Float16Rank:
  4939. case HalfRank: llvm_unreachable("Complex half is not supported");
  4940. case FloatRank: return FloatComplexTy;
  4941. case DoubleRank: return DoubleComplexTy;
  4942. case LongDoubleRank: return LongDoubleComplexTy;
  4943. case Float128Rank: return Float128ComplexTy;
  4944. }
  4945. }
  4946. assert(Domain->isRealFloatingType() && "Unknown domain!");
  4947. switch (EltRank) {
  4948. case Float16Rank: return HalfTy;
  4949. case HalfRank: return HalfTy;
  4950. case FloatRank: return FloatTy;
  4951. case DoubleRank: return DoubleTy;
  4952. case LongDoubleRank: return LongDoubleTy;
  4953. case Float128Rank: return Float128Ty;
  4954. }
  4955. llvm_unreachable("getFloatingRank(): illegal value for rank");
  4956. }
  4957. /// getFloatingTypeOrder - Compare the rank of the two specified floating
  4958. /// point types, ignoring the domain of the type (i.e. 'double' ==
  4959. /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If
  4960. /// LHS < RHS, return -1.
  4961. int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
  4962. FloatingRank LHSR = getFloatingRank(LHS);
  4963. FloatingRank RHSR = getFloatingRank(RHS);
  4964. if (LHSR == RHSR)
  4965. return 0;
  4966. if (LHSR > RHSR)
  4967. return 1;
  4968. return -1;
  4969. }
  4970. int ASTContext::getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const {
  4971. if (&getFloatTypeSemantics(LHS) == &getFloatTypeSemantics(RHS))
  4972. return 0;
  4973. return getFloatingTypeOrder(LHS, RHS);
  4974. }
  4975. /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
  4976. /// routine will assert if passed a built-in type that isn't an integer or enum,
  4977. /// or if it is not canonicalized.
  4978. unsigned ASTContext::getIntegerRank(const Type *T) const {
  4979. assert(T->isCanonicalUnqualified() && "T should be canonicalized");
  4980. switch (cast<BuiltinType>(T)->getKind()) {
  4981. default: llvm_unreachable("getIntegerRank(): not a built-in integer");
  4982. case BuiltinType::Bool:
  4983. return 1 + (getIntWidth(BoolTy) << 3);
  4984. case BuiltinType::Char_S:
  4985. case BuiltinType::Char_U:
  4986. case BuiltinType::SChar:
  4987. case BuiltinType::UChar:
  4988. return 2 + (getIntWidth(CharTy) << 3);
  4989. case BuiltinType::Short:
  4990. case BuiltinType::UShort:
  4991. return 3 + (getIntWidth(ShortTy) << 3);
  4992. case BuiltinType::Int:
  4993. case BuiltinType::UInt:
  4994. return 4 + (getIntWidth(IntTy) << 3);
  4995. case BuiltinType::Long:
  4996. case BuiltinType::ULong:
  4997. return 5 + (getIntWidth(LongTy) << 3);
  4998. case BuiltinType::LongLong:
  4999. case BuiltinType::ULongLong:
  5000. return 6 + (getIntWidth(LongLongTy) << 3);
  5001. case BuiltinType::Int128:
  5002. case BuiltinType::UInt128:
  5003. return 7 + (getIntWidth(Int128Ty) << 3);
  5004. }
  5005. }
  5006. /// Whether this is a promotable bitfield reference according
  5007. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  5008. ///
  5009. /// \returns the type this bit-field will promote to, or NULL if no
  5010. /// promotion occurs.
  5011. QualType ASTContext::isPromotableBitField(Expr *E) const {
  5012. if (E->isTypeDependent() || E->isValueDependent())
  5013. return {};
  5014. // C++ [conv.prom]p5:
  5015. // If the bit-field has an enumerated type, it is treated as any other
  5016. // value of that type for promotion purposes.
  5017. if (getLangOpts().CPlusPlus && E->getType()->isEnumeralType())
  5018. return {};
  5019. // FIXME: We should not do this unless E->refersToBitField() is true. This
  5020. // matters in C where getSourceBitField() will find bit-fields for various
  5021. // cases where the source expression is not a bit-field designator.
  5022. FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
  5023. if (!Field)
  5024. return {};
  5025. QualType FT = Field->getType();
  5026. uint64_t BitWidth = Field->getBitWidthValue(*this);
  5027. uint64_t IntSize = getTypeSize(IntTy);
  5028. // C++ [conv.prom]p5:
  5029. // A prvalue for an integral bit-field can be converted to a prvalue of type
  5030. // int if int can represent all the values of the bit-field; otherwise, it
  5031. // can be converted to unsigned int if unsigned int can represent all the
  5032. // values of the bit-field. If the bit-field is larger yet, no integral
  5033. // promotion applies to it.
  5034. // C11 6.3.1.1/2:
  5035. // [For a bit-field of type _Bool, int, signed int, or unsigned int:]
  5036. // If an int can represent all values of the original type (as restricted by
  5037. // the width, for a bit-field), the value is converted to an int; otherwise,
  5038. // it is converted to an unsigned int.
  5039. //
  5040. // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
  5041. // We perform that promotion here to match GCC and C++.
  5042. // FIXME: C does not permit promotion of an enum bit-field whose rank is
  5043. // greater than that of 'int'. We perform that promotion to match GCC.
  5044. if (BitWidth < IntSize)
  5045. return IntTy;
  5046. if (BitWidth == IntSize)
  5047. return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
  5048. // Bit-fields wider than int are not subject to promotions, and therefore act
  5049. // like the base type. GCC has some weird bugs in this area that we
  5050. // deliberately do not follow (GCC follows a pre-standard resolution to
  5051. // C's DR315 which treats bit-width as being part of the type, and this leaks
  5052. // into their semantics in some cases).
  5053. return {};
  5054. }
  5055. /// getPromotedIntegerType - Returns the type that Promotable will
  5056. /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
  5057. /// integer type.
  5058. QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
  5059. assert(!Promotable.isNull());
  5060. assert(Promotable->isPromotableIntegerType());
  5061. if (const auto *ET = Promotable->getAs<EnumType>())
  5062. return ET->getDecl()->getPromotionType();
  5063. if (const auto *BT = Promotable->getAs<BuiltinType>()) {
  5064. // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
  5065. // (3.9.1) can be converted to a prvalue of the first of the following
  5066. // types that can represent all the values of its underlying type:
  5067. // int, unsigned int, long int, unsigned long int, long long int, or
  5068. // unsigned long long int [...]
  5069. // FIXME: Is there some better way to compute this?
  5070. if (BT->getKind() == BuiltinType::WChar_S ||
  5071. BT->getKind() == BuiltinType::WChar_U ||
  5072. BT->getKind() == BuiltinType::Char8 ||
  5073. BT->getKind() == BuiltinType::Char16 ||
  5074. BT->getKind() == BuiltinType::Char32) {
  5075. bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
  5076. uint64_t FromSize = getTypeSize(BT);
  5077. QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
  5078. LongLongTy, UnsignedLongLongTy };
  5079. for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
  5080. uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
  5081. if (FromSize < ToSize ||
  5082. (FromSize == ToSize &&
  5083. FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
  5084. return PromoteTypes[Idx];
  5085. }
  5086. llvm_unreachable("char type should fit into long long");
  5087. }
  5088. }
  5089. // At this point, we should have a signed or unsigned integer type.
  5090. if (Promotable->isSignedIntegerType())
  5091. return IntTy;
  5092. uint64_t PromotableSize = getIntWidth(Promotable);
  5093. uint64_t IntSize = getIntWidth(IntTy);
  5094. assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
  5095. return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
  5096. }
  5097. /// Recurses in pointer/array types until it finds an objc retainable
  5098. /// type and returns its ownership.
  5099. Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
  5100. while (!T.isNull()) {
  5101. if (T.getObjCLifetime() != Qualifiers::OCL_None)
  5102. return T.getObjCLifetime();
  5103. if (T->isArrayType())
  5104. T = getBaseElementType(T);
  5105. else if (const auto *PT = T->getAs<PointerType>())
  5106. T = PT->getPointeeType();
  5107. else if (const auto *RT = T->getAs<ReferenceType>())
  5108. T = RT->getPointeeType();
  5109. else
  5110. break;
  5111. }
  5112. return Qualifiers::OCL_None;
  5113. }
  5114. static const Type *getIntegerTypeForEnum(const EnumType *ET) {
  5115. // Incomplete enum types are not treated as integer types.
  5116. // FIXME: In C++, enum types are never integer types.
  5117. if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
  5118. return ET->getDecl()->getIntegerType().getTypePtr();
  5119. return nullptr;
  5120. }
  5121. /// getIntegerTypeOrder - Returns the highest ranked integer type:
  5122. /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If
  5123. /// LHS < RHS, return -1.
  5124. int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
  5125. const Type *LHSC = getCanonicalType(LHS).getTypePtr();
  5126. const Type *RHSC = getCanonicalType(RHS).getTypePtr();
  5127. // Unwrap enums to their underlying type.
  5128. if (const auto *ET = dyn_cast<EnumType>(LHSC))
  5129. LHSC = getIntegerTypeForEnum(ET);
  5130. if (const auto *ET = dyn_cast<EnumType>(RHSC))
  5131. RHSC = getIntegerTypeForEnum(ET);
  5132. if (LHSC == RHSC) return 0;
  5133. bool LHSUnsigned = LHSC->isUnsignedIntegerType();
  5134. bool RHSUnsigned = RHSC->isUnsignedIntegerType();
  5135. unsigned LHSRank = getIntegerRank(LHSC);
  5136. unsigned RHSRank = getIntegerRank(RHSC);
  5137. if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned.
  5138. if (LHSRank == RHSRank) return 0;
  5139. return LHSRank > RHSRank ? 1 : -1;
  5140. }
  5141. // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
  5142. if (LHSUnsigned) {
  5143. // If the unsigned [LHS] type is larger, return it.
  5144. if (LHSRank >= RHSRank)
  5145. return 1;
  5146. // If the signed type can represent all values of the unsigned type, it
  5147. // wins. Because we are dealing with 2's complement and types that are
  5148. // powers of two larger than each other, this is always safe.
  5149. return -1;
  5150. }
  5151. // If the unsigned [RHS] type is larger, return it.
  5152. if (RHSRank >= LHSRank)
  5153. return -1;
  5154. // If the signed type can represent all values of the unsigned type, it
  5155. // wins. Because we are dealing with 2's complement and types that are
  5156. // powers of two larger than each other, this is always safe.
  5157. return 1;
  5158. }
  5159. TypedefDecl *ASTContext::getCFConstantStringDecl() const {
  5160. if (CFConstantStringTypeDecl)
  5161. return CFConstantStringTypeDecl;
  5162. assert(!CFConstantStringTagDecl &&
  5163. "tag and typedef should be initialized together");
  5164. CFConstantStringTagDecl = buildImplicitRecord("__NSConstantString_tag");
  5165. CFConstantStringTagDecl->startDefinition();
  5166. struct {
  5167. QualType Type;
  5168. const char *Name;
  5169. } Fields[5];
  5170. unsigned Count = 0;
  5171. /// Objective-C ABI
  5172. ///
  5173. /// typedef struct __NSConstantString_tag {
  5174. /// const int *isa;
  5175. /// int flags;
  5176. /// const char *str;
  5177. /// long length;
  5178. /// } __NSConstantString;
  5179. ///
  5180. /// Swift ABI (4.1, 4.2)
  5181. ///
  5182. /// typedef struct __NSConstantString_tag {
  5183. /// uintptr_t _cfisa;
  5184. /// uintptr_t _swift_rc;
  5185. /// _Atomic(uint64_t) _cfinfoa;
  5186. /// const char *_ptr;
  5187. /// uint32_t _length;
  5188. /// } __NSConstantString;
  5189. ///
  5190. /// Swift ABI (5.0)
  5191. ///
  5192. /// typedef struct __NSConstantString_tag {
  5193. /// uintptr_t _cfisa;
  5194. /// uintptr_t _swift_rc;
  5195. /// _Atomic(uint64_t) _cfinfoa;
  5196. /// const char *_ptr;
  5197. /// uintptr_t _length;
  5198. /// } __NSConstantString;
  5199. const auto CFRuntime = getLangOpts().CFRuntime;
  5200. if (static_cast<unsigned>(CFRuntime) <
  5201. static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift)) {
  5202. Fields[Count++] = { getPointerType(IntTy.withConst()), "isa" };
  5203. Fields[Count++] = { IntTy, "flags" };
  5204. Fields[Count++] = { getPointerType(CharTy.withConst()), "str" };
  5205. Fields[Count++] = { LongTy, "length" };
  5206. } else {
  5207. Fields[Count++] = { getUIntPtrType(), "_cfisa" };
  5208. Fields[Count++] = { getUIntPtrType(), "_swift_rc" };
  5209. Fields[Count++] = { getFromTargetType(Target->getUInt64Type()), "_swift_rc" };
  5210. Fields[Count++] = { getPointerType(CharTy.withConst()), "_ptr" };
  5211. if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
  5212. CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
  5213. Fields[Count++] = { IntTy, "_ptr" };
  5214. else
  5215. Fields[Count++] = { getUIntPtrType(), "_ptr" };
  5216. }
  5217. // Create fields
  5218. for (unsigned i = 0; i < Count; ++i) {
  5219. FieldDecl *Field =
  5220. FieldDecl::Create(*this, CFConstantStringTagDecl, SourceLocation(),
  5221. SourceLocation(), &Idents.get(Fields[i].Name),
  5222. Fields[i].Type, /*TInfo=*/nullptr,
  5223. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  5224. Field->setAccess(AS_public);
  5225. CFConstantStringTagDecl->addDecl(Field);
  5226. }
  5227. CFConstantStringTagDecl->completeDefinition();
  5228. // This type is designed to be compatible with NSConstantString, but cannot
  5229. // use the same name, since NSConstantString is an interface.
  5230. auto tagType = getTagDeclType(CFConstantStringTagDecl);
  5231. CFConstantStringTypeDecl =
  5232. buildImplicitTypedef(tagType, "__NSConstantString");
  5233. return CFConstantStringTypeDecl;
  5234. }
  5235. RecordDecl *ASTContext::getCFConstantStringTagDecl() const {
  5236. if (!CFConstantStringTagDecl)
  5237. getCFConstantStringDecl(); // Build the tag and the typedef.
  5238. return CFConstantStringTagDecl;
  5239. }
  5240. // getCFConstantStringType - Return the type used for constant CFStrings.
  5241. QualType ASTContext::getCFConstantStringType() const {
  5242. return getTypedefType(getCFConstantStringDecl());
  5243. }
  5244. QualType ASTContext::getObjCSuperType() const {
  5245. if (ObjCSuperType.isNull()) {
  5246. RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
  5247. TUDecl->addDecl(ObjCSuperTypeDecl);
  5248. ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
  5249. }
  5250. return ObjCSuperType;
  5251. }
  5252. void ASTContext::setCFConstantStringType(QualType T) {
  5253. const auto *TD = T->castAs<TypedefType>();
  5254. CFConstantStringTypeDecl = cast<TypedefDecl>(TD->getDecl());
  5255. const auto *TagType =
  5256. CFConstantStringTypeDecl->getUnderlyingType()->castAs<RecordType>();
  5257. CFConstantStringTagDecl = TagType->getDecl();
  5258. }
  5259. QualType ASTContext::getBlockDescriptorType() const {
  5260. if (BlockDescriptorType)
  5261. return getTagDeclType(BlockDescriptorType);
  5262. RecordDecl *RD;
  5263. // FIXME: Needs the FlagAppleBlock bit.
  5264. RD = buildImplicitRecord("__block_descriptor");
  5265. RD->startDefinition();
  5266. QualType FieldTypes[] = {
  5267. UnsignedLongTy,
  5268. UnsignedLongTy,
  5269. };
  5270. static const char *const FieldNames[] = {
  5271. "reserved",
  5272. "Size"
  5273. };
  5274. for (size_t i = 0; i < 2; ++i) {
  5275. FieldDecl *Field = FieldDecl::Create(
  5276. *this, RD, SourceLocation(), SourceLocation(),
  5277. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  5278. /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
  5279. Field->setAccess(AS_public);
  5280. RD->addDecl(Field);
  5281. }
  5282. RD->completeDefinition();
  5283. BlockDescriptorType = RD;
  5284. return getTagDeclType(BlockDescriptorType);
  5285. }
  5286. QualType ASTContext::getBlockDescriptorExtendedType() const {
  5287. if (BlockDescriptorExtendedType)
  5288. return getTagDeclType(BlockDescriptorExtendedType);
  5289. RecordDecl *RD;
  5290. // FIXME: Needs the FlagAppleBlock bit.
  5291. RD = buildImplicitRecord("__block_descriptor_withcopydispose");
  5292. RD->startDefinition();
  5293. QualType FieldTypes[] = {
  5294. UnsignedLongTy,
  5295. UnsignedLongTy,
  5296. getPointerType(VoidPtrTy),
  5297. getPointerType(VoidPtrTy)
  5298. };
  5299. static const char *const FieldNames[] = {
  5300. "reserved",
  5301. "Size",
  5302. "CopyFuncPtr",
  5303. "DestroyFuncPtr"
  5304. };
  5305. for (size_t i = 0; i < 4; ++i) {
  5306. FieldDecl *Field = FieldDecl::Create(
  5307. *this, RD, SourceLocation(), SourceLocation(),
  5308. &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
  5309. /*BitWidth=*/nullptr,
  5310. /*Mutable=*/false, ICIS_NoInit);
  5311. Field->setAccess(AS_public);
  5312. RD->addDecl(Field);
  5313. }
  5314. RD->completeDefinition();
  5315. BlockDescriptorExtendedType = RD;
  5316. return getTagDeclType(BlockDescriptorExtendedType);
  5317. }
  5318. TargetInfo::OpenCLTypeKind ASTContext::getOpenCLTypeKind(const Type *T) const {
  5319. const auto *BT = dyn_cast<BuiltinType>(T);
  5320. if (!BT) {
  5321. if (isa<PipeType>(T))
  5322. return TargetInfo::OCLTK_Pipe;
  5323. return TargetInfo::OCLTK_Default;
  5324. }
  5325. switch (BT->getKind()) {
  5326. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5327. case BuiltinType::Id: \
  5328. return TargetInfo::OCLTK_Image;
  5329. #include "clang/Basic/OpenCLImageTypes.def"
  5330. case BuiltinType::OCLClkEvent:
  5331. return TargetInfo::OCLTK_ClkEvent;
  5332. case BuiltinType::OCLEvent:
  5333. return TargetInfo::OCLTK_Event;
  5334. case BuiltinType::OCLQueue:
  5335. return TargetInfo::OCLTK_Queue;
  5336. case BuiltinType::OCLReserveID:
  5337. return TargetInfo::OCLTK_ReserveID;
  5338. case BuiltinType::OCLSampler:
  5339. return TargetInfo::OCLTK_Sampler;
  5340. default:
  5341. return TargetInfo::OCLTK_Default;
  5342. }
  5343. }
  5344. LangAS ASTContext::getOpenCLTypeAddrSpace(const Type *T) const {
  5345. return Target->getOpenCLTypeAddrSpace(getOpenCLTypeKind(T));
  5346. }
  5347. /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
  5348. /// requires copy/dispose. Note that this must match the logic
  5349. /// in buildByrefHelpers.
  5350. bool ASTContext::BlockRequiresCopying(QualType Ty,
  5351. const VarDecl *D) {
  5352. if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
  5353. const Expr *copyExpr = getBlockVarCopyInit(D).getCopyExpr();
  5354. if (!copyExpr && record->hasTrivialDestructor()) return false;
  5355. return true;
  5356. }
  5357. // The block needs copy/destroy helpers if Ty is non-trivial to destructively
  5358. // move or destroy.
  5359. if (Ty.isNonTrivialToPrimitiveDestructiveMove() || Ty.isDestructedType())
  5360. return true;
  5361. if (!Ty->isObjCRetainableType()) return false;
  5362. Qualifiers qs = Ty.getQualifiers();
  5363. // If we have lifetime, that dominates.
  5364. if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
  5365. switch (lifetime) {
  5366. case Qualifiers::OCL_None: llvm_unreachable("impossible");
  5367. // These are just bits as far as the runtime is concerned.
  5368. case Qualifiers::OCL_ExplicitNone:
  5369. case Qualifiers::OCL_Autoreleasing:
  5370. return false;
  5371. // These cases should have been taken care of when checking the type's
  5372. // non-triviality.
  5373. case Qualifiers::OCL_Weak:
  5374. case Qualifiers::OCL_Strong:
  5375. llvm_unreachable("impossible");
  5376. }
  5377. llvm_unreachable("fell out of lifetime switch!");
  5378. }
  5379. return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
  5380. Ty->isObjCObjectPointerType());
  5381. }
  5382. bool ASTContext::getByrefLifetime(QualType Ty,
  5383. Qualifiers::ObjCLifetime &LifeTime,
  5384. bool &HasByrefExtendedLayout) const {
  5385. if (!getLangOpts().ObjC ||
  5386. getLangOpts().getGC() != LangOptions::NonGC)
  5387. return false;
  5388. HasByrefExtendedLayout = false;
  5389. if (Ty->isRecordType()) {
  5390. HasByrefExtendedLayout = true;
  5391. LifeTime = Qualifiers::OCL_None;
  5392. } else if ((LifeTime = Ty.getObjCLifetime())) {
  5393. // Honor the ARC qualifiers.
  5394. } else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) {
  5395. // The MRR rule.
  5396. LifeTime = Qualifiers::OCL_ExplicitNone;
  5397. } else {
  5398. LifeTime = Qualifiers::OCL_None;
  5399. }
  5400. return true;
  5401. }
  5402. TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
  5403. if (!ObjCInstanceTypeDecl)
  5404. ObjCInstanceTypeDecl =
  5405. buildImplicitTypedef(getObjCIdType(), "instancetype");
  5406. return ObjCInstanceTypeDecl;
  5407. }
  5408. // This returns true if a type has been typedefed to BOOL:
  5409. // typedef <type> BOOL;
  5410. static bool isTypeTypedefedAsBOOL(QualType T) {
  5411. if (const auto *TT = dyn_cast<TypedefType>(T))
  5412. if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
  5413. return II->isStr("BOOL");
  5414. return false;
  5415. }
  5416. /// getObjCEncodingTypeSize returns size of type for objective-c encoding
  5417. /// purpose.
  5418. CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
  5419. if (!type->isIncompleteArrayType() && type->isIncompleteType())
  5420. return CharUnits::Zero();
  5421. CharUnits sz = getTypeSizeInChars(type);
  5422. // Make all integer and enum types at least as large as an int
  5423. if (sz.isPositive() && type->isIntegralOrEnumerationType())
  5424. sz = std::max(sz, getTypeSizeInChars(IntTy));
  5425. // Treat arrays as pointers, since that's how they're passed in.
  5426. else if (type->isArrayType())
  5427. sz = getTypeSizeInChars(VoidPtrTy);
  5428. return sz;
  5429. }
  5430. bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
  5431. return getTargetInfo().getCXXABI().isMicrosoft() &&
  5432. VD->isStaticDataMember() &&
  5433. VD->getType()->isIntegralOrEnumerationType() &&
  5434. !VD->getFirstDecl()->isOutOfLine() && VD->getFirstDecl()->hasInit();
  5435. }
  5436. ASTContext::InlineVariableDefinitionKind
  5437. ASTContext::getInlineVariableDefinitionKind(const VarDecl *VD) const {
  5438. if (!VD->isInline())
  5439. return InlineVariableDefinitionKind::None;
  5440. // In almost all cases, it's a weak definition.
  5441. auto *First = VD->getFirstDecl();
  5442. if (First->isInlineSpecified() || !First->isStaticDataMember())
  5443. return InlineVariableDefinitionKind::Weak;
  5444. // If there's a file-context declaration in this translation unit, it's a
  5445. // non-discardable definition.
  5446. for (auto *D : VD->redecls())
  5447. if (D->getLexicalDeclContext()->isFileContext() &&
  5448. !D->isInlineSpecified() && (D->isConstexpr() || First->isConstexpr()))
  5449. return InlineVariableDefinitionKind::Strong;
  5450. // If we've not seen one yet, we don't know.
  5451. return InlineVariableDefinitionKind::WeakUnknown;
  5452. }
  5453. static std::string charUnitsToString(const CharUnits &CU) {
  5454. return llvm::itostr(CU.getQuantity());
  5455. }
  5456. /// getObjCEncodingForBlock - Return the encoded type for this block
  5457. /// declaration.
  5458. std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
  5459. std::string S;
  5460. const BlockDecl *Decl = Expr->getBlockDecl();
  5461. QualType BlockTy =
  5462. Expr->getType()->castAs<BlockPointerType>()->getPointeeType();
  5463. QualType BlockReturnTy = BlockTy->castAs<FunctionType>()->getReturnType();
  5464. // Encode result type.
  5465. if (getLangOpts().EncodeExtendedBlockSig)
  5466. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, BlockReturnTy, S,
  5467. true /*Extended*/);
  5468. else
  5469. getObjCEncodingForType(BlockReturnTy, S);
  5470. // Compute size of all parameters.
  5471. // Start with computing size of a pointer in number of bytes.
  5472. // FIXME: There might(should) be a better way of doing this computation!
  5473. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  5474. CharUnits ParmOffset = PtrSize;
  5475. for (auto PI : Decl->parameters()) {
  5476. QualType PType = PI->getType();
  5477. CharUnits sz = getObjCEncodingTypeSize(PType);
  5478. if (sz.isZero())
  5479. continue;
  5480. assert(sz.isPositive() && "BlockExpr - Incomplete param type");
  5481. ParmOffset += sz;
  5482. }
  5483. // Size of the argument frame
  5484. S += charUnitsToString(ParmOffset);
  5485. // Block pointer and offset.
  5486. S += "@?0";
  5487. // Argument types.
  5488. ParmOffset = PtrSize;
  5489. for (auto PVDecl : Decl->parameters()) {
  5490. QualType PType = PVDecl->getOriginalType();
  5491. if (const auto *AT =
  5492. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5493. // Use array's original type only if it has known number of
  5494. // elements.
  5495. if (!isa<ConstantArrayType>(AT))
  5496. PType = PVDecl->getType();
  5497. } else if (PType->isFunctionType())
  5498. PType = PVDecl->getType();
  5499. if (getLangOpts().EncodeExtendedBlockSig)
  5500. getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
  5501. S, true /*Extended*/);
  5502. else
  5503. getObjCEncodingForType(PType, S);
  5504. S += charUnitsToString(ParmOffset);
  5505. ParmOffset += getObjCEncodingTypeSize(PType);
  5506. }
  5507. return S;
  5508. }
  5509. std::string
  5510. ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const {
  5511. std::string S;
  5512. // Encode result type.
  5513. getObjCEncodingForType(Decl->getReturnType(), S);
  5514. CharUnits ParmOffset;
  5515. // Compute size of all parameters.
  5516. for (auto PI : Decl->parameters()) {
  5517. QualType PType = PI->getType();
  5518. CharUnits sz = getObjCEncodingTypeSize(PType);
  5519. if (sz.isZero())
  5520. continue;
  5521. assert(sz.isPositive() &&
  5522. "getObjCEncodingForFunctionDecl - Incomplete param type");
  5523. ParmOffset += sz;
  5524. }
  5525. S += charUnitsToString(ParmOffset);
  5526. ParmOffset = CharUnits::Zero();
  5527. // Argument types.
  5528. for (auto PVDecl : Decl->parameters()) {
  5529. QualType PType = PVDecl->getOriginalType();
  5530. if (const auto *AT =
  5531. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5532. // Use array's original type only if it has known number of
  5533. // elements.
  5534. if (!isa<ConstantArrayType>(AT))
  5535. PType = PVDecl->getType();
  5536. } else if (PType->isFunctionType())
  5537. PType = PVDecl->getType();
  5538. getObjCEncodingForType(PType, S);
  5539. S += charUnitsToString(ParmOffset);
  5540. ParmOffset += getObjCEncodingTypeSize(PType);
  5541. }
  5542. return S;
  5543. }
  5544. /// getObjCEncodingForMethodParameter - Return the encoded type for a single
  5545. /// method parameter or return type. If Extended, include class names and
  5546. /// block object types.
  5547. void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  5548. QualType T, std::string& S,
  5549. bool Extended) const {
  5550. // Encode type qualifer, 'in', 'inout', etc. for the parameter.
  5551. getObjCEncodingForTypeQualifier(QT, S);
  5552. // Encode parameter type.
  5553. ObjCEncOptions Options = ObjCEncOptions()
  5554. .setExpandPointedToStructures()
  5555. .setExpandStructures()
  5556. .setIsOutermostType();
  5557. if (Extended)
  5558. Options.setEncodeBlockParameters().setEncodeClassNames();
  5559. getObjCEncodingForTypeImpl(T, S, Options, /*Field=*/nullptr);
  5560. }
  5561. /// getObjCEncodingForMethodDecl - Return the encoded type for this method
  5562. /// declaration.
  5563. std::string ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  5564. bool Extended) const {
  5565. // FIXME: This is not very efficient.
  5566. // Encode return type.
  5567. std::string S;
  5568. getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
  5569. Decl->getReturnType(), S, Extended);
  5570. // Compute size of all parameters.
  5571. // Start with computing size of a pointer in number of bytes.
  5572. // FIXME: There might(should) be a better way of doing this computation!
  5573. CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
  5574. // The first two arguments (self and _cmd) are pointers; account for
  5575. // their size.
  5576. CharUnits ParmOffset = 2 * PtrSize;
  5577. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  5578. E = Decl->sel_param_end(); PI != E; ++PI) {
  5579. QualType PType = (*PI)->getType();
  5580. CharUnits sz = getObjCEncodingTypeSize(PType);
  5581. if (sz.isZero())
  5582. continue;
  5583. assert(sz.isPositive() &&
  5584. "getObjCEncodingForMethodDecl - Incomplete param type");
  5585. ParmOffset += sz;
  5586. }
  5587. S += charUnitsToString(ParmOffset);
  5588. S += "@0:";
  5589. S += charUnitsToString(PtrSize);
  5590. // Argument types.
  5591. ParmOffset = 2 * PtrSize;
  5592. for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
  5593. E = Decl->sel_param_end(); PI != E; ++PI) {
  5594. const ParmVarDecl *PVDecl = *PI;
  5595. QualType PType = PVDecl->getOriginalType();
  5596. if (const auto *AT =
  5597. dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
  5598. // Use array's original type only if it has known number of
  5599. // elements.
  5600. if (!isa<ConstantArrayType>(AT))
  5601. PType = PVDecl->getType();
  5602. } else if (PType->isFunctionType())
  5603. PType = PVDecl->getType();
  5604. getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
  5605. PType, S, Extended);
  5606. S += charUnitsToString(ParmOffset);
  5607. ParmOffset += getObjCEncodingTypeSize(PType);
  5608. }
  5609. return S;
  5610. }
  5611. ObjCPropertyImplDecl *
  5612. ASTContext::getObjCPropertyImplDeclForPropertyDecl(
  5613. const ObjCPropertyDecl *PD,
  5614. const Decl *Container) const {
  5615. if (!Container)
  5616. return nullptr;
  5617. if (const auto *CID = dyn_cast<ObjCCategoryImplDecl>(Container)) {
  5618. for (auto *PID : CID->property_impls())
  5619. if (PID->getPropertyDecl() == PD)
  5620. return PID;
  5621. } else {
  5622. const auto *OID = cast<ObjCImplementationDecl>(Container);
  5623. for (auto *PID : OID->property_impls())
  5624. if (PID->getPropertyDecl() == PD)
  5625. return PID;
  5626. }
  5627. return nullptr;
  5628. }
  5629. /// getObjCEncodingForPropertyDecl - Return the encoded type for this
  5630. /// property declaration. If non-NULL, Container must be either an
  5631. /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
  5632. /// NULL when getting encodings for protocol properties.
  5633. /// Property attributes are stored as a comma-delimited C string. The simple
  5634. /// attributes readonly and bycopy are encoded as single characters. The
  5635. /// parametrized attributes, getter=name, setter=name, and ivar=name, are
  5636. /// encoded as single characters, followed by an identifier. Property types
  5637. /// are also encoded as a parametrized attribute. The characters used to encode
  5638. /// these attributes are defined by the following enumeration:
  5639. /// @code
  5640. /// enum PropertyAttributes {
  5641. /// kPropertyReadOnly = 'R', // property is read-only.
  5642. /// kPropertyBycopy = 'C', // property is a copy of the value last assigned
  5643. /// kPropertyByref = '&', // property is a reference to the value last assigned
  5644. /// kPropertyDynamic = 'D', // property is dynamic
  5645. /// kPropertyGetter = 'G', // followed by getter selector name
  5646. /// kPropertySetter = 'S', // followed by setter selector name
  5647. /// kPropertyInstanceVariable = 'V' // followed by instance variable name
  5648. /// kPropertyType = 'T' // followed by old-style type encoding.
  5649. /// kPropertyWeak = 'W' // 'weak' property
  5650. /// kPropertyStrong = 'P' // property GC'able
  5651. /// kPropertyNonAtomic = 'N' // property non-atomic
  5652. /// };
  5653. /// @endcode
  5654. std::string
  5655. ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  5656. const Decl *Container) const {
  5657. // Collect information from the property implementation decl(s).
  5658. bool Dynamic = false;
  5659. ObjCPropertyImplDecl *SynthesizePID = nullptr;
  5660. if (ObjCPropertyImplDecl *PropertyImpDecl =
  5661. getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
  5662. if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
  5663. Dynamic = true;
  5664. else
  5665. SynthesizePID = PropertyImpDecl;
  5666. }
  5667. // FIXME: This is not very efficient.
  5668. std::string S = "T";
  5669. // Encode result type.
  5670. // GCC has some special rules regarding encoding of properties which
  5671. // closely resembles encoding of ivars.
  5672. getObjCEncodingForPropertyType(PD->getType(), S);
  5673. if (PD->isReadOnly()) {
  5674. S += ",R";
  5675. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
  5676. S += ",C";
  5677. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
  5678. S += ",&";
  5679. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
  5680. S += ",W";
  5681. } else {
  5682. switch (PD->getSetterKind()) {
  5683. case ObjCPropertyDecl::Assign: break;
  5684. case ObjCPropertyDecl::Copy: S += ",C"; break;
  5685. case ObjCPropertyDecl::Retain: S += ",&"; break;
  5686. case ObjCPropertyDecl::Weak: S += ",W"; break;
  5687. }
  5688. }
  5689. // It really isn't clear at all what this means, since properties
  5690. // are "dynamic by default".
  5691. if (Dynamic)
  5692. S += ",D";
  5693. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
  5694. S += ",N";
  5695. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
  5696. S += ",G";
  5697. S += PD->getGetterName().getAsString();
  5698. }
  5699. if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
  5700. S += ",S";
  5701. S += PD->getSetterName().getAsString();
  5702. }
  5703. if (SynthesizePID) {
  5704. const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
  5705. S += ",V";
  5706. S += OID->getNameAsString();
  5707. }
  5708. // FIXME: OBJCGC: weak & strong
  5709. return S;
  5710. }
  5711. /// getLegacyIntegralTypeEncoding -
  5712. /// Another legacy compatibility encoding: 32-bit longs are encoded as
  5713. /// 'l' or 'L' , but not always. For typedefs, we need to use
  5714. /// 'i' or 'I' instead if encoding a struct field, or a pointer!
  5715. void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
  5716. if (isa<TypedefType>(PointeeTy.getTypePtr())) {
  5717. if (const auto *BT = PointeeTy->getAs<BuiltinType>()) {
  5718. if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
  5719. PointeeTy = UnsignedIntTy;
  5720. else
  5721. if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
  5722. PointeeTy = IntTy;
  5723. }
  5724. }
  5725. }
  5726. void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
  5727. const FieldDecl *Field,
  5728. QualType *NotEncodedT) const {
  5729. // We follow the behavior of gcc, expanding structures which are
  5730. // directly pointed to, and expanding embedded structures. Note that
  5731. // these rules are sufficient to prevent recursive encoding of the
  5732. // same type.
  5733. getObjCEncodingForTypeImpl(T, S,
  5734. ObjCEncOptions()
  5735. .setExpandPointedToStructures()
  5736. .setExpandStructures()
  5737. .setIsOutermostType(),
  5738. Field, NotEncodedT);
  5739. }
  5740. void ASTContext::getObjCEncodingForPropertyType(QualType T,
  5741. std::string& S) const {
  5742. // Encode result type.
  5743. // GCC has some special rules regarding encoding of properties which
  5744. // closely resembles encoding of ivars.
  5745. getObjCEncodingForTypeImpl(T, S,
  5746. ObjCEncOptions()
  5747. .setExpandPointedToStructures()
  5748. .setExpandStructures()
  5749. .setIsOutermostType()
  5750. .setEncodingProperty(),
  5751. /*Field=*/nullptr);
  5752. }
  5753. static char getObjCEncodingForPrimitiveType(const ASTContext *C,
  5754. const BuiltinType *BT) {
  5755. BuiltinType::Kind kind = BT->getKind();
  5756. switch (kind) {
  5757. case BuiltinType::Void: return 'v';
  5758. case BuiltinType::Bool: return 'B';
  5759. case BuiltinType::Char8:
  5760. case BuiltinType::Char_U:
  5761. case BuiltinType::UChar: return 'C';
  5762. case BuiltinType::Char16:
  5763. case BuiltinType::UShort: return 'S';
  5764. case BuiltinType::Char32:
  5765. case BuiltinType::UInt: return 'I';
  5766. case BuiltinType::ULong:
  5767. return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
  5768. case BuiltinType::UInt128: return 'T';
  5769. case BuiltinType::ULongLong: return 'Q';
  5770. case BuiltinType::Char_S:
  5771. case BuiltinType::SChar: return 'c';
  5772. case BuiltinType::Short: return 's';
  5773. case BuiltinType::WChar_S:
  5774. case BuiltinType::WChar_U:
  5775. case BuiltinType::Int: return 'i';
  5776. case BuiltinType::Long:
  5777. return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
  5778. case BuiltinType::LongLong: return 'q';
  5779. case BuiltinType::Int128: return 't';
  5780. case BuiltinType::Float: return 'f';
  5781. case BuiltinType::Double: return 'd';
  5782. case BuiltinType::LongDouble: return 'D';
  5783. case BuiltinType::NullPtr: return '*'; // like char*
  5784. case BuiltinType::Float16:
  5785. case BuiltinType::Float128:
  5786. case BuiltinType::Half:
  5787. case BuiltinType::ShortAccum:
  5788. case BuiltinType::Accum:
  5789. case BuiltinType::LongAccum:
  5790. case BuiltinType::UShortAccum:
  5791. case BuiltinType::UAccum:
  5792. case BuiltinType::ULongAccum:
  5793. case BuiltinType::ShortFract:
  5794. case BuiltinType::Fract:
  5795. case BuiltinType::LongFract:
  5796. case BuiltinType::UShortFract:
  5797. case BuiltinType::UFract:
  5798. case BuiltinType::ULongFract:
  5799. case BuiltinType::SatShortAccum:
  5800. case BuiltinType::SatAccum:
  5801. case BuiltinType::SatLongAccum:
  5802. case BuiltinType::SatUShortAccum:
  5803. case BuiltinType::SatUAccum:
  5804. case BuiltinType::SatULongAccum:
  5805. case BuiltinType::SatShortFract:
  5806. case BuiltinType::SatFract:
  5807. case BuiltinType::SatLongFract:
  5808. case BuiltinType::SatUShortFract:
  5809. case BuiltinType::SatUFract:
  5810. case BuiltinType::SatULongFract:
  5811. // FIXME: potentially need @encodes for these!
  5812. return ' ';
  5813. #define SVE_TYPE(Name, Id, SingletonId) \
  5814. case BuiltinType::Id:
  5815. #include "clang/Basic/AArch64SVEACLETypes.def"
  5816. {
  5817. DiagnosticsEngine &Diags = C->getDiagnostics();
  5818. unsigned DiagID = Diags.getCustomDiagID(
  5819. DiagnosticsEngine::Error, "cannot yet @encode type %0");
  5820. Diags.Report(DiagID) << BT->getName(C->getPrintingPolicy());
  5821. return ' ';
  5822. }
  5823. case BuiltinType::ObjCId:
  5824. case BuiltinType::ObjCClass:
  5825. case BuiltinType::ObjCSel:
  5826. llvm_unreachable("@encoding ObjC primitive type");
  5827. // OpenCL and placeholder types don't need @encodings.
  5828. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5829. case BuiltinType::Id:
  5830. #include "clang/Basic/OpenCLImageTypes.def"
  5831. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  5832. case BuiltinType::Id:
  5833. #include "clang/Basic/OpenCLExtensionTypes.def"
  5834. case BuiltinType::OCLEvent:
  5835. case BuiltinType::OCLClkEvent:
  5836. case BuiltinType::OCLQueue:
  5837. case BuiltinType::OCLReserveID:
  5838. case BuiltinType::OCLSampler:
  5839. case BuiltinType::Dependent:
  5840. #define BUILTIN_TYPE(KIND, ID)
  5841. #define PLACEHOLDER_TYPE(KIND, ID) \
  5842. case BuiltinType::KIND:
  5843. #include "clang/AST/BuiltinTypes.def"
  5844. llvm_unreachable("invalid builtin type for @encode");
  5845. }
  5846. llvm_unreachable("invalid BuiltinType::Kind value");
  5847. }
  5848. static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
  5849. EnumDecl *Enum = ET->getDecl();
  5850. // The encoding of an non-fixed enum type is always 'i', regardless of size.
  5851. if (!Enum->isFixed())
  5852. return 'i';
  5853. // The encoding of a fixed enum type matches its fixed underlying type.
  5854. const auto *BT = Enum->getIntegerType()->castAs<BuiltinType>();
  5855. return getObjCEncodingForPrimitiveType(C, BT);
  5856. }
  5857. static void EncodeBitField(const ASTContext *Ctx, std::string& S,
  5858. QualType T, const FieldDecl *FD) {
  5859. assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
  5860. S += 'b';
  5861. // The NeXT runtime encodes bit fields as b followed by the number of bits.
  5862. // The GNU runtime requires more information; bitfields are encoded as b,
  5863. // then the offset (in bits) of the first element, then the type of the
  5864. // bitfield, then the size in bits. For example, in this structure:
  5865. //
  5866. // struct
  5867. // {
  5868. // int integer;
  5869. // int flags:2;
  5870. // };
  5871. // On a 32-bit system, the encoding for flags would be b2 for the NeXT
  5872. // runtime, but b32i2 for the GNU runtime. The reason for this extra
  5873. // information is not especially sensible, but we're stuck with it for
  5874. // compatibility with GCC, although providing it breaks anything that
  5875. // actually uses runtime introspection and wants to work on both runtimes...
  5876. if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
  5877. uint64_t Offset;
  5878. if (const auto *IVD = dyn_cast<ObjCIvarDecl>(FD)) {
  5879. Offset = Ctx->lookupFieldBitOffset(IVD->getContainingInterface(), nullptr,
  5880. IVD);
  5881. } else {
  5882. const RecordDecl *RD = FD->getParent();
  5883. const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
  5884. Offset = RL.getFieldOffset(FD->getFieldIndex());
  5885. }
  5886. S += llvm::utostr(Offset);
  5887. if (const auto *ET = T->getAs<EnumType>())
  5888. S += ObjCEncodingForEnumType(Ctx, ET);
  5889. else {
  5890. const auto *BT = T->castAs<BuiltinType>();
  5891. S += getObjCEncodingForPrimitiveType(Ctx, BT);
  5892. }
  5893. }
  5894. S += llvm::utostr(FD->getBitWidthValue(*Ctx));
  5895. }
  5896. // FIXME: Use SmallString for accumulating string.
  5897. void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string &S,
  5898. const ObjCEncOptions Options,
  5899. const FieldDecl *FD,
  5900. QualType *NotEncodedT) const {
  5901. CanQualType CT = getCanonicalType(T);
  5902. switch (CT->getTypeClass()) {
  5903. case Type::Builtin:
  5904. case Type::Enum:
  5905. if (FD && FD->isBitField())
  5906. return EncodeBitField(this, S, T, FD);
  5907. if (const auto *BT = dyn_cast<BuiltinType>(CT))
  5908. S += getObjCEncodingForPrimitiveType(this, BT);
  5909. else
  5910. S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
  5911. return;
  5912. case Type::Complex: {
  5913. const auto *CT = T->castAs<ComplexType>();
  5914. S += 'j';
  5915. getObjCEncodingForTypeImpl(CT->getElementType(), S, ObjCEncOptions(),
  5916. /*Field=*/nullptr);
  5917. return;
  5918. }
  5919. case Type::Atomic: {
  5920. const auto *AT = T->castAs<AtomicType>();
  5921. S += 'A';
  5922. getObjCEncodingForTypeImpl(AT->getValueType(), S, ObjCEncOptions(),
  5923. /*Field=*/nullptr);
  5924. return;
  5925. }
  5926. // encoding for pointer or reference types.
  5927. case Type::Pointer:
  5928. case Type::LValueReference:
  5929. case Type::RValueReference: {
  5930. QualType PointeeTy;
  5931. if (isa<PointerType>(CT)) {
  5932. const auto *PT = T->castAs<PointerType>();
  5933. if (PT->isObjCSelType()) {
  5934. S += ':';
  5935. return;
  5936. }
  5937. PointeeTy = PT->getPointeeType();
  5938. } else {
  5939. PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
  5940. }
  5941. bool isReadOnly = false;
  5942. // For historical/compatibility reasons, the read-only qualifier of the
  5943. // pointee gets emitted _before_ the '^'. The read-only qualifier of
  5944. // the pointer itself gets ignored, _unless_ we are looking at a typedef!
  5945. // Also, do not emit the 'r' for anything but the outermost type!
  5946. if (isa<TypedefType>(T.getTypePtr())) {
  5947. if (Options.IsOutermostType() && T.isConstQualified()) {
  5948. isReadOnly = true;
  5949. S += 'r';
  5950. }
  5951. } else if (Options.IsOutermostType()) {
  5952. QualType P = PointeeTy;
  5953. while (auto PT = P->getAs<PointerType>())
  5954. P = PT->getPointeeType();
  5955. if (P.isConstQualified()) {
  5956. isReadOnly = true;
  5957. S += 'r';
  5958. }
  5959. }
  5960. if (isReadOnly) {
  5961. // Another legacy compatibility encoding. Some ObjC qualifier and type
  5962. // combinations need to be rearranged.
  5963. // Rewrite "in const" from "nr" to "rn"
  5964. if (StringRef(S).endswith("nr"))
  5965. S.replace(S.end()-2, S.end(), "rn");
  5966. }
  5967. if (PointeeTy->isCharType()) {
  5968. // char pointer types should be encoded as '*' unless it is a
  5969. // type that has been typedef'd to 'BOOL'.
  5970. if (!isTypeTypedefedAsBOOL(PointeeTy)) {
  5971. S += '*';
  5972. return;
  5973. }
  5974. } else if (const auto *RTy = PointeeTy->getAs<RecordType>()) {
  5975. // GCC binary compat: Need to convert "struct objc_class *" to "#".
  5976. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
  5977. S += '#';
  5978. return;
  5979. }
  5980. // GCC binary compat: Need to convert "struct objc_object *" to "@".
  5981. if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
  5982. S += '@';
  5983. return;
  5984. }
  5985. // fall through...
  5986. }
  5987. S += '^';
  5988. getLegacyIntegralTypeEncoding(PointeeTy);
  5989. ObjCEncOptions NewOptions;
  5990. if (Options.ExpandPointedToStructures())
  5991. NewOptions.setExpandStructures();
  5992. getObjCEncodingForTypeImpl(PointeeTy, S, NewOptions,
  5993. /*Field=*/nullptr, NotEncodedT);
  5994. return;
  5995. }
  5996. case Type::ConstantArray:
  5997. case Type::IncompleteArray:
  5998. case Type::VariableArray: {
  5999. const auto *AT = cast<ArrayType>(CT);
  6000. if (isa<IncompleteArrayType>(AT) && !Options.IsStructField()) {
  6001. // Incomplete arrays are encoded as a pointer to the array element.
  6002. S += '^';
  6003. getObjCEncodingForTypeImpl(
  6004. AT->getElementType(), S,
  6005. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD);
  6006. } else {
  6007. S += '[';
  6008. if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
  6009. S += llvm::utostr(CAT->getSize().getZExtValue());
  6010. else {
  6011. //Variable length arrays are encoded as a regular array with 0 elements.
  6012. assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
  6013. "Unknown array type!");
  6014. S += '0';
  6015. }
  6016. getObjCEncodingForTypeImpl(
  6017. AT->getElementType(), S,
  6018. Options.keepingOnly(ObjCEncOptions().setExpandStructures()), FD,
  6019. NotEncodedT);
  6020. S += ']';
  6021. }
  6022. return;
  6023. }
  6024. case Type::FunctionNoProto:
  6025. case Type::FunctionProto:
  6026. S += '?';
  6027. return;
  6028. case Type::Record: {
  6029. RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
  6030. S += RDecl->isUnion() ? '(' : '{';
  6031. // Anonymous structures print as '?'
  6032. if (const IdentifierInfo *II = RDecl->getIdentifier()) {
  6033. S += II->getName();
  6034. if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
  6035. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  6036. llvm::raw_string_ostream OS(S);
  6037. printTemplateArgumentList(OS, TemplateArgs.asArray(),
  6038. getPrintingPolicy());
  6039. }
  6040. } else {
  6041. S += '?';
  6042. }
  6043. if (Options.ExpandStructures()) {
  6044. S += '=';
  6045. if (!RDecl->isUnion()) {
  6046. getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
  6047. } else {
  6048. for (const auto *Field : RDecl->fields()) {
  6049. if (FD) {
  6050. S += '"';
  6051. S += Field->getNameAsString();
  6052. S += '"';
  6053. }
  6054. // Special case bit-fields.
  6055. if (Field->isBitField()) {
  6056. getObjCEncodingForTypeImpl(Field->getType(), S,
  6057. ObjCEncOptions().setExpandStructures(),
  6058. Field);
  6059. } else {
  6060. QualType qt = Field->getType();
  6061. getLegacyIntegralTypeEncoding(qt);
  6062. getObjCEncodingForTypeImpl(
  6063. qt, S,
  6064. ObjCEncOptions().setExpandStructures().setIsStructField(), FD,
  6065. NotEncodedT);
  6066. }
  6067. }
  6068. }
  6069. }
  6070. S += RDecl->isUnion() ? ')' : '}';
  6071. return;
  6072. }
  6073. case Type::BlockPointer: {
  6074. const auto *BT = T->castAs<BlockPointerType>();
  6075. S += "@?"; // Unlike a pointer-to-function, which is "^?".
  6076. if (Options.EncodeBlockParameters()) {
  6077. const auto *FT = BT->getPointeeType()->castAs<FunctionType>();
  6078. S += '<';
  6079. // Block return type
  6080. getObjCEncodingForTypeImpl(FT->getReturnType(), S,
  6081. Options.forComponentType(), FD, NotEncodedT);
  6082. // Block self
  6083. S += "@?";
  6084. // Block parameters
  6085. if (const auto *FPT = dyn_cast<FunctionProtoType>(FT)) {
  6086. for (const auto &I : FPT->param_types())
  6087. getObjCEncodingForTypeImpl(I, S, Options.forComponentType(), FD,
  6088. NotEncodedT);
  6089. }
  6090. S += '>';
  6091. }
  6092. return;
  6093. }
  6094. case Type::ObjCObject: {
  6095. // hack to match legacy encoding of *id and *Class
  6096. QualType Ty = getObjCObjectPointerType(CT);
  6097. if (Ty->isObjCIdType()) {
  6098. S += "{objc_object=}";
  6099. return;
  6100. }
  6101. else if (Ty->isObjCClassType()) {
  6102. S += "{objc_class=}";
  6103. return;
  6104. }
  6105. // TODO: Double check to make sure this intentionally falls through.
  6106. LLVM_FALLTHROUGH;
  6107. }
  6108. case Type::ObjCInterface: {
  6109. // Ignore protocol qualifiers when mangling at this level.
  6110. // @encode(class_name)
  6111. ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
  6112. S += '{';
  6113. S += OI->getObjCRuntimeNameAsString();
  6114. if (Options.ExpandStructures()) {
  6115. S += '=';
  6116. SmallVector<const ObjCIvarDecl*, 32> Ivars;
  6117. DeepCollectObjCIvars(OI, true, Ivars);
  6118. for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
  6119. const FieldDecl *Field = Ivars[i];
  6120. if (Field->isBitField())
  6121. getObjCEncodingForTypeImpl(Field->getType(), S,
  6122. ObjCEncOptions().setExpandStructures(),
  6123. Field);
  6124. else
  6125. getObjCEncodingForTypeImpl(Field->getType(), S,
  6126. ObjCEncOptions().setExpandStructures(), FD,
  6127. NotEncodedT);
  6128. }
  6129. }
  6130. S += '}';
  6131. return;
  6132. }
  6133. case Type::ObjCObjectPointer: {
  6134. const auto *OPT = T->castAs<ObjCObjectPointerType>();
  6135. if (OPT->isObjCIdType()) {
  6136. S += '@';
  6137. return;
  6138. }
  6139. if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
  6140. // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
  6141. // Since this is a binary compatibility issue, need to consult with
  6142. // runtime folks. Fortunately, this is a *very* obscure construct.
  6143. S += '#';
  6144. return;
  6145. }
  6146. if (OPT->isObjCQualifiedIdType()) {
  6147. getObjCEncodingForTypeImpl(
  6148. getObjCIdType(), S,
  6149. Options.keepingOnly(ObjCEncOptions()
  6150. .setExpandPointedToStructures()
  6151. .setExpandStructures()),
  6152. FD);
  6153. if (FD || Options.EncodingProperty() || Options.EncodeClassNames()) {
  6154. // Note that we do extended encoding of protocol qualifer list
  6155. // Only when doing ivar or property encoding.
  6156. S += '"';
  6157. for (const auto *I : OPT->quals()) {
  6158. S += '<';
  6159. S += I->getObjCRuntimeNameAsString();
  6160. S += '>';
  6161. }
  6162. S += '"';
  6163. }
  6164. return;
  6165. }
  6166. S += '@';
  6167. if (OPT->getInterfaceDecl() &&
  6168. (FD || Options.EncodingProperty() || Options.EncodeClassNames())) {
  6169. S += '"';
  6170. S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
  6171. for (const auto *I : OPT->quals()) {
  6172. S += '<';
  6173. S += I->getObjCRuntimeNameAsString();
  6174. S += '>';
  6175. }
  6176. S += '"';
  6177. }
  6178. return;
  6179. }
  6180. // gcc just blithely ignores member pointers.
  6181. // FIXME: we should do better than that. 'M' is available.
  6182. case Type::MemberPointer:
  6183. // This matches gcc's encoding, even though technically it is insufficient.
  6184. //FIXME. We should do a better job than gcc.
  6185. case Type::Vector:
  6186. case Type::ExtVector:
  6187. // Until we have a coherent encoding of these three types, issue warning.
  6188. if (NotEncodedT)
  6189. *NotEncodedT = T;
  6190. return;
  6191. // We could see an undeduced auto type here during error recovery.
  6192. // Just ignore it.
  6193. case Type::Auto:
  6194. case Type::DeducedTemplateSpecialization:
  6195. return;
  6196. case Type::Pipe:
  6197. #define ABSTRACT_TYPE(KIND, BASE)
  6198. #define TYPE(KIND, BASE)
  6199. #define DEPENDENT_TYPE(KIND, BASE) \
  6200. case Type::KIND:
  6201. #define NON_CANONICAL_TYPE(KIND, BASE) \
  6202. case Type::KIND:
  6203. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
  6204. case Type::KIND:
  6205. #include "clang/AST/TypeNodes.inc"
  6206. llvm_unreachable("@encode for dependent type!");
  6207. }
  6208. llvm_unreachable("bad type kind!");
  6209. }
  6210. void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
  6211. std::string &S,
  6212. const FieldDecl *FD,
  6213. bool includeVBases,
  6214. QualType *NotEncodedT) const {
  6215. assert(RDecl && "Expected non-null RecordDecl");
  6216. assert(!RDecl->isUnion() && "Should not be called for unions");
  6217. if (!RDecl->getDefinition() || RDecl->getDefinition()->isInvalidDecl())
  6218. return;
  6219. const auto *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
  6220. std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
  6221. const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
  6222. if (CXXRec) {
  6223. for (const auto &BI : CXXRec->bases()) {
  6224. if (!BI.isVirtual()) {
  6225. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  6226. if (base->isEmpty())
  6227. continue;
  6228. uint64_t offs = toBits(layout.getBaseClassOffset(base));
  6229. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6230. std::make_pair(offs, base));
  6231. }
  6232. }
  6233. }
  6234. unsigned i = 0;
  6235. for (auto *Field : RDecl->fields()) {
  6236. uint64_t offs = layout.getFieldOffset(i);
  6237. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6238. std::make_pair(offs, Field));
  6239. ++i;
  6240. }
  6241. if (CXXRec && includeVBases) {
  6242. for (const auto &BI : CXXRec->vbases()) {
  6243. CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
  6244. if (base->isEmpty())
  6245. continue;
  6246. uint64_t offs = toBits(layout.getVBaseClassOffset(base));
  6247. if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
  6248. FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
  6249. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
  6250. std::make_pair(offs, base));
  6251. }
  6252. }
  6253. CharUnits size;
  6254. if (CXXRec) {
  6255. size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
  6256. } else {
  6257. size = layout.getSize();
  6258. }
  6259. #ifndef NDEBUG
  6260. uint64_t CurOffs = 0;
  6261. #endif
  6262. std::multimap<uint64_t, NamedDecl *>::iterator
  6263. CurLayObj = FieldOrBaseOffsets.begin();
  6264. if (CXXRec && CXXRec->isDynamicClass() &&
  6265. (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
  6266. if (FD) {
  6267. S += "\"_vptr$";
  6268. std::string recname = CXXRec->getNameAsString();
  6269. if (recname.empty()) recname = "?";
  6270. S += recname;
  6271. S += '"';
  6272. }
  6273. S += "^^?";
  6274. #ifndef NDEBUG
  6275. CurOffs += getTypeSize(VoidPtrTy);
  6276. #endif
  6277. }
  6278. if (!RDecl->hasFlexibleArrayMember()) {
  6279. // Mark the end of the structure.
  6280. uint64_t offs = toBits(size);
  6281. FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
  6282. std::make_pair(offs, nullptr));
  6283. }
  6284. for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
  6285. #ifndef NDEBUG
  6286. assert(CurOffs <= CurLayObj->first);
  6287. if (CurOffs < CurLayObj->first) {
  6288. uint64_t padding = CurLayObj->first - CurOffs;
  6289. // FIXME: There doesn't seem to be a way to indicate in the encoding that
  6290. // packing/alignment of members is different that normal, in which case
  6291. // the encoding will be out-of-sync with the real layout.
  6292. // If the runtime switches to just consider the size of types without
  6293. // taking into account alignment, we could make padding explicit in the
  6294. // encoding (e.g. using arrays of chars). The encoding strings would be
  6295. // longer then though.
  6296. CurOffs += padding;
  6297. }
  6298. #endif
  6299. NamedDecl *dcl = CurLayObj->second;
  6300. if (!dcl)
  6301. break; // reached end of structure.
  6302. if (auto *base = dyn_cast<CXXRecordDecl>(dcl)) {
  6303. // We expand the bases without their virtual bases since those are going
  6304. // in the initial structure. Note that this differs from gcc which
  6305. // expands virtual bases each time one is encountered in the hierarchy,
  6306. // making the encoding type bigger than it really is.
  6307. getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
  6308. NotEncodedT);
  6309. assert(!base->isEmpty());
  6310. #ifndef NDEBUG
  6311. CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
  6312. #endif
  6313. } else {
  6314. const auto *field = cast<FieldDecl>(dcl);
  6315. if (FD) {
  6316. S += '"';
  6317. S += field->getNameAsString();
  6318. S += '"';
  6319. }
  6320. if (field->isBitField()) {
  6321. EncodeBitField(this, S, field->getType(), field);
  6322. #ifndef NDEBUG
  6323. CurOffs += field->getBitWidthValue(*this);
  6324. #endif
  6325. } else {
  6326. QualType qt = field->getType();
  6327. getLegacyIntegralTypeEncoding(qt);
  6328. getObjCEncodingForTypeImpl(
  6329. qt, S, ObjCEncOptions().setExpandStructures().setIsStructField(),
  6330. FD, NotEncodedT);
  6331. #ifndef NDEBUG
  6332. CurOffs += getTypeSize(field->getType());
  6333. #endif
  6334. }
  6335. }
  6336. }
  6337. }
  6338. void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  6339. std::string& S) const {
  6340. if (QT & Decl::OBJC_TQ_In)
  6341. S += 'n';
  6342. if (QT & Decl::OBJC_TQ_Inout)
  6343. S += 'N';
  6344. if (QT & Decl::OBJC_TQ_Out)
  6345. S += 'o';
  6346. if (QT & Decl::OBJC_TQ_Bycopy)
  6347. S += 'O';
  6348. if (QT & Decl::OBJC_TQ_Byref)
  6349. S += 'R';
  6350. if (QT & Decl::OBJC_TQ_Oneway)
  6351. S += 'V';
  6352. }
  6353. TypedefDecl *ASTContext::getObjCIdDecl() const {
  6354. if (!ObjCIdDecl) {
  6355. QualType T = getObjCObjectType(ObjCBuiltinIdTy, {}, {});
  6356. T = getObjCObjectPointerType(T);
  6357. ObjCIdDecl = buildImplicitTypedef(T, "id");
  6358. }
  6359. return ObjCIdDecl;
  6360. }
  6361. TypedefDecl *ASTContext::getObjCSelDecl() const {
  6362. if (!ObjCSelDecl) {
  6363. QualType T = getPointerType(ObjCBuiltinSelTy);
  6364. ObjCSelDecl = buildImplicitTypedef(T, "SEL");
  6365. }
  6366. return ObjCSelDecl;
  6367. }
  6368. TypedefDecl *ASTContext::getObjCClassDecl() const {
  6369. if (!ObjCClassDecl) {
  6370. QualType T = getObjCObjectType(ObjCBuiltinClassTy, {}, {});
  6371. T = getObjCObjectPointerType(T);
  6372. ObjCClassDecl = buildImplicitTypedef(T, "Class");
  6373. }
  6374. return ObjCClassDecl;
  6375. }
  6376. ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
  6377. if (!ObjCProtocolClassDecl) {
  6378. ObjCProtocolClassDecl
  6379. = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
  6380. SourceLocation(),
  6381. &Idents.get("Protocol"),
  6382. /*typeParamList=*/nullptr,
  6383. /*PrevDecl=*/nullptr,
  6384. SourceLocation(), true);
  6385. }
  6386. return ObjCProtocolClassDecl;
  6387. }
  6388. //===----------------------------------------------------------------------===//
  6389. // __builtin_va_list Construction Functions
  6390. //===----------------------------------------------------------------------===//
  6391. static TypedefDecl *CreateCharPtrNamedVaListDecl(const ASTContext *Context,
  6392. StringRef Name) {
  6393. // typedef char* __builtin[_ms]_va_list;
  6394. QualType T = Context->getPointerType(Context->CharTy);
  6395. return Context->buildImplicitTypedef(T, Name);
  6396. }
  6397. static TypedefDecl *CreateMSVaListDecl(const ASTContext *Context) {
  6398. return CreateCharPtrNamedVaListDecl(Context, "__builtin_ms_va_list");
  6399. }
  6400. static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
  6401. return CreateCharPtrNamedVaListDecl(Context, "__builtin_va_list");
  6402. }
  6403. static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
  6404. // typedef void* __builtin_va_list;
  6405. QualType T = Context->getPointerType(Context->VoidTy);
  6406. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  6407. }
  6408. static TypedefDecl *
  6409. CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
  6410. // struct __va_list
  6411. RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
  6412. if (Context->getLangOpts().CPlusPlus) {
  6413. // namespace std { struct __va_list {
  6414. NamespaceDecl *NS;
  6415. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  6416. Context->getTranslationUnitDecl(),
  6417. /*Inline*/ false, SourceLocation(),
  6418. SourceLocation(), &Context->Idents.get("std"),
  6419. /*PrevDecl*/ nullptr);
  6420. NS->setImplicit();
  6421. VaListTagDecl->setDeclContext(NS);
  6422. }
  6423. VaListTagDecl->startDefinition();
  6424. const size_t NumFields = 5;
  6425. QualType FieldTypes[NumFields];
  6426. const char *FieldNames[NumFields];
  6427. // void *__stack;
  6428. FieldTypes[0] = Context->getPointerType(Context->VoidTy);
  6429. FieldNames[0] = "__stack";
  6430. // void *__gr_top;
  6431. FieldTypes[1] = Context->getPointerType(Context->VoidTy);
  6432. FieldNames[1] = "__gr_top";
  6433. // void *__vr_top;
  6434. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6435. FieldNames[2] = "__vr_top";
  6436. // int __gr_offs;
  6437. FieldTypes[3] = Context->IntTy;
  6438. FieldNames[3] = "__gr_offs";
  6439. // int __vr_offs;
  6440. FieldTypes[4] = Context->IntTy;
  6441. FieldNames[4] = "__vr_offs";
  6442. // Create fields
  6443. for (unsigned i = 0; i < NumFields; ++i) {
  6444. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6445. VaListTagDecl,
  6446. SourceLocation(),
  6447. SourceLocation(),
  6448. &Context->Idents.get(FieldNames[i]),
  6449. FieldTypes[i], /*TInfo=*/nullptr,
  6450. /*BitWidth=*/nullptr,
  6451. /*Mutable=*/false,
  6452. ICIS_NoInit);
  6453. Field->setAccess(AS_public);
  6454. VaListTagDecl->addDecl(Field);
  6455. }
  6456. VaListTagDecl->completeDefinition();
  6457. Context->VaListTagDecl = VaListTagDecl;
  6458. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6459. // } __builtin_va_list;
  6460. return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
  6461. }
  6462. static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
  6463. // typedef struct __va_list_tag {
  6464. RecordDecl *VaListTagDecl;
  6465. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6466. VaListTagDecl->startDefinition();
  6467. const size_t NumFields = 5;
  6468. QualType FieldTypes[NumFields];
  6469. const char *FieldNames[NumFields];
  6470. // unsigned char gpr;
  6471. FieldTypes[0] = Context->UnsignedCharTy;
  6472. FieldNames[0] = "gpr";
  6473. // unsigned char fpr;
  6474. FieldTypes[1] = Context->UnsignedCharTy;
  6475. FieldNames[1] = "fpr";
  6476. // unsigned short reserved;
  6477. FieldTypes[2] = Context->UnsignedShortTy;
  6478. FieldNames[2] = "reserved";
  6479. // void* overflow_arg_area;
  6480. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6481. FieldNames[3] = "overflow_arg_area";
  6482. // void* reg_save_area;
  6483. FieldTypes[4] = Context->getPointerType(Context->VoidTy);
  6484. FieldNames[4] = "reg_save_area";
  6485. // Create fields
  6486. for (unsigned i = 0; i < NumFields; ++i) {
  6487. FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
  6488. SourceLocation(),
  6489. SourceLocation(),
  6490. &Context->Idents.get(FieldNames[i]),
  6491. FieldTypes[i], /*TInfo=*/nullptr,
  6492. /*BitWidth=*/nullptr,
  6493. /*Mutable=*/false,
  6494. ICIS_NoInit);
  6495. Field->setAccess(AS_public);
  6496. VaListTagDecl->addDecl(Field);
  6497. }
  6498. VaListTagDecl->completeDefinition();
  6499. Context->VaListTagDecl = VaListTagDecl;
  6500. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6501. // } __va_list_tag;
  6502. TypedefDecl *VaListTagTypedefDecl =
  6503. Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
  6504. QualType VaListTagTypedefType =
  6505. Context->getTypedefType(VaListTagTypedefDecl);
  6506. // typedef __va_list_tag __builtin_va_list[1];
  6507. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6508. QualType VaListTagArrayType
  6509. = Context->getConstantArrayType(VaListTagTypedefType,
  6510. Size, nullptr, ArrayType::Normal, 0);
  6511. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6512. }
  6513. static TypedefDecl *
  6514. CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
  6515. // struct __va_list_tag {
  6516. RecordDecl *VaListTagDecl;
  6517. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6518. VaListTagDecl->startDefinition();
  6519. const size_t NumFields = 4;
  6520. QualType FieldTypes[NumFields];
  6521. const char *FieldNames[NumFields];
  6522. // unsigned gp_offset;
  6523. FieldTypes[0] = Context->UnsignedIntTy;
  6524. FieldNames[0] = "gp_offset";
  6525. // unsigned fp_offset;
  6526. FieldTypes[1] = Context->UnsignedIntTy;
  6527. FieldNames[1] = "fp_offset";
  6528. // void* overflow_arg_area;
  6529. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6530. FieldNames[2] = "overflow_arg_area";
  6531. // void* reg_save_area;
  6532. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6533. FieldNames[3] = "reg_save_area";
  6534. // Create fields
  6535. for (unsigned i = 0; i < NumFields; ++i) {
  6536. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6537. VaListTagDecl,
  6538. SourceLocation(),
  6539. SourceLocation(),
  6540. &Context->Idents.get(FieldNames[i]),
  6541. FieldTypes[i], /*TInfo=*/nullptr,
  6542. /*BitWidth=*/nullptr,
  6543. /*Mutable=*/false,
  6544. ICIS_NoInit);
  6545. Field->setAccess(AS_public);
  6546. VaListTagDecl->addDecl(Field);
  6547. }
  6548. VaListTagDecl->completeDefinition();
  6549. Context->VaListTagDecl = VaListTagDecl;
  6550. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6551. // };
  6552. // typedef struct __va_list_tag __builtin_va_list[1];
  6553. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6554. QualType VaListTagArrayType = Context->getConstantArrayType(
  6555. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  6556. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6557. }
  6558. static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
  6559. // typedef int __builtin_va_list[4];
  6560. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
  6561. QualType IntArrayType = Context->getConstantArrayType(
  6562. Context->IntTy, Size, nullptr, ArrayType::Normal, 0);
  6563. return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
  6564. }
  6565. static TypedefDecl *
  6566. CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
  6567. // struct __va_list
  6568. RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
  6569. if (Context->getLangOpts().CPlusPlus) {
  6570. // namespace std { struct __va_list {
  6571. NamespaceDecl *NS;
  6572. NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
  6573. Context->getTranslationUnitDecl(),
  6574. /*Inline*/false, SourceLocation(),
  6575. SourceLocation(), &Context->Idents.get("std"),
  6576. /*PrevDecl*/ nullptr);
  6577. NS->setImplicit();
  6578. VaListDecl->setDeclContext(NS);
  6579. }
  6580. VaListDecl->startDefinition();
  6581. // void * __ap;
  6582. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6583. VaListDecl,
  6584. SourceLocation(),
  6585. SourceLocation(),
  6586. &Context->Idents.get("__ap"),
  6587. Context->getPointerType(Context->VoidTy),
  6588. /*TInfo=*/nullptr,
  6589. /*BitWidth=*/nullptr,
  6590. /*Mutable=*/false,
  6591. ICIS_NoInit);
  6592. Field->setAccess(AS_public);
  6593. VaListDecl->addDecl(Field);
  6594. // };
  6595. VaListDecl->completeDefinition();
  6596. Context->VaListTagDecl = VaListDecl;
  6597. // typedef struct __va_list __builtin_va_list;
  6598. QualType T = Context->getRecordType(VaListDecl);
  6599. return Context->buildImplicitTypedef(T, "__builtin_va_list");
  6600. }
  6601. static TypedefDecl *
  6602. CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
  6603. // struct __va_list_tag {
  6604. RecordDecl *VaListTagDecl;
  6605. VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
  6606. VaListTagDecl->startDefinition();
  6607. const size_t NumFields = 4;
  6608. QualType FieldTypes[NumFields];
  6609. const char *FieldNames[NumFields];
  6610. // long __gpr;
  6611. FieldTypes[0] = Context->LongTy;
  6612. FieldNames[0] = "__gpr";
  6613. // long __fpr;
  6614. FieldTypes[1] = Context->LongTy;
  6615. FieldNames[1] = "__fpr";
  6616. // void *__overflow_arg_area;
  6617. FieldTypes[2] = Context->getPointerType(Context->VoidTy);
  6618. FieldNames[2] = "__overflow_arg_area";
  6619. // void *__reg_save_area;
  6620. FieldTypes[3] = Context->getPointerType(Context->VoidTy);
  6621. FieldNames[3] = "__reg_save_area";
  6622. // Create fields
  6623. for (unsigned i = 0; i < NumFields; ++i) {
  6624. FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
  6625. VaListTagDecl,
  6626. SourceLocation(),
  6627. SourceLocation(),
  6628. &Context->Idents.get(FieldNames[i]),
  6629. FieldTypes[i], /*TInfo=*/nullptr,
  6630. /*BitWidth=*/nullptr,
  6631. /*Mutable=*/false,
  6632. ICIS_NoInit);
  6633. Field->setAccess(AS_public);
  6634. VaListTagDecl->addDecl(Field);
  6635. }
  6636. VaListTagDecl->completeDefinition();
  6637. Context->VaListTagDecl = VaListTagDecl;
  6638. QualType VaListTagType = Context->getRecordType(VaListTagDecl);
  6639. // };
  6640. // typedef __va_list_tag __builtin_va_list[1];
  6641. llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
  6642. QualType VaListTagArrayType = Context->getConstantArrayType(
  6643. VaListTagType, Size, nullptr, ArrayType::Normal, 0);
  6644. return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
  6645. }
  6646. static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
  6647. TargetInfo::BuiltinVaListKind Kind) {
  6648. switch (Kind) {
  6649. case TargetInfo::CharPtrBuiltinVaList:
  6650. return CreateCharPtrBuiltinVaListDecl(Context);
  6651. case TargetInfo::VoidPtrBuiltinVaList:
  6652. return CreateVoidPtrBuiltinVaListDecl(Context);
  6653. case TargetInfo::AArch64ABIBuiltinVaList:
  6654. return CreateAArch64ABIBuiltinVaListDecl(Context);
  6655. case TargetInfo::PowerABIBuiltinVaList:
  6656. return CreatePowerABIBuiltinVaListDecl(Context);
  6657. case TargetInfo::X86_64ABIBuiltinVaList:
  6658. return CreateX86_64ABIBuiltinVaListDecl(Context);
  6659. case TargetInfo::PNaClABIBuiltinVaList:
  6660. return CreatePNaClABIBuiltinVaListDecl(Context);
  6661. case TargetInfo::AAPCSABIBuiltinVaList:
  6662. return CreateAAPCSABIBuiltinVaListDecl(Context);
  6663. case TargetInfo::SystemZBuiltinVaList:
  6664. return CreateSystemZBuiltinVaListDecl(Context);
  6665. }
  6666. llvm_unreachable("Unhandled __builtin_va_list type kind");
  6667. }
  6668. TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
  6669. if (!BuiltinVaListDecl) {
  6670. BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
  6671. assert(BuiltinVaListDecl->isImplicit());
  6672. }
  6673. return BuiltinVaListDecl;
  6674. }
  6675. Decl *ASTContext::getVaListTagDecl() const {
  6676. // Force the creation of VaListTagDecl by building the __builtin_va_list
  6677. // declaration.
  6678. if (!VaListTagDecl)
  6679. (void)getBuiltinVaListDecl();
  6680. return VaListTagDecl;
  6681. }
  6682. TypedefDecl *ASTContext::getBuiltinMSVaListDecl() const {
  6683. if (!BuiltinMSVaListDecl)
  6684. BuiltinMSVaListDecl = CreateMSVaListDecl(this);
  6685. return BuiltinMSVaListDecl;
  6686. }
  6687. bool ASTContext::canBuiltinBeRedeclared(const FunctionDecl *FD) const {
  6688. return BuiltinInfo.canBeRedeclared(FD->getBuiltinID());
  6689. }
  6690. void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
  6691. assert(ObjCConstantStringType.isNull() &&
  6692. "'NSConstantString' type already set!");
  6693. ObjCConstantStringType = getObjCInterfaceType(Decl);
  6694. }
  6695. /// Retrieve the template name that corresponds to a non-empty
  6696. /// lookup.
  6697. TemplateName
  6698. ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
  6699. UnresolvedSetIterator End) const {
  6700. unsigned size = End - Begin;
  6701. assert(size > 1 && "set is not overloaded!");
  6702. void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
  6703. size * sizeof(FunctionTemplateDecl*));
  6704. auto *OT = new (memory) OverloadedTemplateStorage(size);
  6705. NamedDecl **Storage = OT->getStorage();
  6706. for (UnresolvedSetIterator I = Begin; I != End; ++I) {
  6707. NamedDecl *D = *I;
  6708. assert(isa<FunctionTemplateDecl>(D) ||
  6709. isa<UnresolvedUsingValueDecl>(D) ||
  6710. (isa<UsingShadowDecl>(D) &&
  6711. isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
  6712. *Storage++ = D;
  6713. }
  6714. return TemplateName(OT);
  6715. }
  6716. /// Retrieve a template name representing an unqualified-id that has been
  6717. /// assumed to name a template for ADL purposes.
  6718. TemplateName ASTContext::getAssumedTemplateName(DeclarationName Name) const {
  6719. auto *OT = new (*this) AssumedTemplateStorage(Name);
  6720. return TemplateName(OT);
  6721. }
  6722. /// Retrieve the template name that represents a qualified
  6723. /// template name such as \c std::vector.
  6724. TemplateName
  6725. ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
  6726. bool TemplateKeyword,
  6727. TemplateDecl *Template) const {
  6728. assert(NNS && "Missing nested-name-specifier in qualified template name");
  6729. // FIXME: Canonicalization?
  6730. llvm::FoldingSetNodeID ID;
  6731. QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
  6732. void *InsertPos = nullptr;
  6733. QualifiedTemplateName *QTN =
  6734. QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6735. if (!QTN) {
  6736. QTN = new (*this, alignof(QualifiedTemplateName))
  6737. QualifiedTemplateName(NNS, TemplateKeyword, Template);
  6738. QualifiedTemplateNames.InsertNode(QTN, InsertPos);
  6739. }
  6740. return TemplateName(QTN);
  6741. }
  6742. /// Retrieve the template name that represents a dependent
  6743. /// template name such as \c MetaFun::template apply.
  6744. TemplateName
  6745. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  6746. const IdentifierInfo *Name) const {
  6747. assert((!NNS || NNS->isDependent()) &&
  6748. "Nested name specifier must be dependent");
  6749. llvm::FoldingSetNodeID ID;
  6750. DependentTemplateName::Profile(ID, NNS, Name);
  6751. void *InsertPos = nullptr;
  6752. DependentTemplateName *QTN =
  6753. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6754. if (QTN)
  6755. return TemplateName(QTN);
  6756. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  6757. if (CanonNNS == NNS) {
  6758. QTN = new (*this, alignof(DependentTemplateName))
  6759. DependentTemplateName(NNS, Name);
  6760. } else {
  6761. TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
  6762. QTN = new (*this, alignof(DependentTemplateName))
  6763. DependentTemplateName(NNS, Name, Canon);
  6764. DependentTemplateName *CheckQTN =
  6765. DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6766. assert(!CheckQTN && "Dependent type name canonicalization broken");
  6767. (void)CheckQTN;
  6768. }
  6769. DependentTemplateNames.InsertNode(QTN, InsertPos);
  6770. return TemplateName(QTN);
  6771. }
  6772. /// Retrieve the template name that represents a dependent
  6773. /// template name such as \c MetaFun::template operator+.
  6774. TemplateName
  6775. ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
  6776. OverloadedOperatorKind Operator) const {
  6777. assert((!NNS || NNS->isDependent()) &&
  6778. "Nested name specifier must be dependent");
  6779. llvm::FoldingSetNodeID ID;
  6780. DependentTemplateName::Profile(ID, NNS, Operator);
  6781. void *InsertPos = nullptr;
  6782. DependentTemplateName *QTN
  6783. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6784. if (QTN)
  6785. return TemplateName(QTN);
  6786. NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
  6787. if (CanonNNS == NNS) {
  6788. QTN = new (*this, alignof(DependentTemplateName))
  6789. DependentTemplateName(NNS, Operator);
  6790. } else {
  6791. TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
  6792. QTN = new (*this, alignof(DependentTemplateName))
  6793. DependentTemplateName(NNS, Operator, Canon);
  6794. DependentTemplateName *CheckQTN
  6795. = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
  6796. assert(!CheckQTN && "Dependent template name canonicalization broken");
  6797. (void)CheckQTN;
  6798. }
  6799. DependentTemplateNames.InsertNode(QTN, InsertPos);
  6800. return TemplateName(QTN);
  6801. }
  6802. TemplateName
  6803. ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
  6804. TemplateName replacement) const {
  6805. llvm::FoldingSetNodeID ID;
  6806. SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
  6807. void *insertPos = nullptr;
  6808. SubstTemplateTemplateParmStorage *subst
  6809. = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
  6810. if (!subst) {
  6811. subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
  6812. SubstTemplateTemplateParms.InsertNode(subst, insertPos);
  6813. }
  6814. return TemplateName(subst);
  6815. }
  6816. TemplateName
  6817. ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
  6818. const TemplateArgument &ArgPack) const {
  6819. auto &Self = const_cast<ASTContext &>(*this);
  6820. llvm::FoldingSetNodeID ID;
  6821. SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
  6822. void *InsertPos = nullptr;
  6823. SubstTemplateTemplateParmPackStorage *Subst
  6824. = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
  6825. if (!Subst) {
  6826. Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
  6827. ArgPack.pack_size(),
  6828. ArgPack.pack_begin());
  6829. SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
  6830. }
  6831. return TemplateName(Subst);
  6832. }
  6833. /// getFromTargetType - Given one of the integer types provided by
  6834. /// TargetInfo, produce the corresponding type. The unsigned @p Type
  6835. /// is actually a value of type @c TargetInfo::IntType.
  6836. CanQualType ASTContext::getFromTargetType(unsigned Type) const {
  6837. switch (Type) {
  6838. case TargetInfo::NoInt: return {};
  6839. case TargetInfo::SignedChar: return SignedCharTy;
  6840. case TargetInfo::UnsignedChar: return UnsignedCharTy;
  6841. case TargetInfo::SignedShort: return ShortTy;
  6842. case TargetInfo::UnsignedShort: return UnsignedShortTy;
  6843. case TargetInfo::SignedInt: return IntTy;
  6844. case TargetInfo::UnsignedInt: return UnsignedIntTy;
  6845. case TargetInfo::SignedLong: return LongTy;
  6846. case TargetInfo::UnsignedLong: return UnsignedLongTy;
  6847. case TargetInfo::SignedLongLong: return LongLongTy;
  6848. case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
  6849. }
  6850. llvm_unreachable("Unhandled TargetInfo::IntType value");
  6851. }
  6852. //===----------------------------------------------------------------------===//
  6853. // Type Predicates.
  6854. //===----------------------------------------------------------------------===//
  6855. /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
  6856. /// garbage collection attribute.
  6857. ///
  6858. Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
  6859. if (getLangOpts().getGC() == LangOptions::NonGC)
  6860. return Qualifiers::GCNone;
  6861. assert(getLangOpts().ObjC);
  6862. Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
  6863. // Default behaviour under objective-C's gc is for ObjC pointers
  6864. // (or pointers to them) be treated as though they were declared
  6865. // as __strong.
  6866. if (GCAttrs == Qualifiers::GCNone) {
  6867. if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
  6868. return Qualifiers::Strong;
  6869. else if (Ty->isPointerType())
  6870. return getObjCGCAttrKind(Ty->castAs<PointerType>()->getPointeeType());
  6871. } else {
  6872. // It's not valid to set GC attributes on anything that isn't a
  6873. // pointer.
  6874. #ifndef NDEBUG
  6875. QualType CT = Ty->getCanonicalTypeInternal();
  6876. while (const auto *AT = dyn_cast<ArrayType>(CT))
  6877. CT = AT->getElementType();
  6878. assert(CT->isAnyPointerType() || CT->isBlockPointerType());
  6879. #endif
  6880. }
  6881. return GCAttrs;
  6882. }
  6883. //===----------------------------------------------------------------------===//
  6884. // Type Compatibility Testing
  6885. //===----------------------------------------------------------------------===//
  6886. /// areCompatVectorTypes - Return true if the two specified vector types are
  6887. /// compatible.
  6888. static bool areCompatVectorTypes(const VectorType *LHS,
  6889. const VectorType *RHS) {
  6890. assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
  6891. return LHS->getElementType() == RHS->getElementType() &&
  6892. LHS->getNumElements() == RHS->getNumElements();
  6893. }
  6894. bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
  6895. QualType SecondVec) {
  6896. assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
  6897. assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
  6898. if (hasSameUnqualifiedType(FirstVec, SecondVec))
  6899. return true;
  6900. // Treat Neon vector types and most AltiVec vector types as if they are the
  6901. // equivalent GCC vector types.
  6902. const auto *First = FirstVec->castAs<VectorType>();
  6903. const auto *Second = SecondVec->castAs<VectorType>();
  6904. if (First->getNumElements() == Second->getNumElements() &&
  6905. hasSameType(First->getElementType(), Second->getElementType()) &&
  6906. First->getVectorKind() != VectorType::AltiVecPixel &&
  6907. First->getVectorKind() != VectorType::AltiVecBool &&
  6908. Second->getVectorKind() != VectorType::AltiVecPixel &&
  6909. Second->getVectorKind() != VectorType::AltiVecBool)
  6910. return true;
  6911. return false;
  6912. }
  6913. bool ASTContext::hasDirectOwnershipQualifier(QualType Ty) const {
  6914. while (true) {
  6915. // __strong id
  6916. if (const AttributedType *Attr = dyn_cast<AttributedType>(Ty)) {
  6917. if (Attr->getAttrKind() == attr::ObjCOwnership)
  6918. return true;
  6919. Ty = Attr->getModifiedType();
  6920. // X *__strong (...)
  6921. } else if (const ParenType *Paren = dyn_cast<ParenType>(Ty)) {
  6922. Ty = Paren->getInnerType();
  6923. // We do not want to look through typedefs, typeof(expr),
  6924. // typeof(type), or any other way that the type is somehow
  6925. // abstracted.
  6926. } else {
  6927. return false;
  6928. }
  6929. }
  6930. }
  6931. //===----------------------------------------------------------------------===//
  6932. // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
  6933. //===----------------------------------------------------------------------===//
  6934. /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
  6935. /// inheritance hierarchy of 'rProto'.
  6936. bool
  6937. ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  6938. ObjCProtocolDecl *rProto) const {
  6939. if (declaresSameEntity(lProto, rProto))
  6940. return true;
  6941. for (auto *PI : rProto->protocols())
  6942. if (ProtocolCompatibleWithProtocol(lProto, PI))
  6943. return true;
  6944. return false;
  6945. }
  6946. /// ObjCQualifiedClassTypesAreCompatible - compare Class<pr,...> and
  6947. /// Class<pr1, ...>.
  6948. bool ASTContext::ObjCQualifiedClassTypesAreCompatible(
  6949. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs) {
  6950. for (auto *lhsProto : lhs->quals()) {
  6951. bool match = false;
  6952. for (auto *rhsProto : rhs->quals()) {
  6953. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
  6954. match = true;
  6955. break;
  6956. }
  6957. }
  6958. if (!match)
  6959. return false;
  6960. }
  6961. return true;
  6962. }
  6963. /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
  6964. /// ObjCQualifiedIDType.
  6965. bool ASTContext::ObjCQualifiedIdTypesAreCompatible(
  6966. const ObjCObjectPointerType *lhs, const ObjCObjectPointerType *rhs,
  6967. bool compare) {
  6968. // Allow id<P..> and an 'id' or void* type in all cases.
  6969. if (lhs->isVoidPointerType() ||
  6970. lhs->isObjCIdType() || lhs->isObjCClassType())
  6971. return true;
  6972. else if (rhs->isVoidPointerType() ||
  6973. rhs->isObjCIdType() || rhs->isObjCClassType())
  6974. return true;
  6975. if (lhs->isObjCQualifiedIdType()) {
  6976. if (rhs->qual_empty()) {
  6977. // If the RHS is a unqualified interface pointer "NSString*",
  6978. // make sure we check the class hierarchy.
  6979. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  6980. for (auto *I : lhs->quals()) {
  6981. // when comparing an id<P> on lhs with a static type on rhs,
  6982. // see if static class implements all of id's protocols, directly or
  6983. // through its super class and categories.
  6984. if (!rhsID->ClassImplementsProtocol(I, true))
  6985. return false;
  6986. }
  6987. }
  6988. // If there are no qualifiers and no interface, we have an 'id'.
  6989. return true;
  6990. }
  6991. // Both the right and left sides have qualifiers.
  6992. for (auto *lhsProto : lhs->quals()) {
  6993. bool match = false;
  6994. // when comparing an id<P> on lhs with a static type on rhs,
  6995. // see if static class implements all of id's protocols, directly or
  6996. // through its super class and categories.
  6997. for (auto *rhsProto : rhs->quals()) {
  6998. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  6999. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  7000. match = true;
  7001. break;
  7002. }
  7003. }
  7004. // If the RHS is a qualified interface pointer "NSString<P>*",
  7005. // make sure we check the class hierarchy.
  7006. if (ObjCInterfaceDecl *rhsID = rhs->getInterfaceDecl()) {
  7007. for (auto *I : lhs->quals()) {
  7008. // when comparing an id<P> on lhs with a static type on rhs,
  7009. // see if static class implements all of id's protocols, directly or
  7010. // through its super class and categories.
  7011. if (rhsID->ClassImplementsProtocol(I, true)) {
  7012. match = true;
  7013. break;
  7014. }
  7015. }
  7016. }
  7017. if (!match)
  7018. return false;
  7019. }
  7020. return true;
  7021. }
  7022. assert(rhs->isObjCQualifiedIdType() && "One of the LHS/RHS should be id<x>");
  7023. if (lhs->getInterfaceType()) {
  7024. // If both the right and left sides have qualifiers.
  7025. for (auto *lhsProto : lhs->quals()) {
  7026. bool match = false;
  7027. // when comparing an id<P> on rhs with a static type on lhs,
  7028. // see if static class implements all of id's protocols, directly or
  7029. // through its super class and categories.
  7030. // First, lhs protocols in the qualifier list must be found, direct
  7031. // or indirect in rhs's qualifier list or it is a mismatch.
  7032. for (auto *rhsProto : rhs->quals()) {
  7033. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  7034. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  7035. match = true;
  7036. break;
  7037. }
  7038. }
  7039. if (!match)
  7040. return false;
  7041. }
  7042. // Static class's protocols, or its super class or category protocols
  7043. // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
  7044. if (ObjCInterfaceDecl *lhsID = lhs->getInterfaceDecl()) {
  7045. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
  7046. CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
  7047. // This is rather dubious but matches gcc's behavior. If lhs has
  7048. // no type qualifier and its class has no static protocol(s)
  7049. // assume that it is mismatch.
  7050. if (LHSInheritedProtocols.empty() && lhs->qual_empty())
  7051. return false;
  7052. for (auto *lhsProto : LHSInheritedProtocols) {
  7053. bool match = false;
  7054. for (auto *rhsProto : rhs->quals()) {
  7055. if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
  7056. (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
  7057. match = true;
  7058. break;
  7059. }
  7060. }
  7061. if (!match)
  7062. return false;
  7063. }
  7064. }
  7065. return true;
  7066. }
  7067. return false;
  7068. }
  7069. /// canAssignObjCInterfaces - Return true if the two interface types are
  7070. /// compatible for assignment from RHS to LHS. This handles validation of any
  7071. /// protocol qualifiers on the LHS or RHS.
  7072. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  7073. const ObjCObjectPointerType *RHSOPT) {
  7074. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  7075. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  7076. // If either type represents the built-in 'id' or 'Class' types, return true.
  7077. if (LHS->isObjCUnqualifiedIdOrClass() ||
  7078. RHS->isObjCUnqualifiedIdOrClass())
  7079. return true;
  7080. // Function object that propagates a successful result or handles
  7081. // __kindof types.
  7082. auto finish = [&](bool succeeded) -> bool {
  7083. if (succeeded)
  7084. return true;
  7085. if (!RHS->isKindOfType())
  7086. return false;
  7087. // Strip off __kindof and protocol qualifiers, then check whether
  7088. // we can assign the other way.
  7089. return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  7090. LHSOPT->stripObjCKindOfTypeAndQuals(*this));
  7091. };
  7092. if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
  7093. return finish(ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT, false));
  7094. }
  7095. if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
  7096. return finish(ObjCQualifiedClassTypesAreCompatible(LHSOPT, RHSOPT));
  7097. }
  7098. // If we have 2 user-defined types, fall into that path.
  7099. if (LHS->getInterface() && RHS->getInterface()) {
  7100. return finish(canAssignObjCInterfaces(LHS, RHS));
  7101. }
  7102. return false;
  7103. }
  7104. /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
  7105. /// for providing type-safety for objective-c pointers used to pass/return
  7106. /// arguments in block literals. When passed as arguments, passing 'A*' where
  7107. /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
  7108. /// not OK. For the return type, the opposite is not OK.
  7109. bool ASTContext::canAssignObjCInterfacesInBlockPointer(
  7110. const ObjCObjectPointerType *LHSOPT,
  7111. const ObjCObjectPointerType *RHSOPT,
  7112. bool BlockReturnType) {
  7113. // Function object that propagates a successful result or handles
  7114. // __kindof types.
  7115. auto finish = [&](bool succeeded) -> bool {
  7116. if (succeeded)
  7117. return true;
  7118. const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
  7119. if (!Expected->isKindOfType())
  7120. return false;
  7121. // Strip off __kindof and protocol qualifiers, then check whether
  7122. // we can assign the other way.
  7123. return canAssignObjCInterfacesInBlockPointer(
  7124. RHSOPT->stripObjCKindOfTypeAndQuals(*this),
  7125. LHSOPT->stripObjCKindOfTypeAndQuals(*this),
  7126. BlockReturnType);
  7127. };
  7128. if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
  7129. return true;
  7130. if (LHSOPT->isObjCBuiltinType()) {
  7131. return finish(RHSOPT->isObjCBuiltinType() ||
  7132. RHSOPT->isObjCQualifiedIdType());
  7133. }
  7134. if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
  7135. return finish(ObjCQualifiedIdTypesAreCompatible(
  7136. (BlockReturnType ? LHSOPT : RHSOPT),
  7137. (BlockReturnType ? RHSOPT : LHSOPT), false));
  7138. const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
  7139. const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
  7140. if (LHS && RHS) { // We have 2 user-defined types.
  7141. if (LHS != RHS) {
  7142. if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
  7143. return finish(BlockReturnType);
  7144. if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
  7145. return finish(!BlockReturnType);
  7146. }
  7147. else
  7148. return true;
  7149. }
  7150. return false;
  7151. }
  7152. /// Comparison routine for Objective-C protocols to be used with
  7153. /// llvm::array_pod_sort.
  7154. static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
  7155. ObjCProtocolDecl * const *rhs) {
  7156. return (*lhs)->getName().compare((*rhs)->getName());
  7157. }
  7158. /// getIntersectionOfProtocols - This routine finds the intersection of set
  7159. /// of protocols inherited from two distinct objective-c pointer objects with
  7160. /// the given common base.
  7161. /// It is used to build composite qualifier list of the composite type of
  7162. /// the conditional expression involving two objective-c pointer objects.
  7163. static
  7164. void getIntersectionOfProtocols(ASTContext &Context,
  7165. const ObjCInterfaceDecl *CommonBase,
  7166. const ObjCObjectPointerType *LHSOPT,
  7167. const ObjCObjectPointerType *RHSOPT,
  7168. SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
  7169. const ObjCObjectType* LHS = LHSOPT->getObjectType();
  7170. const ObjCObjectType* RHS = RHSOPT->getObjectType();
  7171. assert(LHS->getInterface() && "LHS must have an interface base");
  7172. assert(RHS->getInterface() && "RHS must have an interface base");
  7173. // Add all of the protocols for the LHS.
  7174. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
  7175. // Start with the protocol qualifiers.
  7176. for (auto proto : LHS->quals()) {
  7177. Context.CollectInheritedProtocols(proto, LHSProtocolSet);
  7178. }
  7179. // Also add the protocols associated with the LHS interface.
  7180. Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
  7181. // Add all of the protocols for the RHS.
  7182. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
  7183. // Start with the protocol qualifiers.
  7184. for (auto proto : RHS->quals()) {
  7185. Context.CollectInheritedProtocols(proto, RHSProtocolSet);
  7186. }
  7187. // Also add the protocols associated with the RHS interface.
  7188. Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
  7189. // Compute the intersection of the collected protocol sets.
  7190. for (auto proto : LHSProtocolSet) {
  7191. if (RHSProtocolSet.count(proto))
  7192. IntersectionSet.push_back(proto);
  7193. }
  7194. // Compute the set of protocols that is implied by either the common type or
  7195. // the protocols within the intersection.
  7196. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
  7197. Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
  7198. // Remove any implied protocols from the list of inherited protocols.
  7199. if (!ImpliedProtocols.empty()) {
  7200. IntersectionSet.erase(
  7201. std::remove_if(IntersectionSet.begin(),
  7202. IntersectionSet.end(),
  7203. [&](ObjCProtocolDecl *proto) -> bool {
  7204. return ImpliedProtocols.count(proto) > 0;
  7205. }),
  7206. IntersectionSet.end());
  7207. }
  7208. // Sort the remaining protocols by name.
  7209. llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
  7210. compareObjCProtocolsByName);
  7211. }
  7212. /// Determine whether the first type is a subtype of the second.
  7213. static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
  7214. QualType rhs) {
  7215. // Common case: two object pointers.
  7216. const auto *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
  7217. const auto *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
  7218. if (lhsOPT && rhsOPT)
  7219. return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
  7220. // Two block pointers.
  7221. const auto *lhsBlock = lhs->getAs<BlockPointerType>();
  7222. const auto *rhsBlock = rhs->getAs<BlockPointerType>();
  7223. if (lhsBlock && rhsBlock)
  7224. return ctx.typesAreBlockPointerCompatible(lhs, rhs);
  7225. // If either is an unqualified 'id' and the other is a block, it's
  7226. // acceptable.
  7227. if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
  7228. (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
  7229. return true;
  7230. return false;
  7231. }
  7232. // Check that the given Objective-C type argument lists are equivalent.
  7233. static bool sameObjCTypeArgs(ASTContext &ctx,
  7234. const ObjCInterfaceDecl *iface,
  7235. ArrayRef<QualType> lhsArgs,
  7236. ArrayRef<QualType> rhsArgs,
  7237. bool stripKindOf) {
  7238. if (lhsArgs.size() != rhsArgs.size())
  7239. return false;
  7240. ObjCTypeParamList *typeParams = iface->getTypeParamList();
  7241. for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
  7242. if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
  7243. continue;
  7244. switch (typeParams->begin()[i]->getVariance()) {
  7245. case ObjCTypeParamVariance::Invariant:
  7246. if (!stripKindOf ||
  7247. !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
  7248. rhsArgs[i].stripObjCKindOfType(ctx))) {
  7249. return false;
  7250. }
  7251. break;
  7252. case ObjCTypeParamVariance::Covariant:
  7253. if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
  7254. return false;
  7255. break;
  7256. case ObjCTypeParamVariance::Contravariant:
  7257. if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
  7258. return false;
  7259. break;
  7260. }
  7261. }
  7262. return true;
  7263. }
  7264. QualType ASTContext::areCommonBaseCompatible(
  7265. const ObjCObjectPointerType *Lptr,
  7266. const ObjCObjectPointerType *Rptr) {
  7267. const ObjCObjectType *LHS = Lptr->getObjectType();
  7268. const ObjCObjectType *RHS = Rptr->getObjectType();
  7269. const ObjCInterfaceDecl* LDecl = LHS->getInterface();
  7270. const ObjCInterfaceDecl* RDecl = RHS->getInterface();
  7271. if (!LDecl || !RDecl)
  7272. return {};
  7273. // When either LHS or RHS is a kindof type, we should return a kindof type.
  7274. // For example, for common base of kindof(ASub1) and kindof(ASub2), we return
  7275. // kindof(A).
  7276. bool anyKindOf = LHS->isKindOfType() || RHS->isKindOfType();
  7277. // Follow the left-hand side up the class hierarchy until we either hit a
  7278. // root or find the RHS. Record the ancestors in case we don't find it.
  7279. llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
  7280. LHSAncestors;
  7281. while (true) {
  7282. // Record this ancestor. We'll need this if the common type isn't in the
  7283. // path from the LHS to the root.
  7284. LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
  7285. if (declaresSameEntity(LHS->getInterface(), RDecl)) {
  7286. // Get the type arguments.
  7287. ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
  7288. bool anyChanges = false;
  7289. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  7290. // Both have type arguments, compare them.
  7291. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  7292. LHS->getTypeArgs(), RHS->getTypeArgs(),
  7293. /*stripKindOf=*/true))
  7294. return {};
  7295. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  7296. // If only one has type arguments, the result will not have type
  7297. // arguments.
  7298. LHSTypeArgs = {};
  7299. anyChanges = true;
  7300. }
  7301. // Compute the intersection of protocols.
  7302. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  7303. getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
  7304. Protocols);
  7305. if (!Protocols.empty())
  7306. anyChanges = true;
  7307. // If anything in the LHS will have changed, build a new result type.
  7308. // If we need to return a kindof type but LHS is not a kindof type, we
  7309. // build a new result type.
  7310. if (anyChanges || LHS->isKindOfType() != anyKindOf) {
  7311. QualType Result = getObjCInterfaceType(LHS->getInterface());
  7312. Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
  7313. anyKindOf || LHS->isKindOfType());
  7314. return getObjCObjectPointerType(Result);
  7315. }
  7316. return getObjCObjectPointerType(QualType(LHS, 0));
  7317. }
  7318. // Find the superclass.
  7319. QualType LHSSuperType = LHS->getSuperClassType();
  7320. if (LHSSuperType.isNull())
  7321. break;
  7322. LHS = LHSSuperType->castAs<ObjCObjectType>();
  7323. }
  7324. // We didn't find anything by following the LHS to its root; now check
  7325. // the RHS against the cached set of ancestors.
  7326. while (true) {
  7327. auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
  7328. if (KnownLHS != LHSAncestors.end()) {
  7329. LHS = KnownLHS->second;
  7330. // Get the type arguments.
  7331. ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
  7332. bool anyChanges = false;
  7333. if (LHS->isSpecialized() && RHS->isSpecialized()) {
  7334. // Both have type arguments, compare them.
  7335. if (!sameObjCTypeArgs(*this, LHS->getInterface(),
  7336. LHS->getTypeArgs(), RHS->getTypeArgs(),
  7337. /*stripKindOf=*/true))
  7338. return {};
  7339. } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
  7340. // If only one has type arguments, the result will not have type
  7341. // arguments.
  7342. RHSTypeArgs = {};
  7343. anyChanges = true;
  7344. }
  7345. // Compute the intersection of protocols.
  7346. SmallVector<ObjCProtocolDecl *, 8> Protocols;
  7347. getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
  7348. Protocols);
  7349. if (!Protocols.empty())
  7350. anyChanges = true;
  7351. // If we need to return a kindof type but RHS is not a kindof type, we
  7352. // build a new result type.
  7353. if (anyChanges || RHS->isKindOfType() != anyKindOf) {
  7354. QualType Result = getObjCInterfaceType(RHS->getInterface());
  7355. Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
  7356. anyKindOf || RHS->isKindOfType());
  7357. return getObjCObjectPointerType(Result);
  7358. }
  7359. return getObjCObjectPointerType(QualType(RHS, 0));
  7360. }
  7361. // Find the superclass of the RHS.
  7362. QualType RHSSuperType = RHS->getSuperClassType();
  7363. if (RHSSuperType.isNull())
  7364. break;
  7365. RHS = RHSSuperType->castAs<ObjCObjectType>();
  7366. }
  7367. return {};
  7368. }
  7369. bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
  7370. const ObjCObjectType *RHS) {
  7371. assert(LHS->getInterface() && "LHS is not an interface type");
  7372. assert(RHS->getInterface() && "RHS is not an interface type");
  7373. // Verify that the base decls are compatible: the RHS must be a subclass of
  7374. // the LHS.
  7375. ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
  7376. bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
  7377. if (!IsSuperClass)
  7378. return false;
  7379. // If the LHS has protocol qualifiers, determine whether all of them are
  7380. // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
  7381. // LHS).
  7382. if (LHS->getNumProtocols() > 0) {
  7383. // OK if conversion of LHS to SuperClass results in narrowing of types
  7384. // ; i.e., SuperClass may implement at least one of the protocols
  7385. // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
  7386. // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
  7387. llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
  7388. CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
  7389. // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
  7390. // qualifiers.
  7391. for (auto *RHSPI : RHS->quals())
  7392. CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
  7393. // If there is no protocols associated with RHS, it is not a match.
  7394. if (SuperClassInheritedProtocols.empty())
  7395. return false;
  7396. for (const auto *LHSProto : LHS->quals()) {
  7397. bool SuperImplementsProtocol = false;
  7398. for (auto *SuperClassProto : SuperClassInheritedProtocols)
  7399. if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
  7400. SuperImplementsProtocol = true;
  7401. break;
  7402. }
  7403. if (!SuperImplementsProtocol)
  7404. return false;
  7405. }
  7406. }
  7407. // If the LHS is specialized, we may need to check type arguments.
  7408. if (LHS->isSpecialized()) {
  7409. // Follow the superclass chain until we've matched the LHS class in the
  7410. // hierarchy. This substitutes type arguments through.
  7411. const ObjCObjectType *RHSSuper = RHS;
  7412. while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
  7413. RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
  7414. // If the RHS is specializd, compare type arguments.
  7415. if (RHSSuper->isSpecialized() &&
  7416. !sameObjCTypeArgs(*this, LHS->getInterface(),
  7417. LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
  7418. /*stripKindOf=*/true)) {
  7419. return false;
  7420. }
  7421. }
  7422. return true;
  7423. }
  7424. bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
  7425. // get the "pointed to" types
  7426. const auto *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
  7427. const auto *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
  7428. if (!LHSOPT || !RHSOPT)
  7429. return false;
  7430. return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
  7431. canAssignObjCInterfaces(RHSOPT, LHSOPT);
  7432. }
  7433. bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
  7434. return canAssignObjCInterfaces(
  7435. getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
  7436. getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
  7437. }
  7438. /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
  7439. /// both shall have the identically qualified version of a compatible type.
  7440. /// C99 6.2.7p1: Two types have compatible types if their types are the
  7441. /// same. See 6.7.[2,3,5] for additional rules.
  7442. bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
  7443. bool CompareUnqualified) {
  7444. if (getLangOpts().CPlusPlus)
  7445. return hasSameType(LHS, RHS);
  7446. return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
  7447. }
  7448. bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
  7449. return typesAreCompatible(LHS, RHS);
  7450. }
  7451. bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
  7452. return !mergeTypes(LHS, RHS, true).isNull();
  7453. }
  7454. /// mergeTransparentUnionType - if T is a transparent union type and a member
  7455. /// of T is compatible with SubType, return the merged type, else return
  7456. /// QualType()
  7457. QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
  7458. bool OfBlockPointer,
  7459. bool Unqualified) {
  7460. if (const RecordType *UT = T->getAsUnionType()) {
  7461. RecordDecl *UD = UT->getDecl();
  7462. if (UD->hasAttr<TransparentUnionAttr>()) {
  7463. for (const auto *I : UD->fields()) {
  7464. QualType ET = I->getType().getUnqualifiedType();
  7465. QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
  7466. if (!MT.isNull())
  7467. return MT;
  7468. }
  7469. }
  7470. }
  7471. return {};
  7472. }
  7473. /// mergeFunctionParameterTypes - merge two types which appear as function
  7474. /// parameter types
  7475. QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
  7476. bool OfBlockPointer,
  7477. bool Unqualified) {
  7478. // GNU extension: two types are compatible if they appear as a function
  7479. // argument, one of the types is a transparent union type and the other
  7480. // type is compatible with a union member
  7481. QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
  7482. Unqualified);
  7483. if (!lmerge.isNull())
  7484. return lmerge;
  7485. QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
  7486. Unqualified);
  7487. if (!rmerge.isNull())
  7488. return rmerge;
  7489. return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
  7490. }
  7491. QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
  7492. bool OfBlockPointer,
  7493. bool Unqualified) {
  7494. const auto *lbase = lhs->getAs<FunctionType>();
  7495. const auto *rbase = rhs->getAs<FunctionType>();
  7496. const auto *lproto = dyn_cast<FunctionProtoType>(lbase);
  7497. const auto *rproto = dyn_cast<FunctionProtoType>(rbase);
  7498. bool allLTypes = true;
  7499. bool allRTypes = true;
  7500. // Check return type
  7501. QualType retType;
  7502. if (OfBlockPointer) {
  7503. QualType RHS = rbase->getReturnType();
  7504. QualType LHS = lbase->getReturnType();
  7505. bool UnqualifiedResult = Unqualified;
  7506. if (!UnqualifiedResult)
  7507. UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
  7508. retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
  7509. }
  7510. else
  7511. retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
  7512. Unqualified);
  7513. if (retType.isNull())
  7514. return {};
  7515. if (Unqualified)
  7516. retType = retType.getUnqualifiedType();
  7517. CanQualType LRetType = getCanonicalType(lbase->getReturnType());
  7518. CanQualType RRetType = getCanonicalType(rbase->getReturnType());
  7519. if (Unqualified) {
  7520. LRetType = LRetType.getUnqualifiedType();
  7521. RRetType = RRetType.getUnqualifiedType();
  7522. }
  7523. if (getCanonicalType(retType) != LRetType)
  7524. allLTypes = false;
  7525. if (getCanonicalType(retType) != RRetType)
  7526. allRTypes = false;
  7527. // FIXME: double check this
  7528. // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
  7529. // rbase->getRegParmAttr() != 0 &&
  7530. // lbase->getRegParmAttr() != rbase->getRegParmAttr()?
  7531. FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
  7532. FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
  7533. // Compatible functions must have compatible calling conventions
  7534. if (lbaseInfo.getCC() != rbaseInfo.getCC())
  7535. return {};
  7536. // Regparm is part of the calling convention.
  7537. if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
  7538. return {};
  7539. if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
  7540. return {};
  7541. if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
  7542. return {};
  7543. if (lbaseInfo.getNoCallerSavedRegs() != rbaseInfo.getNoCallerSavedRegs())
  7544. return {};
  7545. if (lbaseInfo.getNoCfCheck() != rbaseInfo.getNoCfCheck())
  7546. return {};
  7547. // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
  7548. bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
  7549. if (lbaseInfo.getNoReturn() != NoReturn)
  7550. allLTypes = false;
  7551. if (rbaseInfo.getNoReturn() != NoReturn)
  7552. allRTypes = false;
  7553. FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
  7554. if (lproto && rproto) { // two C99 style function prototypes
  7555. assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
  7556. "C++ shouldn't be here");
  7557. // Compatible functions must have the same number of parameters
  7558. if (lproto->getNumParams() != rproto->getNumParams())
  7559. return {};
  7560. // Variadic and non-variadic functions aren't compatible
  7561. if (lproto->isVariadic() != rproto->isVariadic())
  7562. return {};
  7563. if (lproto->getMethodQuals() != rproto->getMethodQuals())
  7564. return {};
  7565. SmallVector<FunctionProtoType::ExtParameterInfo, 4> newParamInfos;
  7566. bool canUseLeft, canUseRight;
  7567. if (!mergeExtParameterInfo(lproto, rproto, canUseLeft, canUseRight,
  7568. newParamInfos))
  7569. return {};
  7570. if (!canUseLeft)
  7571. allLTypes = false;
  7572. if (!canUseRight)
  7573. allRTypes = false;
  7574. // Check parameter type compatibility
  7575. SmallVector<QualType, 10> types;
  7576. for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
  7577. QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
  7578. QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
  7579. QualType paramType = mergeFunctionParameterTypes(
  7580. lParamType, rParamType, OfBlockPointer, Unqualified);
  7581. if (paramType.isNull())
  7582. return {};
  7583. if (Unqualified)
  7584. paramType = paramType.getUnqualifiedType();
  7585. types.push_back(paramType);
  7586. if (Unqualified) {
  7587. lParamType = lParamType.getUnqualifiedType();
  7588. rParamType = rParamType.getUnqualifiedType();
  7589. }
  7590. if (getCanonicalType(paramType) != getCanonicalType(lParamType))
  7591. allLTypes = false;
  7592. if (getCanonicalType(paramType) != getCanonicalType(rParamType))
  7593. allRTypes = false;
  7594. }
  7595. if (allLTypes) return lhs;
  7596. if (allRTypes) return rhs;
  7597. FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
  7598. EPI.ExtInfo = einfo;
  7599. EPI.ExtParameterInfos =
  7600. newParamInfos.empty() ? nullptr : newParamInfos.data();
  7601. return getFunctionType(retType, types, EPI);
  7602. }
  7603. if (lproto) allRTypes = false;
  7604. if (rproto) allLTypes = false;
  7605. const FunctionProtoType *proto = lproto ? lproto : rproto;
  7606. if (proto) {
  7607. assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
  7608. if (proto->isVariadic())
  7609. return {};
  7610. // Check that the types are compatible with the types that
  7611. // would result from default argument promotions (C99 6.7.5.3p15).
  7612. // The only types actually affected are promotable integer
  7613. // types and floats, which would be passed as a different
  7614. // type depending on whether the prototype is visible.
  7615. for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
  7616. QualType paramTy = proto->getParamType(i);
  7617. // Look at the converted type of enum types, since that is the type used
  7618. // to pass enum values.
  7619. if (const auto *Enum = paramTy->getAs<EnumType>()) {
  7620. paramTy = Enum->getDecl()->getIntegerType();
  7621. if (paramTy.isNull())
  7622. return {};
  7623. }
  7624. if (paramTy->isPromotableIntegerType() ||
  7625. getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
  7626. return {};
  7627. }
  7628. if (allLTypes) return lhs;
  7629. if (allRTypes) return rhs;
  7630. FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
  7631. EPI.ExtInfo = einfo;
  7632. return getFunctionType(retType, proto->getParamTypes(), EPI);
  7633. }
  7634. if (allLTypes) return lhs;
  7635. if (allRTypes) return rhs;
  7636. return getFunctionNoProtoType(retType, einfo);
  7637. }
  7638. /// Given that we have an enum type and a non-enum type, try to merge them.
  7639. static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
  7640. QualType other, bool isBlockReturnType) {
  7641. // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
  7642. // a signed integer type, or an unsigned integer type.
  7643. // Compatibility is based on the underlying type, not the promotion
  7644. // type.
  7645. QualType underlyingType = ET->getDecl()->getIntegerType();
  7646. if (underlyingType.isNull())
  7647. return {};
  7648. if (Context.hasSameType(underlyingType, other))
  7649. return other;
  7650. // In block return types, we're more permissive and accept any
  7651. // integral type of the same size.
  7652. if (isBlockReturnType && other->isIntegerType() &&
  7653. Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
  7654. return other;
  7655. return {};
  7656. }
  7657. QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
  7658. bool OfBlockPointer,
  7659. bool Unqualified, bool BlockReturnType) {
  7660. // C++ [expr]: If an expression initially has the type "reference to T", the
  7661. // type is adjusted to "T" prior to any further analysis, the expression
  7662. // designates the object or function denoted by the reference, and the
  7663. // expression is an lvalue unless the reference is an rvalue reference and
  7664. // the expression is a function call (possibly inside parentheses).
  7665. assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
  7666. assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
  7667. if (Unqualified) {
  7668. LHS = LHS.getUnqualifiedType();
  7669. RHS = RHS.getUnqualifiedType();
  7670. }
  7671. QualType LHSCan = getCanonicalType(LHS),
  7672. RHSCan = getCanonicalType(RHS);
  7673. // If two types are identical, they are compatible.
  7674. if (LHSCan == RHSCan)
  7675. return LHS;
  7676. // If the qualifiers are different, the types aren't compatible... mostly.
  7677. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  7678. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  7679. if (LQuals != RQuals) {
  7680. // If any of these qualifiers are different, we have a type
  7681. // mismatch.
  7682. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  7683. LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
  7684. LQuals.getObjCLifetime() != RQuals.getObjCLifetime() ||
  7685. LQuals.hasUnaligned() != RQuals.hasUnaligned())
  7686. return {};
  7687. // Exactly one GC qualifier difference is allowed: __strong is
  7688. // okay if the other type has no GC qualifier but is an Objective
  7689. // C object pointer (i.e. implicitly strong by default). We fix
  7690. // this by pretending that the unqualified type was actually
  7691. // qualified __strong.
  7692. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  7693. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  7694. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  7695. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  7696. return {};
  7697. if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
  7698. return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
  7699. }
  7700. if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
  7701. return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
  7702. }
  7703. return {};
  7704. }
  7705. // Okay, qualifiers are equal.
  7706. Type::TypeClass LHSClass = LHSCan->getTypeClass();
  7707. Type::TypeClass RHSClass = RHSCan->getTypeClass();
  7708. // We want to consider the two function types to be the same for these
  7709. // comparisons, just force one to the other.
  7710. if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
  7711. if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
  7712. // Same as above for arrays
  7713. if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
  7714. LHSClass = Type::ConstantArray;
  7715. if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
  7716. RHSClass = Type::ConstantArray;
  7717. // ObjCInterfaces are just specialized ObjCObjects.
  7718. if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
  7719. if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
  7720. // Canonicalize ExtVector -> Vector.
  7721. if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
  7722. if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
  7723. // If the canonical type classes don't match.
  7724. if (LHSClass != RHSClass) {
  7725. // Note that we only have special rules for turning block enum
  7726. // returns into block int returns, not vice-versa.
  7727. if (const auto *ETy = LHS->getAs<EnumType>()) {
  7728. return mergeEnumWithInteger(*this, ETy, RHS, false);
  7729. }
  7730. if (const EnumType* ETy = RHS->getAs<EnumType>()) {
  7731. return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
  7732. }
  7733. // allow block pointer type to match an 'id' type.
  7734. if (OfBlockPointer && !BlockReturnType) {
  7735. if (LHS->isObjCIdType() && RHS->isBlockPointerType())
  7736. return LHS;
  7737. if (RHS->isObjCIdType() && LHS->isBlockPointerType())
  7738. return RHS;
  7739. }
  7740. return {};
  7741. }
  7742. // The canonical type classes match.
  7743. switch (LHSClass) {
  7744. #define TYPE(Class, Base)
  7745. #define ABSTRACT_TYPE(Class, Base)
  7746. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  7747. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  7748. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  7749. #include "clang/AST/TypeNodes.inc"
  7750. llvm_unreachable("Non-canonical and dependent types shouldn't get here");
  7751. case Type::Auto:
  7752. case Type::DeducedTemplateSpecialization:
  7753. case Type::LValueReference:
  7754. case Type::RValueReference:
  7755. case Type::MemberPointer:
  7756. llvm_unreachable("C++ should never be in mergeTypes");
  7757. case Type::ObjCInterface:
  7758. case Type::IncompleteArray:
  7759. case Type::VariableArray:
  7760. case Type::FunctionProto:
  7761. case Type::ExtVector:
  7762. llvm_unreachable("Types are eliminated above");
  7763. case Type::Pointer:
  7764. {
  7765. // Merge two pointer types, while trying to preserve typedef info
  7766. QualType LHSPointee = LHS->castAs<PointerType>()->getPointeeType();
  7767. QualType RHSPointee = RHS->castAs<PointerType>()->getPointeeType();
  7768. if (Unqualified) {
  7769. LHSPointee = LHSPointee.getUnqualifiedType();
  7770. RHSPointee = RHSPointee.getUnqualifiedType();
  7771. }
  7772. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
  7773. Unqualified);
  7774. if (ResultType.isNull())
  7775. return {};
  7776. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  7777. return LHS;
  7778. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  7779. return RHS;
  7780. return getPointerType(ResultType);
  7781. }
  7782. case Type::BlockPointer:
  7783. {
  7784. // Merge two block pointer types, while trying to preserve typedef info
  7785. QualType LHSPointee = LHS->castAs<BlockPointerType>()->getPointeeType();
  7786. QualType RHSPointee = RHS->castAs<BlockPointerType>()->getPointeeType();
  7787. if (Unqualified) {
  7788. LHSPointee = LHSPointee.getUnqualifiedType();
  7789. RHSPointee = RHSPointee.getUnqualifiedType();
  7790. }
  7791. if (getLangOpts().OpenCL) {
  7792. Qualifiers LHSPteeQual = LHSPointee.getQualifiers();
  7793. Qualifiers RHSPteeQual = RHSPointee.getQualifiers();
  7794. // Blocks can't be an expression in a ternary operator (OpenCL v2.0
  7795. // 6.12.5) thus the following check is asymmetric.
  7796. if (!LHSPteeQual.isAddressSpaceSupersetOf(RHSPteeQual))
  7797. return {};
  7798. LHSPteeQual.removeAddressSpace();
  7799. RHSPteeQual.removeAddressSpace();
  7800. LHSPointee =
  7801. QualType(LHSPointee.getTypePtr(), LHSPteeQual.getAsOpaqueValue());
  7802. RHSPointee =
  7803. QualType(RHSPointee.getTypePtr(), RHSPteeQual.getAsOpaqueValue());
  7804. }
  7805. QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
  7806. Unqualified);
  7807. if (ResultType.isNull())
  7808. return {};
  7809. if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
  7810. return LHS;
  7811. if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
  7812. return RHS;
  7813. return getBlockPointerType(ResultType);
  7814. }
  7815. case Type::Atomic:
  7816. {
  7817. // Merge two pointer types, while trying to preserve typedef info
  7818. QualType LHSValue = LHS->castAs<AtomicType>()->getValueType();
  7819. QualType RHSValue = RHS->castAs<AtomicType>()->getValueType();
  7820. if (Unqualified) {
  7821. LHSValue = LHSValue.getUnqualifiedType();
  7822. RHSValue = RHSValue.getUnqualifiedType();
  7823. }
  7824. QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
  7825. Unqualified);
  7826. if (ResultType.isNull())
  7827. return {};
  7828. if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
  7829. return LHS;
  7830. if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
  7831. return RHS;
  7832. return getAtomicType(ResultType);
  7833. }
  7834. case Type::ConstantArray:
  7835. {
  7836. const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
  7837. const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
  7838. if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
  7839. return {};
  7840. QualType LHSElem = getAsArrayType(LHS)->getElementType();
  7841. QualType RHSElem = getAsArrayType(RHS)->getElementType();
  7842. if (Unqualified) {
  7843. LHSElem = LHSElem.getUnqualifiedType();
  7844. RHSElem = RHSElem.getUnqualifiedType();
  7845. }
  7846. QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
  7847. if (ResultType.isNull())
  7848. return {};
  7849. const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
  7850. const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
  7851. // If either side is a variable array, and both are complete, check whether
  7852. // the current dimension is definite.
  7853. if (LVAT || RVAT) {
  7854. auto SizeFetch = [this](const VariableArrayType* VAT,
  7855. const ConstantArrayType* CAT)
  7856. -> std::pair<bool,llvm::APInt> {
  7857. if (VAT) {
  7858. llvm::APSInt TheInt;
  7859. Expr *E = VAT->getSizeExpr();
  7860. if (E && E->isIntegerConstantExpr(TheInt, *this))
  7861. return std::make_pair(true, TheInt);
  7862. else
  7863. return std::make_pair(false, TheInt);
  7864. } else if (CAT) {
  7865. return std::make_pair(true, CAT->getSize());
  7866. } else {
  7867. return std::make_pair(false, llvm::APInt());
  7868. }
  7869. };
  7870. bool HaveLSize, HaveRSize;
  7871. llvm::APInt LSize, RSize;
  7872. std::tie(HaveLSize, LSize) = SizeFetch(LVAT, LCAT);
  7873. std::tie(HaveRSize, RSize) = SizeFetch(RVAT, RCAT);
  7874. if (HaveLSize && HaveRSize && !llvm::APInt::isSameValue(LSize, RSize))
  7875. return {}; // Definite, but unequal, array dimension
  7876. }
  7877. if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  7878. return LHS;
  7879. if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  7880. return RHS;
  7881. if (LCAT)
  7882. return getConstantArrayType(ResultType, LCAT->getSize(),
  7883. LCAT->getSizeExpr(),
  7884. ArrayType::ArraySizeModifier(), 0);
  7885. if (RCAT)
  7886. return getConstantArrayType(ResultType, RCAT->getSize(),
  7887. RCAT->getSizeExpr(),
  7888. ArrayType::ArraySizeModifier(), 0);
  7889. if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
  7890. return LHS;
  7891. if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
  7892. return RHS;
  7893. if (LVAT) {
  7894. // FIXME: This isn't correct! But tricky to implement because
  7895. // the array's size has to be the size of LHS, but the type
  7896. // has to be different.
  7897. return LHS;
  7898. }
  7899. if (RVAT) {
  7900. // FIXME: This isn't correct! But tricky to implement because
  7901. // the array's size has to be the size of RHS, but the type
  7902. // has to be different.
  7903. return RHS;
  7904. }
  7905. if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
  7906. if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
  7907. return getIncompleteArrayType(ResultType,
  7908. ArrayType::ArraySizeModifier(), 0);
  7909. }
  7910. case Type::FunctionNoProto:
  7911. return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
  7912. case Type::Record:
  7913. case Type::Enum:
  7914. return {};
  7915. case Type::Builtin:
  7916. // Only exactly equal builtin types are compatible, which is tested above.
  7917. return {};
  7918. case Type::Complex:
  7919. // Distinct complex types are incompatible.
  7920. return {};
  7921. case Type::Vector:
  7922. // FIXME: The merged type should be an ExtVector!
  7923. if (areCompatVectorTypes(LHSCan->castAs<VectorType>(),
  7924. RHSCan->castAs<VectorType>()))
  7925. return LHS;
  7926. return {};
  7927. case Type::ObjCObject: {
  7928. // Check if the types are assignment compatible.
  7929. // FIXME: This should be type compatibility, e.g. whether
  7930. // "LHS x; RHS x;" at global scope is legal.
  7931. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectType>(),
  7932. RHS->castAs<ObjCObjectType>()))
  7933. return LHS;
  7934. return {};
  7935. }
  7936. case Type::ObjCObjectPointer:
  7937. if (OfBlockPointer) {
  7938. if (canAssignObjCInterfacesInBlockPointer(
  7939. LHS->castAs<ObjCObjectPointerType>(),
  7940. RHS->castAs<ObjCObjectPointerType>(), BlockReturnType))
  7941. return LHS;
  7942. return {};
  7943. }
  7944. if (canAssignObjCInterfaces(LHS->castAs<ObjCObjectPointerType>(),
  7945. RHS->castAs<ObjCObjectPointerType>()))
  7946. return LHS;
  7947. return {};
  7948. case Type::Pipe:
  7949. assert(LHS != RHS &&
  7950. "Equivalent pipe types should have already been handled!");
  7951. return {};
  7952. }
  7953. llvm_unreachable("Invalid Type::Class!");
  7954. }
  7955. bool ASTContext::mergeExtParameterInfo(
  7956. const FunctionProtoType *FirstFnType, const FunctionProtoType *SecondFnType,
  7957. bool &CanUseFirst, bool &CanUseSecond,
  7958. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos) {
  7959. assert(NewParamInfos.empty() && "param info list not empty");
  7960. CanUseFirst = CanUseSecond = true;
  7961. bool FirstHasInfo = FirstFnType->hasExtParameterInfos();
  7962. bool SecondHasInfo = SecondFnType->hasExtParameterInfos();
  7963. // Fast path: if the first type doesn't have ext parameter infos,
  7964. // we match if and only if the second type also doesn't have them.
  7965. if (!FirstHasInfo && !SecondHasInfo)
  7966. return true;
  7967. bool NeedParamInfo = false;
  7968. size_t E = FirstHasInfo ? FirstFnType->getExtParameterInfos().size()
  7969. : SecondFnType->getExtParameterInfos().size();
  7970. for (size_t I = 0; I < E; ++I) {
  7971. FunctionProtoType::ExtParameterInfo FirstParam, SecondParam;
  7972. if (FirstHasInfo)
  7973. FirstParam = FirstFnType->getExtParameterInfo(I);
  7974. if (SecondHasInfo)
  7975. SecondParam = SecondFnType->getExtParameterInfo(I);
  7976. // Cannot merge unless everything except the noescape flag matches.
  7977. if (FirstParam.withIsNoEscape(false) != SecondParam.withIsNoEscape(false))
  7978. return false;
  7979. bool FirstNoEscape = FirstParam.isNoEscape();
  7980. bool SecondNoEscape = SecondParam.isNoEscape();
  7981. bool IsNoEscape = FirstNoEscape && SecondNoEscape;
  7982. NewParamInfos.push_back(FirstParam.withIsNoEscape(IsNoEscape));
  7983. if (NewParamInfos.back().getOpaqueValue())
  7984. NeedParamInfo = true;
  7985. if (FirstNoEscape != IsNoEscape)
  7986. CanUseFirst = false;
  7987. if (SecondNoEscape != IsNoEscape)
  7988. CanUseSecond = false;
  7989. }
  7990. if (!NeedParamInfo)
  7991. NewParamInfos.clear();
  7992. return true;
  7993. }
  7994. void ASTContext::ResetObjCLayout(const ObjCContainerDecl *CD) {
  7995. ObjCLayouts[CD] = nullptr;
  7996. }
  7997. /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
  7998. /// 'RHS' attributes and returns the merged version; including for function
  7999. /// return types.
  8000. QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
  8001. QualType LHSCan = getCanonicalType(LHS),
  8002. RHSCan = getCanonicalType(RHS);
  8003. // If two types are identical, they are compatible.
  8004. if (LHSCan == RHSCan)
  8005. return LHS;
  8006. if (RHSCan->isFunctionType()) {
  8007. if (!LHSCan->isFunctionType())
  8008. return {};
  8009. QualType OldReturnType =
  8010. cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
  8011. QualType NewReturnType =
  8012. cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
  8013. QualType ResReturnType =
  8014. mergeObjCGCQualifiers(NewReturnType, OldReturnType);
  8015. if (ResReturnType.isNull())
  8016. return {};
  8017. if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
  8018. // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
  8019. // In either case, use OldReturnType to build the new function type.
  8020. const auto *F = LHS->castAs<FunctionType>();
  8021. if (const auto *FPT = cast<FunctionProtoType>(F)) {
  8022. FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
  8023. EPI.ExtInfo = getFunctionExtInfo(LHS);
  8024. QualType ResultType =
  8025. getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
  8026. return ResultType;
  8027. }
  8028. }
  8029. return {};
  8030. }
  8031. // If the qualifiers are different, the types can still be merged.
  8032. Qualifiers LQuals = LHSCan.getLocalQualifiers();
  8033. Qualifiers RQuals = RHSCan.getLocalQualifiers();
  8034. if (LQuals != RQuals) {
  8035. // If any of these qualifiers are different, we have a type mismatch.
  8036. if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
  8037. LQuals.getAddressSpace() != RQuals.getAddressSpace())
  8038. return {};
  8039. // Exactly one GC qualifier difference is allowed: __strong is
  8040. // okay if the other type has no GC qualifier but is an Objective
  8041. // C object pointer (i.e. implicitly strong by default). We fix
  8042. // this by pretending that the unqualified type was actually
  8043. // qualified __strong.
  8044. Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
  8045. Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
  8046. assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
  8047. if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
  8048. return {};
  8049. if (GC_L == Qualifiers::Strong)
  8050. return LHS;
  8051. if (GC_R == Qualifiers::Strong)
  8052. return RHS;
  8053. return {};
  8054. }
  8055. if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
  8056. QualType LHSBaseQT = LHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  8057. QualType RHSBaseQT = RHS->castAs<ObjCObjectPointerType>()->getPointeeType();
  8058. QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
  8059. if (ResQT == LHSBaseQT)
  8060. return LHS;
  8061. if (ResQT == RHSBaseQT)
  8062. return RHS;
  8063. }
  8064. return {};
  8065. }
  8066. //===----------------------------------------------------------------------===//
  8067. // Integer Predicates
  8068. //===----------------------------------------------------------------------===//
  8069. unsigned ASTContext::getIntWidth(QualType T) const {
  8070. if (const auto *ET = T->getAs<EnumType>())
  8071. T = ET->getDecl()->getIntegerType();
  8072. if (T->isBooleanType())
  8073. return 1;
  8074. // For builtin types, just use the standard type sizing method
  8075. return (unsigned)getTypeSize(T);
  8076. }
  8077. QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
  8078. assert((T->hasSignedIntegerRepresentation() || T->isSignedFixedPointType()) &&
  8079. "Unexpected type");
  8080. // Turn <4 x signed int> -> <4 x unsigned int>
  8081. if (const auto *VTy = T->getAs<VectorType>())
  8082. return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
  8083. VTy->getNumElements(), VTy->getVectorKind());
  8084. // For enums, we return the unsigned version of the base type.
  8085. if (const auto *ETy = T->getAs<EnumType>())
  8086. T = ETy->getDecl()->getIntegerType();
  8087. switch (T->castAs<BuiltinType>()->getKind()) {
  8088. case BuiltinType::Char_S:
  8089. case BuiltinType::SChar:
  8090. return UnsignedCharTy;
  8091. case BuiltinType::Short:
  8092. return UnsignedShortTy;
  8093. case BuiltinType::Int:
  8094. return UnsignedIntTy;
  8095. case BuiltinType::Long:
  8096. return UnsignedLongTy;
  8097. case BuiltinType::LongLong:
  8098. return UnsignedLongLongTy;
  8099. case BuiltinType::Int128:
  8100. return UnsignedInt128Ty;
  8101. case BuiltinType::ShortAccum:
  8102. return UnsignedShortAccumTy;
  8103. case BuiltinType::Accum:
  8104. return UnsignedAccumTy;
  8105. case BuiltinType::LongAccum:
  8106. return UnsignedLongAccumTy;
  8107. case BuiltinType::SatShortAccum:
  8108. return SatUnsignedShortAccumTy;
  8109. case BuiltinType::SatAccum:
  8110. return SatUnsignedAccumTy;
  8111. case BuiltinType::SatLongAccum:
  8112. return SatUnsignedLongAccumTy;
  8113. case BuiltinType::ShortFract:
  8114. return UnsignedShortFractTy;
  8115. case BuiltinType::Fract:
  8116. return UnsignedFractTy;
  8117. case BuiltinType::LongFract:
  8118. return UnsignedLongFractTy;
  8119. case BuiltinType::SatShortFract:
  8120. return SatUnsignedShortFractTy;
  8121. case BuiltinType::SatFract:
  8122. return SatUnsignedFractTy;
  8123. case BuiltinType::SatLongFract:
  8124. return SatUnsignedLongFractTy;
  8125. default:
  8126. llvm_unreachable("Unexpected signed integer or fixed point type");
  8127. }
  8128. }
  8129. ASTMutationListener::~ASTMutationListener() = default;
  8130. void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
  8131. QualType ReturnType) {}
  8132. //===----------------------------------------------------------------------===//
  8133. // Builtin Type Computation
  8134. //===----------------------------------------------------------------------===//
  8135. /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
  8136. /// pointer over the consumed characters. This returns the resultant type. If
  8137. /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
  8138. /// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of
  8139. /// a vector of "i*".
  8140. ///
  8141. /// RequiresICE is filled in on return to indicate whether the value is required
  8142. /// to be an Integer Constant Expression.
  8143. static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
  8144. ASTContext::GetBuiltinTypeError &Error,
  8145. bool &RequiresICE,
  8146. bool AllowTypeModifiers) {
  8147. // Modifiers.
  8148. int HowLong = 0;
  8149. bool Signed = false, Unsigned = false;
  8150. RequiresICE = false;
  8151. // Read the prefixed modifiers first.
  8152. bool Done = false;
  8153. #ifndef NDEBUG
  8154. bool IsSpecial = false;
  8155. #endif
  8156. while (!Done) {
  8157. switch (*Str++) {
  8158. default: Done = true; --Str; break;
  8159. case 'I':
  8160. RequiresICE = true;
  8161. break;
  8162. case 'S':
  8163. assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
  8164. assert(!Signed && "Can't use 'S' modifier multiple times!");
  8165. Signed = true;
  8166. break;
  8167. case 'U':
  8168. assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
  8169. assert(!Unsigned && "Can't use 'U' modifier multiple times!");
  8170. Unsigned = true;
  8171. break;
  8172. case 'L':
  8173. assert(!IsSpecial && "Can't use 'L' with 'W', 'N', 'Z' or 'O' modifiers");
  8174. assert(HowLong <= 2 && "Can't have LLLL modifier");
  8175. ++HowLong;
  8176. break;
  8177. case 'N':
  8178. // 'N' behaves like 'L' for all non LP64 targets and 'int' otherwise.
  8179. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  8180. assert(HowLong == 0 && "Can't use both 'L' and 'N' modifiers!");
  8181. #ifndef NDEBUG
  8182. IsSpecial = true;
  8183. #endif
  8184. if (Context.getTargetInfo().getLongWidth() == 32)
  8185. ++HowLong;
  8186. break;
  8187. case 'W':
  8188. // This modifier represents int64 type.
  8189. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  8190. assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
  8191. #ifndef NDEBUG
  8192. IsSpecial = true;
  8193. #endif
  8194. switch (Context.getTargetInfo().getInt64Type()) {
  8195. default:
  8196. llvm_unreachable("Unexpected integer type");
  8197. case TargetInfo::SignedLong:
  8198. HowLong = 1;
  8199. break;
  8200. case TargetInfo::SignedLongLong:
  8201. HowLong = 2;
  8202. break;
  8203. }
  8204. break;
  8205. case 'Z':
  8206. // This modifier represents int32 type.
  8207. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  8208. assert(HowLong == 0 && "Can't use both 'L' and 'Z' modifiers!");
  8209. #ifndef NDEBUG
  8210. IsSpecial = true;
  8211. #endif
  8212. switch (Context.getTargetInfo().getIntTypeByWidth(32, true)) {
  8213. default:
  8214. llvm_unreachable("Unexpected integer type");
  8215. case TargetInfo::SignedInt:
  8216. HowLong = 0;
  8217. break;
  8218. case TargetInfo::SignedLong:
  8219. HowLong = 1;
  8220. break;
  8221. case TargetInfo::SignedLongLong:
  8222. HowLong = 2;
  8223. break;
  8224. }
  8225. break;
  8226. case 'O':
  8227. assert(!IsSpecial && "Can't use two 'N', 'W', 'Z' or 'O' modifiers!");
  8228. assert(HowLong == 0 && "Can't use both 'L' and 'O' modifiers!");
  8229. #ifndef NDEBUG
  8230. IsSpecial = true;
  8231. #endif
  8232. if (Context.getLangOpts().OpenCL)
  8233. HowLong = 1;
  8234. else
  8235. HowLong = 2;
  8236. break;
  8237. }
  8238. }
  8239. QualType Type;
  8240. // Read the base type.
  8241. switch (*Str++) {
  8242. default: llvm_unreachable("Unknown builtin type letter!");
  8243. case 'v':
  8244. assert(HowLong == 0 && !Signed && !Unsigned &&
  8245. "Bad modifiers used with 'v'!");
  8246. Type = Context.VoidTy;
  8247. break;
  8248. case 'h':
  8249. assert(HowLong == 0 && !Signed && !Unsigned &&
  8250. "Bad modifiers used with 'h'!");
  8251. Type = Context.HalfTy;
  8252. break;
  8253. case 'f':
  8254. assert(HowLong == 0 && !Signed && !Unsigned &&
  8255. "Bad modifiers used with 'f'!");
  8256. Type = Context.FloatTy;
  8257. break;
  8258. case 'd':
  8259. assert(HowLong < 3 && !Signed && !Unsigned &&
  8260. "Bad modifiers used with 'd'!");
  8261. if (HowLong == 1)
  8262. Type = Context.LongDoubleTy;
  8263. else if (HowLong == 2)
  8264. Type = Context.Float128Ty;
  8265. else
  8266. Type = Context.DoubleTy;
  8267. break;
  8268. case 's':
  8269. assert(HowLong == 0 && "Bad modifiers used with 's'!");
  8270. if (Unsigned)
  8271. Type = Context.UnsignedShortTy;
  8272. else
  8273. Type = Context.ShortTy;
  8274. break;
  8275. case 'i':
  8276. if (HowLong == 3)
  8277. Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
  8278. else if (HowLong == 2)
  8279. Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
  8280. else if (HowLong == 1)
  8281. Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
  8282. else
  8283. Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
  8284. break;
  8285. case 'c':
  8286. assert(HowLong == 0 && "Bad modifiers used with 'c'!");
  8287. if (Signed)
  8288. Type = Context.SignedCharTy;
  8289. else if (Unsigned)
  8290. Type = Context.UnsignedCharTy;
  8291. else
  8292. Type = Context.CharTy;
  8293. break;
  8294. case 'b': // boolean
  8295. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
  8296. Type = Context.BoolTy;
  8297. break;
  8298. case 'z': // size_t.
  8299. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
  8300. Type = Context.getSizeType();
  8301. break;
  8302. case 'w': // wchar_t.
  8303. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'w'!");
  8304. Type = Context.getWideCharType();
  8305. break;
  8306. case 'F':
  8307. Type = Context.getCFConstantStringType();
  8308. break;
  8309. case 'G':
  8310. Type = Context.getObjCIdType();
  8311. break;
  8312. case 'H':
  8313. Type = Context.getObjCSelType();
  8314. break;
  8315. case 'M':
  8316. Type = Context.getObjCSuperType();
  8317. break;
  8318. case 'a':
  8319. Type = Context.getBuiltinVaListType();
  8320. assert(!Type.isNull() && "builtin va list type not initialized!");
  8321. break;
  8322. case 'A':
  8323. // This is a "reference" to a va_list; however, what exactly
  8324. // this means depends on how va_list is defined. There are two
  8325. // different kinds of va_list: ones passed by value, and ones
  8326. // passed by reference. An example of a by-value va_list is
  8327. // x86, where va_list is a char*. An example of by-ref va_list
  8328. // is x86-64, where va_list is a __va_list_tag[1]. For x86,
  8329. // we want this argument to be a char*&; for x86-64, we want
  8330. // it to be a __va_list_tag*.
  8331. Type = Context.getBuiltinVaListType();
  8332. assert(!Type.isNull() && "builtin va list type not initialized!");
  8333. if (Type->isArrayType())
  8334. Type = Context.getArrayDecayedType(Type);
  8335. else
  8336. Type = Context.getLValueReferenceType(Type);
  8337. break;
  8338. case 'V': {
  8339. char *End;
  8340. unsigned NumElements = strtoul(Str, &End, 10);
  8341. assert(End != Str && "Missing vector size");
  8342. Str = End;
  8343. QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
  8344. RequiresICE, false);
  8345. assert(!RequiresICE && "Can't require vector ICE");
  8346. // TODO: No way to make AltiVec vectors in builtins yet.
  8347. Type = Context.getVectorType(ElementType, NumElements,
  8348. VectorType::GenericVector);
  8349. break;
  8350. }
  8351. case 'E': {
  8352. char *End;
  8353. unsigned NumElements = strtoul(Str, &End, 10);
  8354. assert(End != Str && "Missing vector size");
  8355. Str = End;
  8356. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  8357. false);
  8358. Type = Context.getExtVectorType(ElementType, NumElements);
  8359. break;
  8360. }
  8361. case 'X': {
  8362. QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
  8363. false);
  8364. assert(!RequiresICE && "Can't require complex ICE");
  8365. Type = Context.getComplexType(ElementType);
  8366. break;
  8367. }
  8368. case 'Y':
  8369. Type = Context.getPointerDiffType();
  8370. break;
  8371. case 'P':
  8372. Type = Context.getFILEType();
  8373. if (Type.isNull()) {
  8374. Error = ASTContext::GE_Missing_stdio;
  8375. return {};
  8376. }
  8377. break;
  8378. case 'J':
  8379. if (Signed)
  8380. Type = Context.getsigjmp_bufType();
  8381. else
  8382. Type = Context.getjmp_bufType();
  8383. if (Type.isNull()) {
  8384. Error = ASTContext::GE_Missing_setjmp;
  8385. return {};
  8386. }
  8387. break;
  8388. case 'K':
  8389. assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
  8390. Type = Context.getucontext_tType();
  8391. if (Type.isNull()) {
  8392. Error = ASTContext::GE_Missing_ucontext;
  8393. return {};
  8394. }
  8395. break;
  8396. case 'p':
  8397. Type = Context.getProcessIDType();
  8398. break;
  8399. }
  8400. // If there are modifiers and if we're allowed to parse them, go for it.
  8401. Done = !AllowTypeModifiers;
  8402. while (!Done) {
  8403. switch (char c = *Str++) {
  8404. default: Done = true; --Str; break;
  8405. case '*':
  8406. case '&': {
  8407. // Both pointers and references can have their pointee types
  8408. // qualified with an address space.
  8409. char *End;
  8410. unsigned AddrSpace = strtoul(Str, &End, 10);
  8411. if (End != Str) {
  8412. // Note AddrSpace == 0 is not the same as an unspecified address space.
  8413. Type = Context.getAddrSpaceQualType(
  8414. Type,
  8415. Context.getLangASForBuiltinAddressSpace(AddrSpace));
  8416. Str = End;
  8417. }
  8418. if (c == '*')
  8419. Type = Context.getPointerType(Type);
  8420. else
  8421. Type = Context.getLValueReferenceType(Type);
  8422. break;
  8423. }
  8424. // FIXME: There's no way to have a built-in with an rvalue ref arg.
  8425. case 'C':
  8426. Type = Type.withConst();
  8427. break;
  8428. case 'D':
  8429. Type = Context.getVolatileType(Type);
  8430. break;
  8431. case 'R':
  8432. Type = Type.withRestrict();
  8433. break;
  8434. }
  8435. }
  8436. assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
  8437. "Integer constant 'I' type must be an integer");
  8438. return Type;
  8439. }
  8440. /// GetBuiltinType - Return the type for the specified builtin.
  8441. QualType ASTContext::GetBuiltinType(unsigned Id,
  8442. GetBuiltinTypeError &Error,
  8443. unsigned *IntegerConstantArgs) const {
  8444. const char *TypeStr = BuiltinInfo.getTypeString(Id);
  8445. if (TypeStr[0] == '\0') {
  8446. Error = GE_Missing_type;
  8447. return {};
  8448. }
  8449. SmallVector<QualType, 8> ArgTypes;
  8450. bool RequiresICE = false;
  8451. Error = GE_None;
  8452. QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
  8453. RequiresICE, true);
  8454. if (Error != GE_None)
  8455. return {};
  8456. assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
  8457. while (TypeStr[0] && TypeStr[0] != '.') {
  8458. QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
  8459. if (Error != GE_None)
  8460. return {};
  8461. // If this argument is required to be an IntegerConstantExpression and the
  8462. // caller cares, fill in the bitmask we return.
  8463. if (RequiresICE && IntegerConstantArgs)
  8464. *IntegerConstantArgs |= 1 << ArgTypes.size();
  8465. // Do array -> pointer decay. The builtin should use the decayed type.
  8466. if (Ty->isArrayType())
  8467. Ty = getArrayDecayedType(Ty);
  8468. ArgTypes.push_back(Ty);
  8469. }
  8470. if (Id == Builtin::BI__GetExceptionInfo)
  8471. return {};
  8472. assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
  8473. "'.' should only occur at end of builtin type list!");
  8474. bool Variadic = (TypeStr[0] == '.');
  8475. FunctionType::ExtInfo EI(getDefaultCallingConvention(
  8476. Variadic, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
  8477. if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
  8478. // We really shouldn't be making a no-proto type here.
  8479. if (ArgTypes.empty() && Variadic && !getLangOpts().CPlusPlus)
  8480. return getFunctionNoProtoType(ResType, EI);
  8481. FunctionProtoType::ExtProtoInfo EPI;
  8482. EPI.ExtInfo = EI;
  8483. EPI.Variadic = Variadic;
  8484. if (getLangOpts().CPlusPlus && BuiltinInfo.isNoThrow(Id))
  8485. EPI.ExceptionSpec.Type =
  8486. getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
  8487. return getFunctionType(ResType, ArgTypes, EPI);
  8488. }
  8489. static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
  8490. const FunctionDecl *FD) {
  8491. if (!FD->isExternallyVisible())
  8492. return GVA_Internal;
  8493. // Non-user-provided functions get emitted as weak definitions with every
  8494. // use, no matter whether they've been explicitly instantiated etc.
  8495. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
  8496. if (!MD->isUserProvided())
  8497. return GVA_DiscardableODR;
  8498. GVALinkage External;
  8499. switch (FD->getTemplateSpecializationKind()) {
  8500. case TSK_Undeclared:
  8501. case TSK_ExplicitSpecialization:
  8502. External = GVA_StrongExternal;
  8503. break;
  8504. case TSK_ExplicitInstantiationDefinition:
  8505. return GVA_StrongODR;
  8506. // C++11 [temp.explicit]p10:
  8507. // [ Note: The intent is that an inline function that is the subject of
  8508. // an explicit instantiation declaration will still be implicitly
  8509. // instantiated when used so that the body can be considered for
  8510. // inlining, but that no out-of-line copy of the inline function would be
  8511. // generated in the translation unit. -- end note ]
  8512. case TSK_ExplicitInstantiationDeclaration:
  8513. return GVA_AvailableExternally;
  8514. case TSK_ImplicitInstantiation:
  8515. External = GVA_DiscardableODR;
  8516. break;
  8517. }
  8518. if (!FD->isInlined())
  8519. return External;
  8520. if ((!Context.getLangOpts().CPlusPlus &&
  8521. !Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  8522. !FD->hasAttr<DLLExportAttr>()) ||
  8523. FD->hasAttr<GNUInlineAttr>()) {
  8524. // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
  8525. // GNU or C99 inline semantics. Determine whether this symbol should be
  8526. // externally visible.
  8527. if (FD->isInlineDefinitionExternallyVisible())
  8528. return External;
  8529. // C99 inline semantics, where the symbol is not externally visible.
  8530. return GVA_AvailableExternally;
  8531. }
  8532. // Functions specified with extern and inline in -fms-compatibility mode
  8533. // forcibly get emitted. While the body of the function cannot be later
  8534. // replaced, the function definition cannot be discarded.
  8535. if (FD->isMSExternInline())
  8536. return GVA_StrongODR;
  8537. return GVA_DiscardableODR;
  8538. }
  8539. static GVALinkage adjustGVALinkageForAttributes(const ASTContext &Context,
  8540. const Decl *D, GVALinkage L) {
  8541. // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
  8542. // dllexport/dllimport on inline functions.
  8543. if (D->hasAttr<DLLImportAttr>()) {
  8544. if (L == GVA_DiscardableODR || L == GVA_StrongODR)
  8545. return GVA_AvailableExternally;
  8546. } else if (D->hasAttr<DLLExportAttr>()) {
  8547. if (L == GVA_DiscardableODR)
  8548. return GVA_StrongODR;
  8549. } else if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice &&
  8550. D->hasAttr<CUDAGlobalAttr>()) {
  8551. // Device-side functions with __global__ attribute must always be
  8552. // visible externally so they can be launched from host.
  8553. if (L == GVA_DiscardableODR || L == GVA_Internal)
  8554. return GVA_StrongODR;
  8555. }
  8556. return L;
  8557. }
  8558. /// Adjust the GVALinkage for a declaration based on what an external AST source
  8559. /// knows about whether there can be other definitions of this declaration.
  8560. static GVALinkage
  8561. adjustGVALinkageForExternalDefinitionKind(const ASTContext &Ctx, const Decl *D,
  8562. GVALinkage L) {
  8563. ExternalASTSource *Source = Ctx.getExternalSource();
  8564. if (!Source)
  8565. return L;
  8566. switch (Source->hasExternalDefinitions(D)) {
  8567. case ExternalASTSource::EK_Never:
  8568. // Other translation units rely on us to provide the definition.
  8569. if (L == GVA_DiscardableODR)
  8570. return GVA_StrongODR;
  8571. break;
  8572. case ExternalASTSource::EK_Always:
  8573. return GVA_AvailableExternally;
  8574. case ExternalASTSource::EK_ReplyHazy:
  8575. break;
  8576. }
  8577. return L;
  8578. }
  8579. GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
  8580. return adjustGVALinkageForExternalDefinitionKind(*this, FD,
  8581. adjustGVALinkageForAttributes(*this, FD,
  8582. basicGVALinkageForFunction(*this, FD)));
  8583. }
  8584. static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
  8585. const VarDecl *VD) {
  8586. if (!VD->isExternallyVisible())
  8587. return GVA_Internal;
  8588. if (VD->isStaticLocal()) {
  8589. const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
  8590. while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
  8591. LexicalContext = LexicalContext->getLexicalParent();
  8592. // ObjC Blocks can create local variables that don't have a FunctionDecl
  8593. // LexicalContext.
  8594. if (!LexicalContext)
  8595. return GVA_DiscardableODR;
  8596. // Otherwise, let the static local variable inherit its linkage from the
  8597. // nearest enclosing function.
  8598. auto StaticLocalLinkage =
  8599. Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
  8600. // Itanium ABI 5.2.2: "Each COMDAT group [for a static local variable] must
  8601. // be emitted in any object with references to the symbol for the object it
  8602. // contains, whether inline or out-of-line."
  8603. // Similar behavior is observed with MSVC. An alternative ABI could use
  8604. // StrongODR/AvailableExternally to match the function, but none are
  8605. // known/supported currently.
  8606. if (StaticLocalLinkage == GVA_StrongODR ||
  8607. StaticLocalLinkage == GVA_AvailableExternally)
  8608. return GVA_DiscardableODR;
  8609. return StaticLocalLinkage;
  8610. }
  8611. // MSVC treats in-class initialized static data members as definitions.
  8612. // By giving them non-strong linkage, out-of-line definitions won't
  8613. // cause link errors.
  8614. if (Context.isMSStaticDataMemberInlineDefinition(VD))
  8615. return GVA_DiscardableODR;
  8616. // Most non-template variables have strong linkage; inline variables are
  8617. // linkonce_odr or (occasionally, for compatibility) weak_odr.
  8618. GVALinkage StrongLinkage;
  8619. switch (Context.getInlineVariableDefinitionKind(VD)) {
  8620. case ASTContext::InlineVariableDefinitionKind::None:
  8621. StrongLinkage = GVA_StrongExternal;
  8622. break;
  8623. case ASTContext::InlineVariableDefinitionKind::Weak:
  8624. case ASTContext::InlineVariableDefinitionKind::WeakUnknown:
  8625. StrongLinkage = GVA_DiscardableODR;
  8626. break;
  8627. case ASTContext::InlineVariableDefinitionKind::Strong:
  8628. StrongLinkage = GVA_StrongODR;
  8629. break;
  8630. }
  8631. switch (VD->getTemplateSpecializationKind()) {
  8632. case TSK_Undeclared:
  8633. return StrongLinkage;
  8634. case TSK_ExplicitSpecialization:
  8635. return Context.getTargetInfo().getCXXABI().isMicrosoft() &&
  8636. VD->isStaticDataMember()
  8637. ? GVA_StrongODR
  8638. : StrongLinkage;
  8639. case TSK_ExplicitInstantiationDefinition:
  8640. return GVA_StrongODR;
  8641. case TSK_ExplicitInstantiationDeclaration:
  8642. return GVA_AvailableExternally;
  8643. case TSK_ImplicitInstantiation:
  8644. return GVA_DiscardableODR;
  8645. }
  8646. llvm_unreachable("Invalid Linkage!");
  8647. }
  8648. GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
  8649. return adjustGVALinkageForExternalDefinitionKind(*this, VD,
  8650. adjustGVALinkageForAttributes(*this, VD,
  8651. basicGVALinkageForVariable(*this, VD)));
  8652. }
  8653. bool ASTContext::DeclMustBeEmitted(const Decl *D) {
  8654. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  8655. if (!VD->isFileVarDecl())
  8656. return false;
  8657. // Global named register variables (GNU extension) are never emitted.
  8658. if (VD->getStorageClass() == SC_Register)
  8659. return false;
  8660. if (VD->getDescribedVarTemplate() ||
  8661. isa<VarTemplatePartialSpecializationDecl>(VD))
  8662. return false;
  8663. } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  8664. // We never need to emit an uninstantiated function template.
  8665. if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
  8666. return false;
  8667. } else if (isa<PragmaCommentDecl>(D))
  8668. return true;
  8669. else if (isa<PragmaDetectMismatchDecl>(D))
  8670. return true;
  8671. else if (isa<OMPThreadPrivateDecl>(D))
  8672. return !D->getDeclContext()->isDependentContext();
  8673. else if (isa<OMPAllocateDecl>(D))
  8674. return !D->getDeclContext()->isDependentContext();
  8675. else if (isa<OMPDeclareReductionDecl>(D) || isa<OMPDeclareMapperDecl>(D))
  8676. return !D->getDeclContext()->isDependentContext();
  8677. else if (isa<ImportDecl>(D))
  8678. return true;
  8679. else
  8680. return false;
  8681. if (D->isFromASTFile() && !LangOpts.BuildingPCHWithObjectFile) {
  8682. assert(getExternalSource() && "It's from an AST file; must have a source.");
  8683. // On Windows, PCH files are built together with an object file. If this
  8684. // declaration comes from such a PCH and DeclMustBeEmitted would return
  8685. // true, it would have returned true and the decl would have been emitted
  8686. // into that object file, so it doesn't need to be emitted here.
  8687. // Note that decls are still emitted if they're referenced, as usual;
  8688. // DeclMustBeEmitted is used to decide whether a decl must be emitted even
  8689. // if it's not referenced.
  8690. //
  8691. // Explicit template instantiation definitions are tricky. If there was an
  8692. // explicit template instantiation decl in the PCH before, it will look like
  8693. // the definition comes from there, even if that was just the declaration.
  8694. // (Explicit instantiation defs of variable templates always get emitted.)
  8695. bool IsExpInstDef =
  8696. isa<FunctionDecl>(D) &&
  8697. cast<FunctionDecl>(D)->getTemplateSpecializationKind() ==
  8698. TSK_ExplicitInstantiationDefinition;
  8699. // Implicit member function definitions, such as operator= might not be
  8700. // marked as template specializations, since they're not coming from a
  8701. // template but synthesized directly on the class.
  8702. IsExpInstDef |=
  8703. isa<CXXMethodDecl>(D) &&
  8704. cast<CXXMethodDecl>(D)->getParent()->getTemplateSpecializationKind() ==
  8705. TSK_ExplicitInstantiationDefinition;
  8706. if (getExternalSource()->DeclIsFromPCHWithObjectFile(D) && !IsExpInstDef)
  8707. return false;
  8708. }
  8709. // If this is a member of a class template, we do not need to emit it.
  8710. if (D->getDeclContext()->isDependentContext())
  8711. return false;
  8712. // Weak references don't produce any output by themselves.
  8713. if (D->hasAttr<WeakRefAttr>())
  8714. return false;
  8715. // Aliases and used decls are required.
  8716. if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
  8717. return true;
  8718. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  8719. // Forward declarations aren't required.
  8720. if (!FD->doesThisDeclarationHaveABody())
  8721. return FD->doesDeclarationForceExternallyVisibleDefinition();
  8722. // Constructors and destructors are required.
  8723. if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
  8724. return true;
  8725. // The key function for a class is required. This rule only comes
  8726. // into play when inline functions can be key functions, though.
  8727. if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
  8728. if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
  8729. const CXXRecordDecl *RD = MD->getParent();
  8730. if (MD->isOutOfLine() && RD->isDynamicClass()) {
  8731. const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
  8732. if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
  8733. return true;
  8734. }
  8735. }
  8736. }
  8737. GVALinkage Linkage = GetGVALinkageForFunction(FD);
  8738. // static, static inline, always_inline, and extern inline functions can
  8739. // always be deferred. Normal inline functions can be deferred in C99/C++.
  8740. // Implicit template instantiations can also be deferred in C++.
  8741. return !isDiscardableGVALinkage(Linkage);
  8742. }
  8743. const auto *VD = cast<VarDecl>(D);
  8744. assert(VD->isFileVarDecl() && "Expected file scoped var");
  8745. // If the decl is marked as `declare target to`, it should be emitted for the
  8746. // host and for the device.
  8747. if (LangOpts.OpenMP &&
  8748. OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
  8749. return true;
  8750. if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
  8751. !isMSStaticDataMemberInlineDefinition(VD))
  8752. return false;
  8753. // Variables that can be needed in other TUs are required.
  8754. auto Linkage = GetGVALinkageForVariable(VD);
  8755. if (!isDiscardableGVALinkage(Linkage))
  8756. return true;
  8757. // We never need to emit a variable that is available in another TU.
  8758. if (Linkage == GVA_AvailableExternally)
  8759. return false;
  8760. // Variables that have destruction with side-effects are required.
  8761. if (VD->needsDestruction(*this))
  8762. return true;
  8763. // Variables that have initialization with side-effects are required.
  8764. if (VD->getInit() && VD->getInit()->HasSideEffects(*this) &&
  8765. // We can get a value-dependent initializer during error recovery.
  8766. (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
  8767. return true;
  8768. // Likewise, variables with tuple-like bindings are required if their
  8769. // bindings have side-effects.
  8770. if (const auto *DD = dyn_cast<DecompositionDecl>(VD))
  8771. for (const auto *BD : DD->bindings())
  8772. if (const auto *BindingVD = BD->getHoldingVar())
  8773. if (DeclMustBeEmitted(BindingVD))
  8774. return true;
  8775. return false;
  8776. }
  8777. void ASTContext::forEachMultiversionedFunctionVersion(
  8778. const FunctionDecl *FD,
  8779. llvm::function_ref<void(FunctionDecl *)> Pred) const {
  8780. assert(FD->isMultiVersion() && "Only valid for multiversioned functions");
  8781. llvm::SmallDenseSet<const FunctionDecl*, 4> SeenDecls;
  8782. FD = FD->getMostRecentDecl();
  8783. for (auto *CurDecl :
  8784. FD->getDeclContext()->getRedeclContext()->lookup(FD->getDeclName())) {
  8785. FunctionDecl *CurFD = CurDecl->getAsFunction()->getMostRecentDecl();
  8786. if (CurFD && hasSameType(CurFD->getType(), FD->getType()) &&
  8787. std::end(SeenDecls) == llvm::find(SeenDecls, CurFD)) {
  8788. SeenDecls.insert(CurFD);
  8789. Pred(CurFD);
  8790. }
  8791. }
  8792. }
  8793. CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
  8794. bool IsCXXMethod,
  8795. bool IsBuiltin) const {
  8796. // Pass through to the C++ ABI object
  8797. if (IsCXXMethod)
  8798. return ABI->getDefaultMethodCallConv(IsVariadic);
  8799. // Builtins ignore user-specified default calling convention and remain the
  8800. // Target's default calling convention.
  8801. if (!IsBuiltin) {
  8802. switch (LangOpts.getDefaultCallingConv()) {
  8803. case LangOptions::DCC_None:
  8804. break;
  8805. case LangOptions::DCC_CDecl:
  8806. return CC_C;
  8807. case LangOptions::DCC_FastCall:
  8808. if (getTargetInfo().hasFeature("sse2") && !IsVariadic)
  8809. return CC_X86FastCall;
  8810. break;
  8811. case LangOptions::DCC_StdCall:
  8812. if (!IsVariadic)
  8813. return CC_X86StdCall;
  8814. break;
  8815. case LangOptions::DCC_VectorCall:
  8816. // __vectorcall cannot be applied to variadic functions.
  8817. if (!IsVariadic)
  8818. return CC_X86VectorCall;
  8819. break;
  8820. case LangOptions::DCC_RegCall:
  8821. // __regcall cannot be applied to variadic functions.
  8822. if (!IsVariadic)
  8823. return CC_X86RegCall;
  8824. break;
  8825. }
  8826. }
  8827. return Target->getDefaultCallingConv();
  8828. }
  8829. bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
  8830. // Pass through to the C++ ABI object
  8831. return ABI->isNearlyEmpty(RD);
  8832. }
  8833. VTableContextBase *ASTContext::getVTableContext() {
  8834. if (!VTContext.get()) {
  8835. if (Target->getCXXABI().isMicrosoft())
  8836. VTContext.reset(new MicrosoftVTableContext(*this));
  8837. else
  8838. VTContext.reset(new ItaniumVTableContext(*this));
  8839. }
  8840. return VTContext.get();
  8841. }
  8842. MangleContext *ASTContext::createMangleContext(const TargetInfo *T) {
  8843. if (!T)
  8844. T = Target;
  8845. switch (T->getCXXABI().getKind()) {
  8846. case TargetCXXABI::GenericAArch64:
  8847. case TargetCXXABI::GenericItanium:
  8848. case TargetCXXABI::GenericARM:
  8849. case TargetCXXABI::GenericMIPS:
  8850. case TargetCXXABI::iOS:
  8851. case TargetCXXABI::iOS64:
  8852. case TargetCXXABI::WebAssembly:
  8853. case TargetCXXABI::WatchOS:
  8854. return ItaniumMangleContext::create(*this, getDiagnostics());
  8855. case TargetCXXABI::Microsoft:
  8856. return MicrosoftMangleContext::create(*this, getDiagnostics());
  8857. }
  8858. llvm_unreachable("Unsupported ABI");
  8859. }
  8860. CXXABI::~CXXABI() = default;
  8861. size_t ASTContext::getSideTableAllocatedMemory() const {
  8862. return ASTRecordLayouts.getMemorySize() +
  8863. llvm::capacity_in_bytes(ObjCLayouts) +
  8864. llvm::capacity_in_bytes(KeyFunctions) +
  8865. llvm::capacity_in_bytes(ObjCImpls) +
  8866. llvm::capacity_in_bytes(BlockVarCopyInits) +
  8867. llvm::capacity_in_bytes(DeclAttrs) +
  8868. llvm::capacity_in_bytes(TemplateOrInstantiation) +
  8869. llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
  8870. llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
  8871. llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
  8872. llvm::capacity_in_bytes(OverriddenMethods) +
  8873. llvm::capacity_in_bytes(Types) +
  8874. llvm::capacity_in_bytes(VariableArrayTypes);
  8875. }
  8876. /// getIntTypeForBitwidth -
  8877. /// sets integer QualTy according to specified details:
  8878. /// bitwidth, signed/unsigned.
  8879. /// Returns empty type if there is no appropriate target types.
  8880. QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
  8881. unsigned Signed) const {
  8882. TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
  8883. CanQualType QualTy = getFromTargetType(Ty);
  8884. if (!QualTy && DestWidth == 128)
  8885. return Signed ? Int128Ty : UnsignedInt128Ty;
  8886. return QualTy;
  8887. }
  8888. /// getRealTypeForBitwidth -
  8889. /// sets floating point QualTy according to specified bitwidth.
  8890. /// Returns empty type if there is no appropriate target types.
  8891. QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
  8892. TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
  8893. switch (Ty) {
  8894. case TargetInfo::Float:
  8895. return FloatTy;
  8896. case TargetInfo::Double:
  8897. return DoubleTy;
  8898. case TargetInfo::LongDouble:
  8899. return LongDoubleTy;
  8900. case TargetInfo::Float128:
  8901. return Float128Ty;
  8902. case TargetInfo::NoFloat:
  8903. return {};
  8904. }
  8905. llvm_unreachable("Unhandled TargetInfo::RealType value");
  8906. }
  8907. void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
  8908. if (Number > 1)
  8909. MangleNumbers[ND] = Number;
  8910. }
  8911. unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
  8912. auto I = MangleNumbers.find(ND);
  8913. return I != MangleNumbers.end() ? I->second : 1;
  8914. }
  8915. void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
  8916. if (Number > 1)
  8917. StaticLocalNumbers[VD] = Number;
  8918. }
  8919. unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
  8920. auto I = StaticLocalNumbers.find(VD);
  8921. return I != StaticLocalNumbers.end() ? I->second : 1;
  8922. }
  8923. MangleNumberingContext &
  8924. ASTContext::getManglingNumberContext(const DeclContext *DC) {
  8925. assert(LangOpts.CPlusPlus); // We don't need mangling numbers for plain C.
  8926. std::unique_ptr<MangleNumberingContext> &MCtx = MangleNumberingContexts[DC];
  8927. if (!MCtx)
  8928. MCtx = createMangleNumberingContext();
  8929. return *MCtx;
  8930. }
  8931. std::unique_ptr<MangleNumberingContext>
  8932. ASTContext::createMangleNumberingContext() const {
  8933. return ABI->createMangleNumberingContext();
  8934. }
  8935. const CXXConstructorDecl *
  8936. ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
  8937. return ABI->getCopyConstructorForExceptionObject(
  8938. cast<CXXRecordDecl>(RD->getFirstDecl()));
  8939. }
  8940. void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  8941. CXXConstructorDecl *CD) {
  8942. return ABI->addCopyConstructorForExceptionObject(
  8943. cast<CXXRecordDecl>(RD->getFirstDecl()),
  8944. cast<CXXConstructorDecl>(CD->getFirstDecl()));
  8945. }
  8946. void ASTContext::addTypedefNameForUnnamedTagDecl(TagDecl *TD,
  8947. TypedefNameDecl *DD) {
  8948. return ABI->addTypedefNameForUnnamedTagDecl(TD, DD);
  8949. }
  8950. TypedefNameDecl *
  8951. ASTContext::getTypedefNameForUnnamedTagDecl(const TagDecl *TD) {
  8952. return ABI->getTypedefNameForUnnamedTagDecl(TD);
  8953. }
  8954. void ASTContext::addDeclaratorForUnnamedTagDecl(TagDecl *TD,
  8955. DeclaratorDecl *DD) {
  8956. return ABI->addDeclaratorForUnnamedTagDecl(TD, DD);
  8957. }
  8958. DeclaratorDecl *ASTContext::getDeclaratorForUnnamedTagDecl(const TagDecl *TD) {
  8959. return ABI->getDeclaratorForUnnamedTagDecl(TD);
  8960. }
  8961. void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
  8962. ParamIndices[D] = index;
  8963. }
  8964. unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
  8965. ParameterIndexTable::const_iterator I = ParamIndices.find(D);
  8966. assert(I != ParamIndices.end() &&
  8967. "ParmIndices lacks entry set by ParmVarDecl");
  8968. return I->second;
  8969. }
  8970. APValue *
  8971. ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
  8972. bool MayCreate) {
  8973. assert(E && E->getStorageDuration() == SD_Static &&
  8974. "don't need to cache the computed value for this temporary");
  8975. if (MayCreate) {
  8976. APValue *&MTVI = MaterializedTemporaryValues[E];
  8977. if (!MTVI)
  8978. MTVI = new (*this) APValue;
  8979. return MTVI;
  8980. }
  8981. return MaterializedTemporaryValues.lookup(E);
  8982. }
  8983. QualType ASTContext::getStringLiteralArrayType(QualType EltTy,
  8984. unsigned Length) const {
  8985. // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
  8986. if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
  8987. EltTy = EltTy.withConst();
  8988. EltTy = adjustStringLiteralBaseType(EltTy);
  8989. // Get an array type for the string, according to C99 6.4.5. This includes
  8990. // the null terminator character.
  8991. return getConstantArrayType(EltTy, llvm::APInt(32, Length + 1), nullptr,
  8992. ArrayType::Normal, /*IndexTypeQuals*/ 0);
  8993. }
  8994. StringLiteral *
  8995. ASTContext::getPredefinedStringLiteralFromCache(StringRef Key) const {
  8996. StringLiteral *&Result = StringLiteralCache[Key];
  8997. if (!Result)
  8998. Result = StringLiteral::Create(
  8999. *this, Key, StringLiteral::Ascii,
  9000. /*Pascal*/ false, getStringLiteralArrayType(CharTy, Key.size()),
  9001. SourceLocation());
  9002. return Result;
  9003. }
  9004. bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
  9005. const llvm::Triple &T = getTargetInfo().getTriple();
  9006. if (!T.isOSDarwin())
  9007. return false;
  9008. if (!(T.isiOS() && T.isOSVersionLT(7)) &&
  9009. !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
  9010. return false;
  9011. QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
  9012. CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
  9013. uint64_t Size = sizeChars.getQuantity();
  9014. CharUnits alignChars = getTypeAlignInChars(AtomicTy);
  9015. unsigned Align = alignChars.getQuantity();
  9016. unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
  9017. return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
  9018. }
  9019. /// Template specializations to abstract away from pointers and TypeLocs.
  9020. /// @{
  9021. template <typename T>
  9022. static ast_type_traits::DynTypedNode createDynTypedNode(const T &Node) {
  9023. return ast_type_traits::DynTypedNode::create(*Node);
  9024. }
  9025. template <>
  9026. ast_type_traits::DynTypedNode createDynTypedNode(const TypeLoc &Node) {
  9027. return ast_type_traits::DynTypedNode::create(Node);
  9028. }
  9029. template <>
  9030. ast_type_traits::DynTypedNode
  9031. createDynTypedNode(const NestedNameSpecifierLoc &Node) {
  9032. return ast_type_traits::DynTypedNode::create(Node);
  9033. }
  9034. /// @}
  9035. /// A \c RecursiveASTVisitor that builds a map from nodes to their
  9036. /// parents as defined by the \c RecursiveASTVisitor.
  9037. ///
  9038. /// Note that the relationship described here is purely in terms of AST
  9039. /// traversal - there are other relationships (for example declaration context)
  9040. /// in the AST that are better modeled by special matchers.
  9041. ///
  9042. /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
  9043. class ASTContext::ParentMap::ASTVisitor
  9044. : public RecursiveASTVisitor<ASTVisitor> {
  9045. public:
  9046. ASTVisitor(ParentMap &Map) : Map(Map) {}
  9047. private:
  9048. friend class RecursiveASTVisitor<ASTVisitor>;
  9049. using VisitorBase = RecursiveASTVisitor<ASTVisitor>;
  9050. bool shouldVisitTemplateInstantiations() const { return true; }
  9051. bool shouldVisitImplicitCode() const { return true; }
  9052. template <typename T, typename MapNodeTy, typename BaseTraverseFn,
  9053. typename MapTy>
  9054. bool TraverseNode(T Node, MapNodeTy MapNode, BaseTraverseFn BaseTraverse,
  9055. MapTy *Parents) {
  9056. if (!Node)
  9057. return true;
  9058. if (ParentStack.size() > 0) {
  9059. // FIXME: Currently we add the same parent multiple times, but only
  9060. // when no memoization data is available for the type.
  9061. // For example when we visit all subexpressions of template
  9062. // instantiations; this is suboptimal, but benign: the only way to
  9063. // visit those is with hasAncestor / hasParent, and those do not create
  9064. // new matches.
  9065. // The plan is to enable DynTypedNode to be storable in a map or hash
  9066. // map. The main problem there is to implement hash functions /
  9067. // comparison operators for all types that DynTypedNode supports that
  9068. // do not have pointer identity.
  9069. auto &NodeOrVector = (*Parents)[MapNode];
  9070. if (NodeOrVector.isNull()) {
  9071. if (const auto *D = ParentStack.back().get<Decl>())
  9072. NodeOrVector = D;
  9073. else if (const auto *S = ParentStack.back().get<Stmt>())
  9074. NodeOrVector = S;
  9075. else
  9076. NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
  9077. } else {
  9078. if (!NodeOrVector.template is<ParentVector *>()) {
  9079. auto *Vector = new ParentVector(
  9080. 1, getSingleDynTypedNodeFromParentMap(NodeOrVector));
  9081. delete NodeOrVector
  9082. .template dyn_cast<ast_type_traits::DynTypedNode *>();
  9083. NodeOrVector = Vector;
  9084. }
  9085. auto *Vector = NodeOrVector.template get<ParentVector *>();
  9086. // Skip duplicates for types that have memoization data.
  9087. // We must check that the type has memoization data before calling
  9088. // std::find() because DynTypedNode::operator== can't compare all
  9089. // types.
  9090. bool Found = ParentStack.back().getMemoizationData() &&
  9091. std::find(Vector->begin(), Vector->end(),
  9092. ParentStack.back()) != Vector->end();
  9093. if (!Found)
  9094. Vector->push_back(ParentStack.back());
  9095. }
  9096. }
  9097. ParentStack.push_back(createDynTypedNode(Node));
  9098. bool Result = BaseTraverse();
  9099. ParentStack.pop_back();
  9100. return Result;
  9101. }
  9102. bool TraverseDecl(Decl *DeclNode) {
  9103. return TraverseNode(
  9104. DeclNode, DeclNode, [&] { return VisitorBase::TraverseDecl(DeclNode); },
  9105. &Map.PointerParents);
  9106. }
  9107. bool TraverseStmt(Stmt *StmtNode) {
  9108. return TraverseNode(
  9109. StmtNode, StmtNode, [&] { return VisitorBase::TraverseStmt(StmtNode); },
  9110. &Map.PointerParents);
  9111. }
  9112. bool TraverseTypeLoc(TypeLoc TypeLocNode) {
  9113. return TraverseNode(
  9114. TypeLocNode, ast_type_traits::DynTypedNode::create(TypeLocNode),
  9115. [&] { return VisitorBase::TraverseTypeLoc(TypeLocNode); },
  9116. &Map.OtherParents);
  9117. }
  9118. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSLocNode) {
  9119. return TraverseNode(
  9120. NNSLocNode, ast_type_traits::DynTypedNode::create(NNSLocNode),
  9121. [&] { return VisitorBase::TraverseNestedNameSpecifierLoc(NNSLocNode); },
  9122. &Map.OtherParents);
  9123. }
  9124. ParentMap &Map;
  9125. llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
  9126. };
  9127. ASTContext::ParentMap::ParentMap(ASTContext &Ctx) {
  9128. ASTVisitor(*this).TraverseAST(Ctx);
  9129. }
  9130. ASTContext::DynTypedNodeList
  9131. ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
  9132. if (!Parents)
  9133. // We build the parent map for the traversal scope (usually whole TU), as
  9134. // hasAncestor can escape any subtree.
  9135. Parents = std::make_unique<ParentMap>(*this);
  9136. return Parents->getParents(Node);
  9137. }
  9138. bool
  9139. ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  9140. const ObjCMethodDecl *MethodImpl) {
  9141. // No point trying to match an unavailable/deprecated mothod.
  9142. if (MethodDecl->hasAttr<UnavailableAttr>()
  9143. || MethodDecl->hasAttr<DeprecatedAttr>())
  9144. return false;
  9145. if (MethodDecl->getObjCDeclQualifier() !=
  9146. MethodImpl->getObjCDeclQualifier())
  9147. return false;
  9148. if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
  9149. return false;
  9150. if (MethodDecl->param_size() != MethodImpl->param_size())
  9151. return false;
  9152. for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
  9153. IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
  9154. EF = MethodDecl->param_end();
  9155. IM != EM && IF != EF; ++IM, ++IF) {
  9156. const ParmVarDecl *DeclVar = (*IF);
  9157. const ParmVarDecl *ImplVar = (*IM);
  9158. if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
  9159. return false;
  9160. if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
  9161. return false;
  9162. }
  9163. return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
  9164. }
  9165. uint64_t ASTContext::getTargetNullPointerValue(QualType QT) const {
  9166. LangAS AS;
  9167. if (QT->getUnqualifiedDesugaredType()->isNullPtrType())
  9168. AS = LangAS::Default;
  9169. else
  9170. AS = QT->getPointeeType().getAddressSpace();
  9171. return getTargetInfo().getNullPointerValue(AS);
  9172. }
  9173. unsigned ASTContext::getTargetAddressSpace(LangAS AS) const {
  9174. if (isTargetAddressSpace(AS))
  9175. return toTargetAddressSpace(AS);
  9176. else
  9177. return (*AddrSpaceMap)[(unsigned)AS];
  9178. }
  9179. QualType ASTContext::getCorrespondingSaturatedType(QualType Ty) const {
  9180. assert(Ty->isFixedPointType());
  9181. if (Ty->isSaturatedFixedPointType()) return Ty;
  9182. switch (Ty->castAs<BuiltinType>()->getKind()) {
  9183. default:
  9184. llvm_unreachable("Not a fixed point type!");
  9185. case BuiltinType::ShortAccum:
  9186. return SatShortAccumTy;
  9187. case BuiltinType::Accum:
  9188. return SatAccumTy;
  9189. case BuiltinType::LongAccum:
  9190. return SatLongAccumTy;
  9191. case BuiltinType::UShortAccum:
  9192. return SatUnsignedShortAccumTy;
  9193. case BuiltinType::UAccum:
  9194. return SatUnsignedAccumTy;
  9195. case BuiltinType::ULongAccum:
  9196. return SatUnsignedLongAccumTy;
  9197. case BuiltinType::ShortFract:
  9198. return SatShortFractTy;
  9199. case BuiltinType::Fract:
  9200. return SatFractTy;
  9201. case BuiltinType::LongFract:
  9202. return SatLongFractTy;
  9203. case BuiltinType::UShortFract:
  9204. return SatUnsignedShortFractTy;
  9205. case BuiltinType::UFract:
  9206. return SatUnsignedFractTy;
  9207. case BuiltinType::ULongFract:
  9208. return SatUnsignedLongFractTy;
  9209. }
  9210. }
  9211. LangAS ASTContext::getLangASForBuiltinAddressSpace(unsigned AS) const {
  9212. if (LangOpts.OpenCL)
  9213. return getTargetInfo().getOpenCLBuiltinAddressSpace(AS);
  9214. if (LangOpts.CUDA)
  9215. return getTargetInfo().getCUDABuiltinAddressSpace(AS);
  9216. return getLangASFromTargetAS(AS);
  9217. }
  9218. // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
  9219. // doesn't include ASTContext.h
  9220. template
  9221. clang::LazyGenerationalUpdatePtr<
  9222. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
  9223. clang::LazyGenerationalUpdatePtr<
  9224. const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
  9225. const clang::ASTContext &Ctx, Decl *Value);
  9226. unsigned char ASTContext::getFixedPointScale(QualType Ty) const {
  9227. assert(Ty->isFixedPointType());
  9228. const TargetInfo &Target = getTargetInfo();
  9229. switch (Ty->castAs<BuiltinType>()->getKind()) {
  9230. default:
  9231. llvm_unreachable("Not a fixed point type!");
  9232. case BuiltinType::ShortAccum:
  9233. case BuiltinType::SatShortAccum:
  9234. return Target.getShortAccumScale();
  9235. case BuiltinType::Accum:
  9236. case BuiltinType::SatAccum:
  9237. return Target.getAccumScale();
  9238. case BuiltinType::LongAccum:
  9239. case BuiltinType::SatLongAccum:
  9240. return Target.getLongAccumScale();
  9241. case BuiltinType::UShortAccum:
  9242. case BuiltinType::SatUShortAccum:
  9243. return Target.getUnsignedShortAccumScale();
  9244. case BuiltinType::UAccum:
  9245. case BuiltinType::SatUAccum:
  9246. return Target.getUnsignedAccumScale();
  9247. case BuiltinType::ULongAccum:
  9248. case BuiltinType::SatULongAccum:
  9249. return Target.getUnsignedLongAccumScale();
  9250. case BuiltinType::ShortFract:
  9251. case BuiltinType::SatShortFract:
  9252. return Target.getShortFractScale();
  9253. case BuiltinType::Fract:
  9254. case BuiltinType::SatFract:
  9255. return Target.getFractScale();
  9256. case BuiltinType::LongFract:
  9257. case BuiltinType::SatLongFract:
  9258. return Target.getLongFractScale();
  9259. case BuiltinType::UShortFract:
  9260. case BuiltinType::SatUShortFract:
  9261. return Target.getUnsignedShortFractScale();
  9262. case BuiltinType::UFract:
  9263. case BuiltinType::SatUFract:
  9264. return Target.getUnsignedFractScale();
  9265. case BuiltinType::ULongFract:
  9266. case BuiltinType::SatULongFract:
  9267. return Target.getUnsignedLongFractScale();
  9268. }
  9269. }
  9270. unsigned char ASTContext::getFixedPointIBits(QualType Ty) const {
  9271. assert(Ty->isFixedPointType());
  9272. const TargetInfo &Target = getTargetInfo();
  9273. switch (Ty->castAs<BuiltinType>()->getKind()) {
  9274. default:
  9275. llvm_unreachable("Not a fixed point type!");
  9276. case BuiltinType::ShortAccum:
  9277. case BuiltinType::SatShortAccum:
  9278. return Target.getShortAccumIBits();
  9279. case BuiltinType::Accum:
  9280. case BuiltinType::SatAccum:
  9281. return Target.getAccumIBits();
  9282. case BuiltinType::LongAccum:
  9283. case BuiltinType::SatLongAccum:
  9284. return Target.getLongAccumIBits();
  9285. case BuiltinType::UShortAccum:
  9286. case BuiltinType::SatUShortAccum:
  9287. return Target.getUnsignedShortAccumIBits();
  9288. case BuiltinType::UAccum:
  9289. case BuiltinType::SatUAccum:
  9290. return Target.getUnsignedAccumIBits();
  9291. case BuiltinType::ULongAccum:
  9292. case BuiltinType::SatULongAccum:
  9293. return Target.getUnsignedLongAccumIBits();
  9294. case BuiltinType::ShortFract:
  9295. case BuiltinType::SatShortFract:
  9296. case BuiltinType::Fract:
  9297. case BuiltinType::SatFract:
  9298. case BuiltinType::LongFract:
  9299. case BuiltinType::SatLongFract:
  9300. case BuiltinType::UShortFract:
  9301. case BuiltinType::SatUShortFract:
  9302. case BuiltinType::UFract:
  9303. case BuiltinType::SatUFract:
  9304. case BuiltinType::ULongFract:
  9305. case BuiltinType::SatULongFract:
  9306. return 0;
  9307. }
  9308. }
  9309. FixedPointSemantics ASTContext::getFixedPointSemantics(QualType Ty) const {
  9310. assert((Ty->isFixedPointType() || Ty->isIntegerType()) &&
  9311. "Can only get the fixed point semantics for a "
  9312. "fixed point or integer type.");
  9313. if (Ty->isIntegerType())
  9314. return FixedPointSemantics::GetIntegerSemantics(getIntWidth(Ty),
  9315. Ty->isSignedIntegerType());
  9316. bool isSigned = Ty->isSignedFixedPointType();
  9317. return FixedPointSemantics(
  9318. static_cast<unsigned>(getTypeSize(Ty)), getFixedPointScale(Ty), isSigned,
  9319. Ty->isSaturatedFixedPointType(),
  9320. !isSigned && getTargetInfo().doUnsignedFixedPointTypesHavePadding());
  9321. }
  9322. APFixedPoint ASTContext::getFixedPointMax(QualType Ty) const {
  9323. assert(Ty->isFixedPointType());
  9324. return APFixedPoint::getMax(getFixedPointSemantics(Ty));
  9325. }
  9326. APFixedPoint ASTContext::getFixedPointMin(QualType Ty) const {
  9327. assert(Ty->isFixedPointType());
  9328. return APFixedPoint::getMin(getFixedPointSemantics(Ty));
  9329. }
  9330. QualType ASTContext::getCorrespondingSignedFixedPointType(QualType Ty) const {
  9331. assert(Ty->isUnsignedFixedPointType() &&
  9332. "Expected unsigned fixed point type");
  9333. switch (Ty->castAs<BuiltinType>()->getKind()) {
  9334. case BuiltinType::UShortAccum:
  9335. return ShortAccumTy;
  9336. case BuiltinType::UAccum:
  9337. return AccumTy;
  9338. case BuiltinType::ULongAccum:
  9339. return LongAccumTy;
  9340. case BuiltinType::SatUShortAccum:
  9341. return SatShortAccumTy;
  9342. case BuiltinType::SatUAccum:
  9343. return SatAccumTy;
  9344. case BuiltinType::SatULongAccum:
  9345. return SatLongAccumTy;
  9346. case BuiltinType::UShortFract:
  9347. return ShortFractTy;
  9348. case BuiltinType::UFract:
  9349. return FractTy;
  9350. case BuiltinType::ULongFract:
  9351. return LongFractTy;
  9352. case BuiltinType::SatUShortFract:
  9353. return SatShortFractTy;
  9354. case BuiltinType::SatUFract:
  9355. return SatFractTy;
  9356. case BuiltinType::SatULongFract:
  9357. return SatLongFractTy;
  9358. default:
  9359. llvm_unreachable("Unexpected unsigned fixed point type");
  9360. }
  9361. }