LLParser.cpp 279 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217
  1. //===-- LLParser.cpp - Parser Class ---------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the parser class for .ll files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LLParser.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallPtrSet.h"
  19. #include "llvm/AsmParser/SlotMapping.h"
  20. #include "llvm/BinaryFormat/Dwarf.h"
  21. #include "llvm/IR/Argument.h"
  22. #include "llvm/IR/AutoUpgrade.h"
  23. #include "llvm/IR/BasicBlock.h"
  24. #include "llvm/IR/CallingConv.h"
  25. #include "llvm/IR/Comdat.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DebugInfoMetadata.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GlobalIFunc.h"
  31. #include "llvm/IR/GlobalObject.h"
  32. #include "llvm/IR/InlineAsm.h"
  33. #include "llvm/IR/Instruction.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/Intrinsics.h"
  36. #include "llvm/IR/LLVMContext.h"
  37. #include "llvm/IR/Metadata.h"
  38. #include "llvm/IR/Module.h"
  39. #include "llvm/IR/Operator.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/IR/Value.h"
  42. #include "llvm/IR/ValueSymbolTable.h"
  43. #include "llvm/Support/Casting.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/MathExtras.h"
  46. #include "llvm/Support/SaveAndRestore.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstring>
  51. #include <iterator>
  52. #include <vector>
  53. using namespace llvm;
  54. static std::string getTypeString(Type *T) {
  55. std::string Result;
  56. raw_string_ostream Tmp(Result);
  57. Tmp << *T;
  58. return Tmp.str();
  59. }
  60. /// Run: module ::= toplevelentity*
  61. bool LLParser::Run() {
  62. // Prime the lexer.
  63. Lex.Lex();
  64. if (Context.shouldDiscardValueNames())
  65. return Error(
  66. Lex.getLoc(),
  67. "Can't read textual IR with a Context that discards named Values");
  68. return ParseTopLevelEntities() || ValidateEndOfModule() ||
  69. ValidateEndOfIndex();
  70. }
  71. bool LLParser::parseStandaloneConstantValue(Constant *&C,
  72. const SlotMapping *Slots) {
  73. restoreParsingState(Slots);
  74. Lex.Lex();
  75. Type *Ty = nullptr;
  76. if (ParseType(Ty) || parseConstantValue(Ty, C))
  77. return true;
  78. if (Lex.getKind() != lltok::Eof)
  79. return Error(Lex.getLoc(), "expected end of string");
  80. return false;
  81. }
  82. bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
  83. const SlotMapping *Slots) {
  84. restoreParsingState(Slots);
  85. Lex.Lex();
  86. Read = 0;
  87. SMLoc Start = Lex.getLoc();
  88. Ty = nullptr;
  89. if (ParseType(Ty))
  90. return true;
  91. SMLoc End = Lex.getLoc();
  92. Read = End.getPointer() - Start.getPointer();
  93. return false;
  94. }
  95. void LLParser::restoreParsingState(const SlotMapping *Slots) {
  96. if (!Slots)
  97. return;
  98. NumberedVals = Slots->GlobalValues;
  99. NumberedMetadata = Slots->MetadataNodes;
  100. for (const auto &I : Slots->NamedTypes)
  101. NamedTypes.insert(
  102. std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
  103. for (const auto &I : Slots->Types)
  104. NumberedTypes.insert(
  105. std::make_pair(I.first, std::make_pair(I.second, LocTy())));
  106. }
  107. /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
  108. /// module.
  109. bool LLParser::ValidateEndOfModule() {
  110. if (!M)
  111. return false;
  112. // Handle any function attribute group forward references.
  113. for (const auto &RAG : ForwardRefAttrGroups) {
  114. Value *V = RAG.first;
  115. const std::vector<unsigned> &Attrs = RAG.second;
  116. AttrBuilder B;
  117. for (const auto &Attr : Attrs)
  118. B.merge(NumberedAttrBuilders[Attr]);
  119. if (Function *Fn = dyn_cast<Function>(V)) {
  120. AttributeList AS = Fn->getAttributes();
  121. AttrBuilder FnAttrs(AS.getFnAttributes());
  122. AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
  123. FnAttrs.merge(B);
  124. // If the alignment was parsed as an attribute, move to the alignment
  125. // field.
  126. if (FnAttrs.hasAlignmentAttr()) {
  127. Fn->setAlignment(FnAttrs.getAlignment());
  128. FnAttrs.removeAttribute(Attribute::Alignment);
  129. }
  130. AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
  131. AttributeSet::get(Context, FnAttrs));
  132. Fn->setAttributes(AS);
  133. } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
  134. AttributeList AS = CI->getAttributes();
  135. AttrBuilder FnAttrs(AS.getFnAttributes());
  136. AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
  137. FnAttrs.merge(B);
  138. AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
  139. AttributeSet::get(Context, FnAttrs));
  140. CI->setAttributes(AS);
  141. } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
  142. AttributeList AS = II->getAttributes();
  143. AttrBuilder FnAttrs(AS.getFnAttributes());
  144. AS = AS.removeAttributes(Context, AttributeList::FunctionIndex);
  145. FnAttrs.merge(B);
  146. AS = AS.addAttributes(Context, AttributeList::FunctionIndex,
  147. AttributeSet::get(Context, FnAttrs));
  148. II->setAttributes(AS);
  149. } else if (auto *GV = dyn_cast<GlobalVariable>(V)) {
  150. AttrBuilder Attrs(GV->getAttributes());
  151. Attrs.merge(B);
  152. GV->setAttributes(AttributeSet::get(Context,Attrs));
  153. } else {
  154. llvm_unreachable("invalid object with forward attribute group reference");
  155. }
  156. }
  157. // If there are entries in ForwardRefBlockAddresses at this point, the
  158. // function was never defined.
  159. if (!ForwardRefBlockAddresses.empty())
  160. return Error(ForwardRefBlockAddresses.begin()->first.Loc,
  161. "expected function name in blockaddress");
  162. for (const auto &NT : NumberedTypes)
  163. if (NT.second.second.isValid())
  164. return Error(NT.second.second,
  165. "use of undefined type '%" + Twine(NT.first) + "'");
  166. for (StringMap<std::pair<Type*, LocTy> >::iterator I =
  167. NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
  168. if (I->second.second.isValid())
  169. return Error(I->second.second,
  170. "use of undefined type named '" + I->getKey() + "'");
  171. if (!ForwardRefComdats.empty())
  172. return Error(ForwardRefComdats.begin()->second,
  173. "use of undefined comdat '$" +
  174. ForwardRefComdats.begin()->first + "'");
  175. if (!ForwardRefVals.empty())
  176. return Error(ForwardRefVals.begin()->second.second,
  177. "use of undefined value '@" + ForwardRefVals.begin()->first +
  178. "'");
  179. if (!ForwardRefValIDs.empty())
  180. return Error(ForwardRefValIDs.begin()->second.second,
  181. "use of undefined value '@" +
  182. Twine(ForwardRefValIDs.begin()->first) + "'");
  183. if (!ForwardRefMDNodes.empty())
  184. return Error(ForwardRefMDNodes.begin()->second.second,
  185. "use of undefined metadata '!" +
  186. Twine(ForwardRefMDNodes.begin()->first) + "'");
  187. // Resolve metadata cycles.
  188. for (auto &N : NumberedMetadata) {
  189. if (N.second && !N.second->isResolved())
  190. N.second->resolveCycles();
  191. }
  192. for (auto *Inst : InstsWithTBAATag) {
  193. MDNode *MD = Inst->getMetadata(LLVMContext::MD_tbaa);
  194. assert(MD && "UpgradeInstWithTBAATag should have a TBAA tag");
  195. auto *UpgradedMD = UpgradeTBAANode(*MD);
  196. if (MD != UpgradedMD)
  197. Inst->setMetadata(LLVMContext::MD_tbaa, UpgradedMD);
  198. }
  199. // Look for intrinsic functions and CallInst that need to be upgraded
  200. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
  201. UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
  202. // Some types could be renamed during loading if several modules are
  203. // loaded in the same LLVMContext (LTO scenario). In this case we should
  204. // remangle intrinsics names as well.
  205. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
  206. Function *F = &*FI++;
  207. if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
  208. F->replaceAllUsesWith(Remangled.getValue());
  209. F->eraseFromParent();
  210. }
  211. }
  212. if (UpgradeDebugInfo)
  213. llvm::UpgradeDebugInfo(*M);
  214. UpgradeModuleFlags(*M);
  215. UpgradeSectionAttributes(*M);
  216. if (!Slots)
  217. return false;
  218. // Initialize the slot mapping.
  219. // Because by this point we've parsed and validated everything, we can "steal"
  220. // the mapping from LLParser as it doesn't need it anymore.
  221. Slots->GlobalValues = std::move(NumberedVals);
  222. Slots->MetadataNodes = std::move(NumberedMetadata);
  223. for (const auto &I : NamedTypes)
  224. Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
  225. for (const auto &I : NumberedTypes)
  226. Slots->Types.insert(std::make_pair(I.first, I.second.first));
  227. return false;
  228. }
  229. /// Do final validity and sanity checks at the end of the index.
  230. bool LLParser::ValidateEndOfIndex() {
  231. if (!Index)
  232. return false;
  233. if (!ForwardRefValueInfos.empty())
  234. return Error(ForwardRefValueInfos.begin()->second.front().second,
  235. "use of undefined summary '^" +
  236. Twine(ForwardRefValueInfos.begin()->first) + "'");
  237. if (!ForwardRefAliasees.empty())
  238. return Error(ForwardRefAliasees.begin()->second.front().second,
  239. "use of undefined summary '^" +
  240. Twine(ForwardRefAliasees.begin()->first) + "'");
  241. if (!ForwardRefTypeIds.empty())
  242. return Error(ForwardRefTypeIds.begin()->second.front().second,
  243. "use of undefined type id summary '^" +
  244. Twine(ForwardRefTypeIds.begin()->first) + "'");
  245. return false;
  246. }
  247. //===----------------------------------------------------------------------===//
  248. // Top-Level Entities
  249. //===----------------------------------------------------------------------===//
  250. bool LLParser::ParseTopLevelEntities() {
  251. // If there is no Module, then parse just the summary index entries.
  252. if (!M) {
  253. while (true) {
  254. switch (Lex.getKind()) {
  255. case lltok::Eof:
  256. return false;
  257. case lltok::SummaryID:
  258. if (ParseSummaryEntry())
  259. return true;
  260. break;
  261. case lltok::kw_source_filename:
  262. if (ParseSourceFileName())
  263. return true;
  264. break;
  265. default:
  266. // Skip everything else
  267. Lex.Lex();
  268. }
  269. }
  270. }
  271. while (true) {
  272. switch (Lex.getKind()) {
  273. default: return TokError("expected top-level entity");
  274. case lltok::Eof: return false;
  275. case lltok::kw_declare: if (ParseDeclare()) return true; break;
  276. case lltok::kw_define: if (ParseDefine()) return true; break;
  277. case lltok::kw_module: if (ParseModuleAsm()) return true; break;
  278. case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
  279. case lltok::kw_source_filename:
  280. if (ParseSourceFileName())
  281. return true;
  282. break;
  283. case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
  284. case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
  285. case lltok::LocalVar: if (ParseNamedType()) return true; break;
  286. case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
  287. case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
  288. case lltok::ComdatVar: if (parseComdat()) return true; break;
  289. case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
  290. case lltok::SummaryID:
  291. if (ParseSummaryEntry())
  292. return true;
  293. break;
  294. case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
  295. case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
  296. case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
  297. case lltok::kw_uselistorder_bb:
  298. if (ParseUseListOrderBB())
  299. return true;
  300. break;
  301. }
  302. }
  303. }
  304. /// toplevelentity
  305. /// ::= 'module' 'asm' STRINGCONSTANT
  306. bool LLParser::ParseModuleAsm() {
  307. assert(Lex.getKind() == lltok::kw_module);
  308. Lex.Lex();
  309. std::string AsmStr;
  310. if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
  311. ParseStringConstant(AsmStr)) return true;
  312. M->appendModuleInlineAsm(AsmStr);
  313. return false;
  314. }
  315. /// toplevelentity
  316. /// ::= 'target' 'triple' '=' STRINGCONSTANT
  317. /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
  318. bool LLParser::ParseTargetDefinition() {
  319. assert(Lex.getKind() == lltok::kw_target);
  320. std::string Str;
  321. switch (Lex.Lex()) {
  322. default: return TokError("unknown target property");
  323. case lltok::kw_triple:
  324. Lex.Lex();
  325. if (ParseToken(lltok::equal, "expected '=' after target triple") ||
  326. ParseStringConstant(Str))
  327. return true;
  328. M->setTargetTriple(Str);
  329. return false;
  330. case lltok::kw_datalayout:
  331. Lex.Lex();
  332. if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
  333. ParseStringConstant(Str))
  334. return true;
  335. if (DataLayoutStr.empty())
  336. M->setDataLayout(Str);
  337. return false;
  338. }
  339. }
  340. /// toplevelentity
  341. /// ::= 'source_filename' '=' STRINGCONSTANT
  342. bool LLParser::ParseSourceFileName() {
  343. assert(Lex.getKind() == lltok::kw_source_filename);
  344. Lex.Lex();
  345. if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
  346. ParseStringConstant(SourceFileName))
  347. return true;
  348. if (M)
  349. M->setSourceFileName(SourceFileName);
  350. return false;
  351. }
  352. /// toplevelentity
  353. /// ::= 'deplibs' '=' '[' ']'
  354. /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
  355. /// FIXME: Remove in 4.0. Currently parse, but ignore.
  356. bool LLParser::ParseDepLibs() {
  357. assert(Lex.getKind() == lltok::kw_deplibs);
  358. Lex.Lex();
  359. if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
  360. ParseToken(lltok::lsquare, "expected '=' after deplibs"))
  361. return true;
  362. if (EatIfPresent(lltok::rsquare))
  363. return false;
  364. do {
  365. std::string Str;
  366. if (ParseStringConstant(Str)) return true;
  367. } while (EatIfPresent(lltok::comma));
  368. return ParseToken(lltok::rsquare, "expected ']' at end of list");
  369. }
  370. /// ParseUnnamedType:
  371. /// ::= LocalVarID '=' 'type' type
  372. bool LLParser::ParseUnnamedType() {
  373. LocTy TypeLoc = Lex.getLoc();
  374. unsigned TypeID = Lex.getUIntVal();
  375. Lex.Lex(); // eat LocalVarID;
  376. if (ParseToken(lltok::equal, "expected '=' after name") ||
  377. ParseToken(lltok::kw_type, "expected 'type' after '='"))
  378. return true;
  379. Type *Result = nullptr;
  380. if (ParseStructDefinition(TypeLoc, "",
  381. NumberedTypes[TypeID], Result)) return true;
  382. if (!isa<StructType>(Result)) {
  383. std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
  384. if (Entry.first)
  385. return Error(TypeLoc, "non-struct types may not be recursive");
  386. Entry.first = Result;
  387. Entry.second = SMLoc();
  388. }
  389. return false;
  390. }
  391. /// toplevelentity
  392. /// ::= LocalVar '=' 'type' type
  393. bool LLParser::ParseNamedType() {
  394. std::string Name = Lex.getStrVal();
  395. LocTy NameLoc = Lex.getLoc();
  396. Lex.Lex(); // eat LocalVar.
  397. if (ParseToken(lltok::equal, "expected '=' after name") ||
  398. ParseToken(lltok::kw_type, "expected 'type' after name"))
  399. return true;
  400. Type *Result = nullptr;
  401. if (ParseStructDefinition(NameLoc, Name,
  402. NamedTypes[Name], Result)) return true;
  403. if (!isa<StructType>(Result)) {
  404. std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
  405. if (Entry.first)
  406. return Error(NameLoc, "non-struct types may not be recursive");
  407. Entry.first = Result;
  408. Entry.second = SMLoc();
  409. }
  410. return false;
  411. }
  412. /// toplevelentity
  413. /// ::= 'declare' FunctionHeader
  414. bool LLParser::ParseDeclare() {
  415. assert(Lex.getKind() == lltok::kw_declare);
  416. Lex.Lex();
  417. std::vector<std::pair<unsigned, MDNode *>> MDs;
  418. while (Lex.getKind() == lltok::MetadataVar) {
  419. unsigned MDK;
  420. MDNode *N;
  421. if (ParseMetadataAttachment(MDK, N))
  422. return true;
  423. MDs.push_back({MDK, N});
  424. }
  425. Function *F;
  426. if (ParseFunctionHeader(F, false))
  427. return true;
  428. for (auto &MD : MDs)
  429. F->addMetadata(MD.first, *MD.second);
  430. return false;
  431. }
  432. /// toplevelentity
  433. /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
  434. bool LLParser::ParseDefine() {
  435. assert(Lex.getKind() == lltok::kw_define);
  436. Lex.Lex();
  437. Function *F;
  438. return ParseFunctionHeader(F, true) ||
  439. ParseOptionalFunctionMetadata(*F) ||
  440. ParseFunctionBody(*F);
  441. }
  442. /// ParseGlobalType
  443. /// ::= 'constant'
  444. /// ::= 'global'
  445. bool LLParser::ParseGlobalType(bool &IsConstant) {
  446. if (Lex.getKind() == lltok::kw_constant)
  447. IsConstant = true;
  448. else if (Lex.getKind() == lltok::kw_global)
  449. IsConstant = false;
  450. else {
  451. IsConstant = false;
  452. return TokError("expected 'global' or 'constant'");
  453. }
  454. Lex.Lex();
  455. return false;
  456. }
  457. bool LLParser::ParseOptionalUnnamedAddr(
  458. GlobalVariable::UnnamedAddr &UnnamedAddr) {
  459. if (EatIfPresent(lltok::kw_unnamed_addr))
  460. UnnamedAddr = GlobalValue::UnnamedAddr::Global;
  461. else if (EatIfPresent(lltok::kw_local_unnamed_addr))
  462. UnnamedAddr = GlobalValue::UnnamedAddr::Local;
  463. else
  464. UnnamedAddr = GlobalValue::UnnamedAddr::None;
  465. return false;
  466. }
  467. /// ParseUnnamedGlobal:
  468. /// OptionalVisibility (ALIAS | IFUNC) ...
  469. /// OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  470. /// OptionalDLLStorageClass
  471. /// ... -> global variable
  472. /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
  473. /// GlobalID '=' OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  474. /// OptionalDLLStorageClass
  475. /// ... -> global variable
  476. bool LLParser::ParseUnnamedGlobal() {
  477. unsigned VarID = NumberedVals.size();
  478. std::string Name;
  479. LocTy NameLoc = Lex.getLoc();
  480. // Handle the GlobalID form.
  481. if (Lex.getKind() == lltok::GlobalID) {
  482. if (Lex.getUIntVal() != VarID)
  483. return Error(Lex.getLoc(), "variable expected to be numbered '%" +
  484. Twine(VarID) + "'");
  485. Lex.Lex(); // eat GlobalID;
  486. if (ParseToken(lltok::equal, "expected '=' after name"))
  487. return true;
  488. }
  489. bool HasLinkage;
  490. unsigned Linkage, Visibility, DLLStorageClass;
  491. bool DSOLocal;
  492. GlobalVariable::ThreadLocalMode TLM;
  493. GlobalVariable::UnnamedAddr UnnamedAddr;
  494. if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  495. DSOLocal) ||
  496. ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
  497. return true;
  498. if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
  499. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  500. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  501. return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
  502. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  503. }
  504. /// ParseNamedGlobal:
  505. /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
  506. /// GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  507. /// OptionalVisibility OptionalDLLStorageClass
  508. /// ... -> global variable
  509. bool LLParser::ParseNamedGlobal() {
  510. assert(Lex.getKind() == lltok::GlobalVar);
  511. LocTy NameLoc = Lex.getLoc();
  512. std::string Name = Lex.getStrVal();
  513. Lex.Lex();
  514. bool HasLinkage;
  515. unsigned Linkage, Visibility, DLLStorageClass;
  516. bool DSOLocal;
  517. GlobalVariable::ThreadLocalMode TLM;
  518. GlobalVariable::UnnamedAddr UnnamedAddr;
  519. if (ParseToken(lltok::equal, "expected '=' in global variable") ||
  520. ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  521. DSOLocal) ||
  522. ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
  523. return true;
  524. if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
  525. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  526. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  527. return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
  528. DLLStorageClass, DSOLocal, TLM, UnnamedAddr);
  529. }
  530. bool LLParser::parseComdat() {
  531. assert(Lex.getKind() == lltok::ComdatVar);
  532. std::string Name = Lex.getStrVal();
  533. LocTy NameLoc = Lex.getLoc();
  534. Lex.Lex();
  535. if (ParseToken(lltok::equal, "expected '=' here"))
  536. return true;
  537. if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
  538. return TokError("expected comdat type");
  539. Comdat::SelectionKind SK;
  540. switch (Lex.getKind()) {
  541. default:
  542. return TokError("unknown selection kind");
  543. case lltok::kw_any:
  544. SK = Comdat::Any;
  545. break;
  546. case lltok::kw_exactmatch:
  547. SK = Comdat::ExactMatch;
  548. break;
  549. case lltok::kw_largest:
  550. SK = Comdat::Largest;
  551. break;
  552. case lltok::kw_noduplicates:
  553. SK = Comdat::NoDuplicates;
  554. break;
  555. case lltok::kw_samesize:
  556. SK = Comdat::SameSize;
  557. break;
  558. }
  559. Lex.Lex();
  560. // See if the comdat was forward referenced, if so, use the comdat.
  561. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  562. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  563. if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
  564. return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
  565. Comdat *C;
  566. if (I != ComdatSymTab.end())
  567. C = &I->second;
  568. else
  569. C = M->getOrInsertComdat(Name);
  570. C->setSelectionKind(SK);
  571. return false;
  572. }
  573. // MDString:
  574. // ::= '!' STRINGCONSTANT
  575. bool LLParser::ParseMDString(MDString *&Result) {
  576. std::string Str;
  577. if (ParseStringConstant(Str)) return true;
  578. Result = MDString::get(Context, Str);
  579. return false;
  580. }
  581. // MDNode:
  582. // ::= '!' MDNodeNumber
  583. bool LLParser::ParseMDNodeID(MDNode *&Result) {
  584. // !{ ..., !42, ... }
  585. LocTy IDLoc = Lex.getLoc();
  586. unsigned MID = 0;
  587. if (ParseUInt32(MID))
  588. return true;
  589. // If not a forward reference, just return it now.
  590. if (NumberedMetadata.count(MID)) {
  591. Result = NumberedMetadata[MID];
  592. return false;
  593. }
  594. // Otherwise, create MDNode forward reference.
  595. auto &FwdRef = ForwardRefMDNodes[MID];
  596. FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
  597. Result = FwdRef.first.get();
  598. NumberedMetadata[MID].reset(Result);
  599. return false;
  600. }
  601. /// ParseNamedMetadata:
  602. /// !foo = !{ !1, !2 }
  603. bool LLParser::ParseNamedMetadata() {
  604. assert(Lex.getKind() == lltok::MetadataVar);
  605. std::string Name = Lex.getStrVal();
  606. Lex.Lex();
  607. if (ParseToken(lltok::equal, "expected '=' here") ||
  608. ParseToken(lltok::exclaim, "Expected '!' here") ||
  609. ParseToken(lltok::lbrace, "Expected '{' here"))
  610. return true;
  611. NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
  612. if (Lex.getKind() != lltok::rbrace)
  613. do {
  614. MDNode *N = nullptr;
  615. // Parse DIExpressions inline as a special case. They are still MDNodes,
  616. // so they can still appear in named metadata. Remove this logic if they
  617. // become plain Metadata.
  618. if (Lex.getKind() == lltok::MetadataVar &&
  619. Lex.getStrVal() == "DIExpression") {
  620. if (ParseDIExpression(N, /*IsDistinct=*/false))
  621. return true;
  622. } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
  623. ParseMDNodeID(N)) {
  624. return true;
  625. }
  626. NMD->addOperand(N);
  627. } while (EatIfPresent(lltok::comma));
  628. return ParseToken(lltok::rbrace, "expected end of metadata node");
  629. }
  630. /// ParseStandaloneMetadata:
  631. /// !42 = !{...}
  632. bool LLParser::ParseStandaloneMetadata() {
  633. assert(Lex.getKind() == lltok::exclaim);
  634. Lex.Lex();
  635. unsigned MetadataID = 0;
  636. MDNode *Init;
  637. if (ParseUInt32(MetadataID) ||
  638. ParseToken(lltok::equal, "expected '=' here"))
  639. return true;
  640. // Detect common error, from old metadata syntax.
  641. if (Lex.getKind() == lltok::Type)
  642. return TokError("unexpected type in metadata definition");
  643. bool IsDistinct = EatIfPresent(lltok::kw_distinct);
  644. if (Lex.getKind() == lltok::MetadataVar) {
  645. if (ParseSpecializedMDNode(Init, IsDistinct))
  646. return true;
  647. } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
  648. ParseMDTuple(Init, IsDistinct))
  649. return true;
  650. // See if this was forward referenced, if so, handle it.
  651. auto FI = ForwardRefMDNodes.find(MetadataID);
  652. if (FI != ForwardRefMDNodes.end()) {
  653. FI->second.first->replaceAllUsesWith(Init);
  654. ForwardRefMDNodes.erase(FI);
  655. assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
  656. } else {
  657. if (NumberedMetadata.count(MetadataID))
  658. return TokError("Metadata id is already used");
  659. NumberedMetadata[MetadataID].reset(Init);
  660. }
  661. return false;
  662. }
  663. // Skips a single module summary entry.
  664. bool LLParser::SkipModuleSummaryEntry() {
  665. // Each module summary entry consists of a tag for the entry
  666. // type, followed by a colon, then the fields surrounded by nested sets of
  667. // parentheses. The "tag:" looks like a Label. Once parsing support is
  668. // in place we will look for the tokens corresponding to the expected tags.
  669. if (Lex.getKind() != lltok::kw_gv && Lex.getKind() != lltok::kw_module &&
  670. Lex.getKind() != lltok::kw_typeid)
  671. return TokError(
  672. "Expected 'gv', 'module', or 'typeid' at the start of summary entry");
  673. Lex.Lex();
  674. if (ParseToken(lltok::colon, "expected ':' at start of summary entry") ||
  675. ParseToken(lltok::lparen, "expected '(' at start of summary entry"))
  676. return true;
  677. // Now walk through the parenthesized entry, until the number of open
  678. // parentheses goes back down to 0 (the first '(' was parsed above).
  679. unsigned NumOpenParen = 1;
  680. do {
  681. switch (Lex.getKind()) {
  682. case lltok::lparen:
  683. NumOpenParen++;
  684. break;
  685. case lltok::rparen:
  686. NumOpenParen--;
  687. break;
  688. case lltok::Eof:
  689. return TokError("found end of file while parsing summary entry");
  690. default:
  691. // Skip everything in between parentheses.
  692. break;
  693. }
  694. Lex.Lex();
  695. } while (NumOpenParen > 0);
  696. return false;
  697. }
  698. /// SummaryEntry
  699. /// ::= SummaryID '=' GVEntry | ModuleEntry | TypeIdEntry
  700. bool LLParser::ParseSummaryEntry() {
  701. assert(Lex.getKind() == lltok::SummaryID);
  702. unsigned SummaryID = Lex.getUIntVal();
  703. // For summary entries, colons should be treated as distinct tokens,
  704. // not an indication of the end of a label token.
  705. Lex.setIgnoreColonInIdentifiers(true);
  706. Lex.Lex();
  707. if (ParseToken(lltok::equal, "expected '=' here"))
  708. return true;
  709. // If we don't have an index object, skip the summary entry.
  710. if (!Index)
  711. return SkipModuleSummaryEntry();
  712. switch (Lex.getKind()) {
  713. case lltok::kw_gv:
  714. return ParseGVEntry(SummaryID);
  715. case lltok::kw_module:
  716. return ParseModuleEntry(SummaryID);
  717. case lltok::kw_typeid:
  718. return ParseTypeIdEntry(SummaryID);
  719. break;
  720. default:
  721. return Error(Lex.getLoc(), "unexpected summary kind");
  722. }
  723. Lex.setIgnoreColonInIdentifiers(false);
  724. return false;
  725. }
  726. static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
  727. return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
  728. (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
  729. }
  730. // If there was an explicit dso_local, update GV. In the absence of an explicit
  731. // dso_local we keep the default value.
  732. static void maybeSetDSOLocal(bool DSOLocal, GlobalValue &GV) {
  733. if (DSOLocal)
  734. GV.setDSOLocal(true);
  735. }
  736. /// parseIndirectSymbol:
  737. /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  738. /// OptionalVisibility OptionalDLLStorageClass
  739. /// OptionalThreadLocal OptionalUnnamedAddr
  740. // 'alias|ifunc' IndirectSymbol
  741. ///
  742. /// IndirectSymbol
  743. /// ::= TypeAndValue
  744. ///
  745. /// Everything through OptionalUnnamedAddr has already been parsed.
  746. ///
  747. bool LLParser::parseIndirectSymbol(const std::string &Name, LocTy NameLoc,
  748. unsigned L, unsigned Visibility,
  749. unsigned DLLStorageClass, bool DSOLocal,
  750. GlobalVariable::ThreadLocalMode TLM,
  751. GlobalVariable::UnnamedAddr UnnamedAddr) {
  752. bool IsAlias;
  753. if (Lex.getKind() == lltok::kw_alias)
  754. IsAlias = true;
  755. else if (Lex.getKind() == lltok::kw_ifunc)
  756. IsAlias = false;
  757. else
  758. llvm_unreachable("Not an alias or ifunc!");
  759. Lex.Lex();
  760. GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
  761. if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
  762. return Error(NameLoc, "invalid linkage type for alias");
  763. if (!isValidVisibilityForLinkage(Visibility, L))
  764. return Error(NameLoc,
  765. "symbol with local linkage must have default visibility");
  766. Type *Ty;
  767. LocTy ExplicitTypeLoc = Lex.getLoc();
  768. if (ParseType(Ty) ||
  769. ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
  770. return true;
  771. Constant *Aliasee;
  772. LocTy AliaseeLoc = Lex.getLoc();
  773. if (Lex.getKind() != lltok::kw_bitcast &&
  774. Lex.getKind() != lltok::kw_getelementptr &&
  775. Lex.getKind() != lltok::kw_addrspacecast &&
  776. Lex.getKind() != lltok::kw_inttoptr) {
  777. if (ParseGlobalTypeAndValue(Aliasee))
  778. return true;
  779. } else {
  780. // The bitcast dest type is not present, it is implied by the dest type.
  781. ValID ID;
  782. if (ParseValID(ID))
  783. return true;
  784. if (ID.Kind != ValID::t_Constant)
  785. return Error(AliaseeLoc, "invalid aliasee");
  786. Aliasee = ID.ConstantVal;
  787. }
  788. Type *AliaseeType = Aliasee->getType();
  789. auto *PTy = dyn_cast<PointerType>(AliaseeType);
  790. if (!PTy)
  791. return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
  792. unsigned AddrSpace = PTy->getAddressSpace();
  793. if (IsAlias && Ty != PTy->getElementType())
  794. return Error(
  795. ExplicitTypeLoc,
  796. "explicit pointee type doesn't match operand's pointee type");
  797. if (!IsAlias && !PTy->getElementType()->isFunctionTy())
  798. return Error(
  799. ExplicitTypeLoc,
  800. "explicit pointee type should be a function type");
  801. GlobalValue *GVal = nullptr;
  802. // See if the alias was forward referenced, if so, prepare to replace the
  803. // forward reference.
  804. if (!Name.empty()) {
  805. GVal = M->getNamedValue(Name);
  806. if (GVal) {
  807. if (!ForwardRefVals.erase(Name))
  808. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  809. }
  810. } else {
  811. auto I = ForwardRefValIDs.find(NumberedVals.size());
  812. if (I != ForwardRefValIDs.end()) {
  813. GVal = I->second.first;
  814. ForwardRefValIDs.erase(I);
  815. }
  816. }
  817. // Okay, create the alias but do not insert it into the module yet.
  818. std::unique_ptr<GlobalIndirectSymbol> GA;
  819. if (IsAlias)
  820. GA.reset(GlobalAlias::create(Ty, AddrSpace,
  821. (GlobalValue::LinkageTypes)Linkage, Name,
  822. Aliasee, /*Parent*/ nullptr));
  823. else
  824. GA.reset(GlobalIFunc::create(Ty, AddrSpace,
  825. (GlobalValue::LinkageTypes)Linkage, Name,
  826. Aliasee, /*Parent*/ nullptr));
  827. GA->setThreadLocalMode(TLM);
  828. GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  829. GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  830. GA->setUnnamedAddr(UnnamedAddr);
  831. maybeSetDSOLocal(DSOLocal, *GA);
  832. if (Name.empty())
  833. NumberedVals.push_back(GA.get());
  834. if (GVal) {
  835. // Verify that types agree.
  836. if (GVal->getType() != GA->getType())
  837. return Error(
  838. ExplicitTypeLoc,
  839. "forward reference and definition of alias have different types");
  840. // If they agree, just RAUW the old value with the alias and remove the
  841. // forward ref info.
  842. GVal->replaceAllUsesWith(GA.get());
  843. GVal->eraseFromParent();
  844. }
  845. // Insert into the module, we know its name won't collide now.
  846. if (IsAlias)
  847. M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
  848. else
  849. M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
  850. assert(GA->getName() == Name && "Should not be a name conflict!");
  851. // The module owns this now
  852. GA.release();
  853. return false;
  854. }
  855. /// ParseGlobal
  856. /// ::= GlobalVar '=' OptionalLinkage OptionalPreemptionSpecifier
  857. /// OptionalVisibility OptionalDLLStorageClass
  858. /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
  859. /// OptionalExternallyInitialized GlobalType Type Const OptionalAttrs
  860. /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  861. /// OptionalDLLStorageClass OptionalThreadLocal OptionalUnnamedAddr
  862. /// OptionalAddrSpace OptionalExternallyInitialized GlobalType Type
  863. /// Const OptionalAttrs
  864. ///
  865. /// Everything up to and including OptionalUnnamedAddr has been parsed
  866. /// already.
  867. ///
  868. bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
  869. unsigned Linkage, bool HasLinkage,
  870. unsigned Visibility, unsigned DLLStorageClass,
  871. bool DSOLocal, GlobalVariable::ThreadLocalMode TLM,
  872. GlobalVariable::UnnamedAddr UnnamedAddr) {
  873. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  874. return Error(NameLoc,
  875. "symbol with local linkage must have default visibility");
  876. unsigned AddrSpace;
  877. bool IsConstant, IsExternallyInitialized;
  878. LocTy IsExternallyInitializedLoc;
  879. LocTy TyLoc;
  880. Type *Ty = nullptr;
  881. if (ParseOptionalAddrSpace(AddrSpace) ||
  882. ParseOptionalToken(lltok::kw_externally_initialized,
  883. IsExternallyInitialized,
  884. &IsExternallyInitializedLoc) ||
  885. ParseGlobalType(IsConstant) ||
  886. ParseType(Ty, TyLoc))
  887. return true;
  888. // If the linkage is specified and is external, then no initializer is
  889. // present.
  890. Constant *Init = nullptr;
  891. if (!HasLinkage ||
  892. !GlobalValue::isValidDeclarationLinkage(
  893. (GlobalValue::LinkageTypes)Linkage)) {
  894. if (ParseGlobalValue(Ty, Init))
  895. return true;
  896. }
  897. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  898. return Error(TyLoc, "invalid type for global variable");
  899. GlobalValue *GVal = nullptr;
  900. // See if the global was forward referenced, if so, use the global.
  901. if (!Name.empty()) {
  902. GVal = M->getNamedValue(Name);
  903. if (GVal) {
  904. if (!ForwardRefVals.erase(Name))
  905. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  906. }
  907. } else {
  908. auto I = ForwardRefValIDs.find(NumberedVals.size());
  909. if (I != ForwardRefValIDs.end()) {
  910. GVal = I->second.first;
  911. ForwardRefValIDs.erase(I);
  912. }
  913. }
  914. GlobalVariable *GV;
  915. if (!GVal) {
  916. GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
  917. Name, nullptr, GlobalVariable::NotThreadLocal,
  918. AddrSpace);
  919. } else {
  920. if (GVal->getValueType() != Ty)
  921. return Error(TyLoc,
  922. "forward reference and definition of global have different types");
  923. GV = cast<GlobalVariable>(GVal);
  924. // Move the forward-reference to the correct spot in the module.
  925. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
  926. }
  927. if (Name.empty())
  928. NumberedVals.push_back(GV);
  929. // Set the parsed properties on the global.
  930. if (Init)
  931. GV->setInitializer(Init);
  932. GV->setConstant(IsConstant);
  933. GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
  934. maybeSetDSOLocal(DSOLocal, *GV);
  935. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  936. GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  937. GV->setExternallyInitialized(IsExternallyInitialized);
  938. GV->setThreadLocalMode(TLM);
  939. GV->setUnnamedAddr(UnnamedAddr);
  940. // Parse attributes on the global.
  941. while (Lex.getKind() == lltok::comma) {
  942. Lex.Lex();
  943. if (Lex.getKind() == lltok::kw_section) {
  944. Lex.Lex();
  945. GV->setSection(Lex.getStrVal());
  946. if (ParseToken(lltok::StringConstant, "expected global section string"))
  947. return true;
  948. } else if (Lex.getKind() == lltok::kw_align) {
  949. unsigned Alignment;
  950. if (ParseOptionalAlignment(Alignment)) return true;
  951. GV->setAlignment(Alignment);
  952. } else if (Lex.getKind() == lltok::MetadataVar) {
  953. if (ParseGlobalObjectMetadataAttachment(*GV))
  954. return true;
  955. } else {
  956. Comdat *C;
  957. if (parseOptionalComdat(Name, C))
  958. return true;
  959. if (C)
  960. GV->setComdat(C);
  961. else
  962. return TokError("unknown global variable property!");
  963. }
  964. }
  965. AttrBuilder Attrs;
  966. LocTy BuiltinLoc;
  967. std::vector<unsigned> FwdRefAttrGrps;
  968. if (ParseFnAttributeValuePairs(Attrs, FwdRefAttrGrps, false, BuiltinLoc))
  969. return true;
  970. if (Attrs.hasAttributes() || !FwdRefAttrGrps.empty()) {
  971. GV->setAttributes(AttributeSet::get(Context, Attrs));
  972. ForwardRefAttrGroups[GV] = FwdRefAttrGrps;
  973. }
  974. return false;
  975. }
  976. /// ParseUnnamedAttrGrp
  977. /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
  978. bool LLParser::ParseUnnamedAttrGrp() {
  979. assert(Lex.getKind() == lltok::kw_attributes);
  980. LocTy AttrGrpLoc = Lex.getLoc();
  981. Lex.Lex();
  982. if (Lex.getKind() != lltok::AttrGrpID)
  983. return TokError("expected attribute group id");
  984. unsigned VarID = Lex.getUIntVal();
  985. std::vector<unsigned> unused;
  986. LocTy BuiltinLoc;
  987. Lex.Lex();
  988. if (ParseToken(lltok::equal, "expected '=' here") ||
  989. ParseToken(lltok::lbrace, "expected '{' here") ||
  990. ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
  991. BuiltinLoc) ||
  992. ParseToken(lltok::rbrace, "expected end of attribute group"))
  993. return true;
  994. if (!NumberedAttrBuilders[VarID].hasAttributes())
  995. return Error(AttrGrpLoc, "attribute group has no attributes");
  996. return false;
  997. }
  998. /// ParseFnAttributeValuePairs
  999. /// ::= <attr> | <attr> '=' <value>
  1000. bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
  1001. std::vector<unsigned> &FwdRefAttrGrps,
  1002. bool inAttrGrp, LocTy &BuiltinLoc) {
  1003. bool HaveError = false;
  1004. B.clear();
  1005. while (true) {
  1006. lltok::Kind Token = Lex.getKind();
  1007. if (Token == lltok::kw_builtin)
  1008. BuiltinLoc = Lex.getLoc();
  1009. switch (Token) {
  1010. default:
  1011. if (!inAttrGrp) return HaveError;
  1012. return Error(Lex.getLoc(), "unterminated attribute group");
  1013. case lltok::rbrace:
  1014. // Finished.
  1015. return false;
  1016. case lltok::AttrGrpID: {
  1017. // Allow a function to reference an attribute group:
  1018. //
  1019. // define void @foo() #1 { ... }
  1020. if (inAttrGrp)
  1021. HaveError |=
  1022. Error(Lex.getLoc(),
  1023. "cannot have an attribute group reference in an attribute group");
  1024. unsigned AttrGrpNum = Lex.getUIntVal();
  1025. if (inAttrGrp) break;
  1026. // Save the reference to the attribute group. We'll fill it in later.
  1027. FwdRefAttrGrps.push_back(AttrGrpNum);
  1028. break;
  1029. }
  1030. // Target-dependent attributes:
  1031. case lltok::StringConstant: {
  1032. if (ParseStringAttribute(B))
  1033. return true;
  1034. continue;
  1035. }
  1036. // Target-independent attributes:
  1037. case lltok::kw_align: {
  1038. // As a hack, we allow function alignment to be initially parsed as an
  1039. // attribute on a function declaration/definition or added to an attribute
  1040. // group and later moved to the alignment field.
  1041. unsigned Alignment;
  1042. if (inAttrGrp) {
  1043. Lex.Lex();
  1044. if (ParseToken(lltok::equal, "expected '=' here") ||
  1045. ParseUInt32(Alignment))
  1046. return true;
  1047. } else {
  1048. if (ParseOptionalAlignment(Alignment))
  1049. return true;
  1050. }
  1051. B.addAlignmentAttr(Alignment);
  1052. continue;
  1053. }
  1054. case lltok::kw_alignstack: {
  1055. unsigned Alignment;
  1056. if (inAttrGrp) {
  1057. Lex.Lex();
  1058. if (ParseToken(lltok::equal, "expected '=' here") ||
  1059. ParseUInt32(Alignment))
  1060. return true;
  1061. } else {
  1062. if (ParseOptionalStackAlignment(Alignment))
  1063. return true;
  1064. }
  1065. B.addStackAlignmentAttr(Alignment);
  1066. continue;
  1067. }
  1068. case lltok::kw_allocsize: {
  1069. unsigned ElemSizeArg;
  1070. Optional<unsigned> NumElemsArg;
  1071. // inAttrGrp doesn't matter; we only support allocsize(a[, b])
  1072. if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
  1073. return true;
  1074. B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
  1075. continue;
  1076. }
  1077. case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
  1078. case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
  1079. case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
  1080. case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
  1081. case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
  1082. case lltok::kw_inaccessiblememonly:
  1083. B.addAttribute(Attribute::InaccessibleMemOnly); break;
  1084. case lltok::kw_inaccessiblemem_or_argmemonly:
  1085. B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
  1086. case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
  1087. case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
  1088. case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
  1089. case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
  1090. case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
  1091. case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
  1092. case lltok::kw_noimplicitfloat:
  1093. B.addAttribute(Attribute::NoImplicitFloat); break;
  1094. case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
  1095. case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
  1096. case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
  1097. case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
  1098. case lltok::kw_nocf_check: B.addAttribute(Attribute::NoCfCheck); break;
  1099. case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
  1100. case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
  1101. case lltok::kw_optforfuzzing:
  1102. B.addAttribute(Attribute::OptForFuzzing); break;
  1103. case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
  1104. case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
  1105. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  1106. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  1107. case lltok::kw_returns_twice:
  1108. B.addAttribute(Attribute::ReturnsTwice); break;
  1109. case lltok::kw_speculatable: B.addAttribute(Attribute::Speculatable); break;
  1110. case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
  1111. case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
  1112. case lltok::kw_sspstrong:
  1113. B.addAttribute(Attribute::StackProtectStrong); break;
  1114. case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
  1115. case lltok::kw_shadowcallstack:
  1116. B.addAttribute(Attribute::ShadowCallStack); break;
  1117. case lltok::kw_sanitize_address:
  1118. B.addAttribute(Attribute::SanitizeAddress); break;
  1119. case lltok::kw_sanitize_hwaddress:
  1120. B.addAttribute(Attribute::SanitizeHWAddress); break;
  1121. case lltok::kw_sanitize_thread:
  1122. B.addAttribute(Attribute::SanitizeThread); break;
  1123. case lltok::kw_sanitize_memory:
  1124. B.addAttribute(Attribute::SanitizeMemory); break;
  1125. case lltok::kw_speculative_load_hardening:
  1126. B.addAttribute(Attribute::SpeculativeLoadHardening);
  1127. break;
  1128. case lltok::kw_strictfp: B.addAttribute(Attribute::StrictFP); break;
  1129. case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
  1130. case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
  1131. // Error handling.
  1132. case lltok::kw_inreg:
  1133. case lltok::kw_signext:
  1134. case lltok::kw_zeroext:
  1135. HaveError |=
  1136. Error(Lex.getLoc(),
  1137. "invalid use of attribute on a function");
  1138. break;
  1139. case lltok::kw_byval:
  1140. case lltok::kw_dereferenceable:
  1141. case lltok::kw_dereferenceable_or_null:
  1142. case lltok::kw_inalloca:
  1143. case lltok::kw_nest:
  1144. case lltok::kw_noalias:
  1145. case lltok::kw_nocapture:
  1146. case lltok::kw_nonnull:
  1147. case lltok::kw_returned:
  1148. case lltok::kw_sret:
  1149. case lltok::kw_swifterror:
  1150. case lltok::kw_swiftself:
  1151. HaveError |=
  1152. Error(Lex.getLoc(),
  1153. "invalid use of parameter-only attribute on a function");
  1154. break;
  1155. }
  1156. Lex.Lex();
  1157. }
  1158. }
  1159. //===----------------------------------------------------------------------===//
  1160. // GlobalValue Reference/Resolution Routines.
  1161. //===----------------------------------------------------------------------===//
  1162. static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
  1163. const std::string &Name) {
  1164. if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
  1165. return Function::Create(FT, GlobalValue::ExternalWeakLinkage,
  1166. PTy->getAddressSpace(), Name, M);
  1167. else
  1168. return new GlobalVariable(*M, PTy->getElementType(), false,
  1169. GlobalValue::ExternalWeakLinkage, nullptr, Name,
  1170. nullptr, GlobalVariable::NotThreadLocal,
  1171. PTy->getAddressSpace());
  1172. }
  1173. Value *LLParser::checkValidVariableType(LocTy Loc, const Twine &Name, Type *Ty,
  1174. Value *Val, bool IsCall) {
  1175. if (Val->getType() == Ty)
  1176. return Val;
  1177. // For calls we also accept variables in the program address space.
  1178. Type *SuggestedTy = Ty;
  1179. if (IsCall && isa<PointerType>(Ty)) {
  1180. Type *TyInProgAS = cast<PointerType>(Ty)->getElementType()->getPointerTo(
  1181. M->getDataLayout().getProgramAddressSpace());
  1182. SuggestedTy = TyInProgAS;
  1183. if (Val->getType() == TyInProgAS)
  1184. return Val;
  1185. }
  1186. if (Ty->isLabelTy())
  1187. Error(Loc, "'" + Name + "' is not a basic block");
  1188. else
  1189. Error(Loc, "'" + Name + "' defined with type '" +
  1190. getTypeString(Val->getType()) + "' but expected '" +
  1191. getTypeString(SuggestedTy) + "'");
  1192. return nullptr;
  1193. }
  1194. /// GetGlobalVal - Get a value with the specified name or ID, creating a
  1195. /// forward reference record if needed. This can return null if the value
  1196. /// exists but does not have the right type.
  1197. GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
  1198. LocTy Loc, bool IsCall) {
  1199. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1200. if (!PTy) {
  1201. Error(Loc, "global variable reference must have pointer type");
  1202. return nullptr;
  1203. }
  1204. // Look this name up in the normal function symbol table.
  1205. GlobalValue *Val =
  1206. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
  1207. // If this is a forward reference for the value, see if we already created a
  1208. // forward ref record.
  1209. if (!Val) {
  1210. auto I = ForwardRefVals.find(Name);
  1211. if (I != ForwardRefVals.end())
  1212. Val = I->second.first;
  1213. }
  1214. // If we have the value in the symbol table or fwd-ref table, return it.
  1215. if (Val)
  1216. return cast_or_null<GlobalValue>(
  1217. checkValidVariableType(Loc, "@" + Name, Ty, Val, IsCall));
  1218. // Otherwise, create a new forward reference for this value and remember it.
  1219. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
  1220. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  1221. return FwdVal;
  1222. }
  1223. GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc,
  1224. bool IsCall) {
  1225. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1226. if (!PTy) {
  1227. Error(Loc, "global variable reference must have pointer type");
  1228. return nullptr;
  1229. }
  1230. GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  1231. // If this is a forward reference for the value, see if we already created a
  1232. // forward ref record.
  1233. if (!Val) {
  1234. auto I = ForwardRefValIDs.find(ID);
  1235. if (I != ForwardRefValIDs.end())
  1236. Val = I->second.first;
  1237. }
  1238. // If we have the value in the symbol table or fwd-ref table, return it.
  1239. if (Val)
  1240. return cast_or_null<GlobalValue>(
  1241. checkValidVariableType(Loc, "@" + Twine(ID), Ty, Val, IsCall));
  1242. // Otherwise, create a new forward reference for this value and remember it.
  1243. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
  1244. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  1245. return FwdVal;
  1246. }
  1247. //===----------------------------------------------------------------------===//
  1248. // Comdat Reference/Resolution Routines.
  1249. //===----------------------------------------------------------------------===//
  1250. Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
  1251. // Look this name up in the comdat symbol table.
  1252. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  1253. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  1254. if (I != ComdatSymTab.end())
  1255. return &I->second;
  1256. // Otherwise, create a new forward reference for this value and remember it.
  1257. Comdat *C = M->getOrInsertComdat(Name);
  1258. ForwardRefComdats[Name] = Loc;
  1259. return C;
  1260. }
  1261. //===----------------------------------------------------------------------===//
  1262. // Helper Routines.
  1263. //===----------------------------------------------------------------------===//
  1264. /// ParseToken - If the current token has the specified kind, eat it and return
  1265. /// success. Otherwise, emit the specified error and return failure.
  1266. bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
  1267. if (Lex.getKind() != T)
  1268. return TokError(ErrMsg);
  1269. Lex.Lex();
  1270. return false;
  1271. }
  1272. /// ParseStringConstant
  1273. /// ::= StringConstant
  1274. bool LLParser::ParseStringConstant(std::string &Result) {
  1275. if (Lex.getKind() != lltok::StringConstant)
  1276. return TokError("expected string constant");
  1277. Result = Lex.getStrVal();
  1278. Lex.Lex();
  1279. return false;
  1280. }
  1281. /// ParseUInt32
  1282. /// ::= uint32
  1283. bool LLParser::ParseUInt32(uint32_t &Val) {
  1284. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1285. return TokError("expected integer");
  1286. uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
  1287. if (Val64 != unsigned(Val64))
  1288. return TokError("expected 32-bit integer (too large)");
  1289. Val = Val64;
  1290. Lex.Lex();
  1291. return false;
  1292. }
  1293. /// ParseUInt64
  1294. /// ::= uint64
  1295. bool LLParser::ParseUInt64(uint64_t &Val) {
  1296. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1297. return TokError("expected integer");
  1298. Val = Lex.getAPSIntVal().getLimitedValue();
  1299. Lex.Lex();
  1300. return false;
  1301. }
  1302. /// ParseTLSModel
  1303. /// := 'localdynamic'
  1304. /// := 'initialexec'
  1305. /// := 'localexec'
  1306. bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
  1307. switch (Lex.getKind()) {
  1308. default:
  1309. return TokError("expected localdynamic, initialexec or localexec");
  1310. case lltok::kw_localdynamic:
  1311. TLM = GlobalVariable::LocalDynamicTLSModel;
  1312. break;
  1313. case lltok::kw_initialexec:
  1314. TLM = GlobalVariable::InitialExecTLSModel;
  1315. break;
  1316. case lltok::kw_localexec:
  1317. TLM = GlobalVariable::LocalExecTLSModel;
  1318. break;
  1319. }
  1320. Lex.Lex();
  1321. return false;
  1322. }
  1323. /// ParseOptionalThreadLocal
  1324. /// := /*empty*/
  1325. /// := 'thread_local'
  1326. /// := 'thread_local' '(' tlsmodel ')'
  1327. bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
  1328. TLM = GlobalVariable::NotThreadLocal;
  1329. if (!EatIfPresent(lltok::kw_thread_local))
  1330. return false;
  1331. TLM = GlobalVariable::GeneralDynamicTLSModel;
  1332. if (Lex.getKind() == lltok::lparen) {
  1333. Lex.Lex();
  1334. return ParseTLSModel(TLM) ||
  1335. ParseToken(lltok::rparen, "expected ')' after thread local model");
  1336. }
  1337. return false;
  1338. }
  1339. /// ParseOptionalAddrSpace
  1340. /// := /*empty*/
  1341. /// := 'addrspace' '(' uint32 ')'
  1342. bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace, unsigned DefaultAS) {
  1343. AddrSpace = DefaultAS;
  1344. if (!EatIfPresent(lltok::kw_addrspace))
  1345. return false;
  1346. return ParseToken(lltok::lparen, "expected '(' in address space") ||
  1347. ParseUInt32(AddrSpace) ||
  1348. ParseToken(lltok::rparen, "expected ')' in address space");
  1349. }
  1350. /// ParseStringAttribute
  1351. /// := StringConstant
  1352. /// := StringConstant '=' StringConstant
  1353. bool LLParser::ParseStringAttribute(AttrBuilder &B) {
  1354. std::string Attr = Lex.getStrVal();
  1355. Lex.Lex();
  1356. std::string Val;
  1357. if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
  1358. return true;
  1359. B.addAttribute(Attr, Val);
  1360. return false;
  1361. }
  1362. /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
  1363. bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
  1364. bool HaveError = false;
  1365. B.clear();
  1366. while (true) {
  1367. lltok::Kind Token = Lex.getKind();
  1368. switch (Token) {
  1369. default: // End of attributes.
  1370. return HaveError;
  1371. case lltok::StringConstant: {
  1372. if (ParseStringAttribute(B))
  1373. return true;
  1374. continue;
  1375. }
  1376. case lltok::kw_align: {
  1377. unsigned Alignment;
  1378. if (ParseOptionalAlignment(Alignment))
  1379. return true;
  1380. B.addAlignmentAttr(Alignment);
  1381. continue;
  1382. }
  1383. case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
  1384. case lltok::kw_dereferenceable: {
  1385. uint64_t Bytes;
  1386. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
  1387. return true;
  1388. B.addDereferenceableAttr(Bytes);
  1389. continue;
  1390. }
  1391. case lltok::kw_dereferenceable_or_null: {
  1392. uint64_t Bytes;
  1393. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
  1394. return true;
  1395. B.addDereferenceableOrNullAttr(Bytes);
  1396. continue;
  1397. }
  1398. case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
  1399. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1400. case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
  1401. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1402. case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
  1403. case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
  1404. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  1405. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  1406. case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
  1407. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1408. case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
  1409. case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
  1410. case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
  1411. case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
  1412. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1413. case lltok::kw_alignstack:
  1414. case lltok::kw_alwaysinline:
  1415. case lltok::kw_argmemonly:
  1416. case lltok::kw_builtin:
  1417. case lltok::kw_inlinehint:
  1418. case lltok::kw_jumptable:
  1419. case lltok::kw_minsize:
  1420. case lltok::kw_naked:
  1421. case lltok::kw_nobuiltin:
  1422. case lltok::kw_noduplicate:
  1423. case lltok::kw_noimplicitfloat:
  1424. case lltok::kw_noinline:
  1425. case lltok::kw_nonlazybind:
  1426. case lltok::kw_noredzone:
  1427. case lltok::kw_noreturn:
  1428. case lltok::kw_nocf_check:
  1429. case lltok::kw_nounwind:
  1430. case lltok::kw_optforfuzzing:
  1431. case lltok::kw_optnone:
  1432. case lltok::kw_optsize:
  1433. case lltok::kw_returns_twice:
  1434. case lltok::kw_sanitize_address:
  1435. case lltok::kw_sanitize_hwaddress:
  1436. case lltok::kw_sanitize_memory:
  1437. case lltok::kw_sanitize_thread:
  1438. case lltok::kw_speculative_load_hardening:
  1439. case lltok::kw_ssp:
  1440. case lltok::kw_sspreq:
  1441. case lltok::kw_sspstrong:
  1442. case lltok::kw_safestack:
  1443. case lltok::kw_shadowcallstack:
  1444. case lltok::kw_strictfp:
  1445. case lltok::kw_uwtable:
  1446. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1447. break;
  1448. }
  1449. Lex.Lex();
  1450. }
  1451. }
  1452. /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
  1453. bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
  1454. bool HaveError = false;
  1455. B.clear();
  1456. while (true) {
  1457. lltok::Kind Token = Lex.getKind();
  1458. switch (Token) {
  1459. default: // End of attributes.
  1460. return HaveError;
  1461. case lltok::StringConstant: {
  1462. if (ParseStringAttribute(B))
  1463. return true;
  1464. continue;
  1465. }
  1466. case lltok::kw_dereferenceable: {
  1467. uint64_t Bytes;
  1468. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
  1469. return true;
  1470. B.addDereferenceableAttr(Bytes);
  1471. continue;
  1472. }
  1473. case lltok::kw_dereferenceable_or_null: {
  1474. uint64_t Bytes;
  1475. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
  1476. return true;
  1477. B.addDereferenceableOrNullAttr(Bytes);
  1478. continue;
  1479. }
  1480. case lltok::kw_align: {
  1481. unsigned Alignment;
  1482. if (ParseOptionalAlignment(Alignment))
  1483. return true;
  1484. B.addAlignmentAttr(Alignment);
  1485. continue;
  1486. }
  1487. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1488. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1489. case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
  1490. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1491. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1492. // Error handling.
  1493. case lltok::kw_byval:
  1494. case lltok::kw_inalloca:
  1495. case lltok::kw_nest:
  1496. case lltok::kw_nocapture:
  1497. case lltok::kw_returned:
  1498. case lltok::kw_sret:
  1499. case lltok::kw_swifterror:
  1500. case lltok::kw_swiftself:
  1501. HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
  1502. break;
  1503. case lltok::kw_alignstack:
  1504. case lltok::kw_alwaysinline:
  1505. case lltok::kw_argmemonly:
  1506. case lltok::kw_builtin:
  1507. case lltok::kw_cold:
  1508. case lltok::kw_inlinehint:
  1509. case lltok::kw_jumptable:
  1510. case lltok::kw_minsize:
  1511. case lltok::kw_naked:
  1512. case lltok::kw_nobuiltin:
  1513. case lltok::kw_noduplicate:
  1514. case lltok::kw_noimplicitfloat:
  1515. case lltok::kw_noinline:
  1516. case lltok::kw_nonlazybind:
  1517. case lltok::kw_noredzone:
  1518. case lltok::kw_noreturn:
  1519. case lltok::kw_nocf_check:
  1520. case lltok::kw_nounwind:
  1521. case lltok::kw_optforfuzzing:
  1522. case lltok::kw_optnone:
  1523. case lltok::kw_optsize:
  1524. case lltok::kw_returns_twice:
  1525. case lltok::kw_sanitize_address:
  1526. case lltok::kw_sanitize_hwaddress:
  1527. case lltok::kw_sanitize_memory:
  1528. case lltok::kw_sanitize_thread:
  1529. case lltok::kw_speculative_load_hardening:
  1530. case lltok::kw_ssp:
  1531. case lltok::kw_sspreq:
  1532. case lltok::kw_sspstrong:
  1533. case lltok::kw_safestack:
  1534. case lltok::kw_shadowcallstack:
  1535. case lltok::kw_strictfp:
  1536. case lltok::kw_uwtable:
  1537. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1538. break;
  1539. case lltok::kw_readnone:
  1540. case lltok::kw_readonly:
  1541. HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
  1542. }
  1543. Lex.Lex();
  1544. }
  1545. }
  1546. static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
  1547. HasLinkage = true;
  1548. switch (Kind) {
  1549. default:
  1550. HasLinkage = false;
  1551. return GlobalValue::ExternalLinkage;
  1552. case lltok::kw_private:
  1553. return GlobalValue::PrivateLinkage;
  1554. case lltok::kw_internal:
  1555. return GlobalValue::InternalLinkage;
  1556. case lltok::kw_weak:
  1557. return GlobalValue::WeakAnyLinkage;
  1558. case lltok::kw_weak_odr:
  1559. return GlobalValue::WeakODRLinkage;
  1560. case lltok::kw_linkonce:
  1561. return GlobalValue::LinkOnceAnyLinkage;
  1562. case lltok::kw_linkonce_odr:
  1563. return GlobalValue::LinkOnceODRLinkage;
  1564. case lltok::kw_available_externally:
  1565. return GlobalValue::AvailableExternallyLinkage;
  1566. case lltok::kw_appending:
  1567. return GlobalValue::AppendingLinkage;
  1568. case lltok::kw_common:
  1569. return GlobalValue::CommonLinkage;
  1570. case lltok::kw_extern_weak:
  1571. return GlobalValue::ExternalWeakLinkage;
  1572. case lltok::kw_external:
  1573. return GlobalValue::ExternalLinkage;
  1574. }
  1575. }
  1576. /// ParseOptionalLinkage
  1577. /// ::= /*empty*/
  1578. /// ::= 'private'
  1579. /// ::= 'internal'
  1580. /// ::= 'weak'
  1581. /// ::= 'weak_odr'
  1582. /// ::= 'linkonce'
  1583. /// ::= 'linkonce_odr'
  1584. /// ::= 'available_externally'
  1585. /// ::= 'appending'
  1586. /// ::= 'common'
  1587. /// ::= 'extern_weak'
  1588. /// ::= 'external'
  1589. bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
  1590. unsigned &Visibility,
  1591. unsigned &DLLStorageClass,
  1592. bool &DSOLocal) {
  1593. Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
  1594. if (HasLinkage)
  1595. Lex.Lex();
  1596. ParseOptionalDSOLocal(DSOLocal);
  1597. ParseOptionalVisibility(Visibility);
  1598. ParseOptionalDLLStorageClass(DLLStorageClass);
  1599. if (DSOLocal && DLLStorageClass == GlobalValue::DLLImportStorageClass) {
  1600. return Error(Lex.getLoc(), "dso_location and DLL-StorageClass mismatch");
  1601. }
  1602. return false;
  1603. }
  1604. void LLParser::ParseOptionalDSOLocal(bool &DSOLocal) {
  1605. switch (Lex.getKind()) {
  1606. default:
  1607. DSOLocal = false;
  1608. break;
  1609. case lltok::kw_dso_local:
  1610. DSOLocal = true;
  1611. Lex.Lex();
  1612. break;
  1613. case lltok::kw_dso_preemptable:
  1614. DSOLocal = false;
  1615. Lex.Lex();
  1616. break;
  1617. }
  1618. }
  1619. /// ParseOptionalVisibility
  1620. /// ::= /*empty*/
  1621. /// ::= 'default'
  1622. /// ::= 'hidden'
  1623. /// ::= 'protected'
  1624. ///
  1625. void LLParser::ParseOptionalVisibility(unsigned &Res) {
  1626. switch (Lex.getKind()) {
  1627. default:
  1628. Res = GlobalValue::DefaultVisibility;
  1629. return;
  1630. case lltok::kw_default:
  1631. Res = GlobalValue::DefaultVisibility;
  1632. break;
  1633. case lltok::kw_hidden:
  1634. Res = GlobalValue::HiddenVisibility;
  1635. break;
  1636. case lltok::kw_protected:
  1637. Res = GlobalValue::ProtectedVisibility;
  1638. break;
  1639. }
  1640. Lex.Lex();
  1641. }
  1642. /// ParseOptionalDLLStorageClass
  1643. /// ::= /*empty*/
  1644. /// ::= 'dllimport'
  1645. /// ::= 'dllexport'
  1646. ///
  1647. void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
  1648. switch (Lex.getKind()) {
  1649. default:
  1650. Res = GlobalValue::DefaultStorageClass;
  1651. return;
  1652. case lltok::kw_dllimport:
  1653. Res = GlobalValue::DLLImportStorageClass;
  1654. break;
  1655. case lltok::kw_dllexport:
  1656. Res = GlobalValue::DLLExportStorageClass;
  1657. break;
  1658. }
  1659. Lex.Lex();
  1660. }
  1661. /// ParseOptionalCallingConv
  1662. /// ::= /*empty*/
  1663. /// ::= 'ccc'
  1664. /// ::= 'fastcc'
  1665. /// ::= 'intel_ocl_bicc'
  1666. /// ::= 'coldcc'
  1667. /// ::= 'x86_stdcallcc'
  1668. /// ::= 'x86_fastcallcc'
  1669. /// ::= 'x86_thiscallcc'
  1670. /// ::= 'x86_vectorcallcc'
  1671. /// ::= 'arm_apcscc'
  1672. /// ::= 'arm_aapcscc'
  1673. /// ::= 'arm_aapcs_vfpcc'
  1674. /// ::= 'aarch64_vector_pcs'
  1675. /// ::= 'msp430_intrcc'
  1676. /// ::= 'avr_intrcc'
  1677. /// ::= 'avr_signalcc'
  1678. /// ::= 'ptx_kernel'
  1679. /// ::= 'ptx_device'
  1680. /// ::= 'spir_func'
  1681. /// ::= 'spir_kernel'
  1682. /// ::= 'x86_64_sysvcc'
  1683. /// ::= 'win64cc'
  1684. /// ::= 'webkit_jscc'
  1685. /// ::= 'anyregcc'
  1686. /// ::= 'preserve_mostcc'
  1687. /// ::= 'preserve_allcc'
  1688. /// ::= 'ghccc'
  1689. /// ::= 'swiftcc'
  1690. /// ::= 'x86_intrcc'
  1691. /// ::= 'hhvmcc'
  1692. /// ::= 'hhvm_ccc'
  1693. /// ::= 'cxx_fast_tlscc'
  1694. /// ::= 'amdgpu_vs'
  1695. /// ::= 'amdgpu_ls'
  1696. /// ::= 'amdgpu_hs'
  1697. /// ::= 'amdgpu_es'
  1698. /// ::= 'amdgpu_gs'
  1699. /// ::= 'amdgpu_ps'
  1700. /// ::= 'amdgpu_cs'
  1701. /// ::= 'amdgpu_kernel'
  1702. /// ::= 'cc' UINT
  1703. ///
  1704. bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
  1705. switch (Lex.getKind()) {
  1706. default: CC = CallingConv::C; return false;
  1707. case lltok::kw_ccc: CC = CallingConv::C; break;
  1708. case lltok::kw_fastcc: CC = CallingConv::Fast; break;
  1709. case lltok::kw_coldcc: CC = CallingConv::Cold; break;
  1710. case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
  1711. case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
  1712. case lltok::kw_x86_regcallcc: CC = CallingConv::X86_RegCall; break;
  1713. case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
  1714. case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
  1715. case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
  1716. case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
  1717. case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
  1718. case lltok::kw_aarch64_vector_pcs:CC = CallingConv::AArch64_VectorCall; break;
  1719. case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
  1720. case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
  1721. case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
  1722. case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
  1723. case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
  1724. case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
  1725. case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
  1726. case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
  1727. case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
  1728. case lltok::kw_win64cc: CC = CallingConv::Win64; break;
  1729. case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
  1730. case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
  1731. case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
  1732. case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
  1733. case lltok::kw_ghccc: CC = CallingConv::GHC; break;
  1734. case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
  1735. case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
  1736. case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
  1737. case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
  1738. case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
  1739. case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
  1740. case lltok::kw_amdgpu_ls: CC = CallingConv::AMDGPU_LS; break;
  1741. case lltok::kw_amdgpu_hs: CC = CallingConv::AMDGPU_HS; break;
  1742. case lltok::kw_amdgpu_es: CC = CallingConv::AMDGPU_ES; break;
  1743. case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
  1744. case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
  1745. case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
  1746. case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
  1747. case lltok::kw_cc: {
  1748. Lex.Lex();
  1749. return ParseUInt32(CC);
  1750. }
  1751. }
  1752. Lex.Lex();
  1753. return false;
  1754. }
  1755. /// ParseMetadataAttachment
  1756. /// ::= !dbg !42
  1757. bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
  1758. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
  1759. std::string Name = Lex.getStrVal();
  1760. Kind = M->getMDKindID(Name);
  1761. Lex.Lex();
  1762. return ParseMDNode(MD);
  1763. }
  1764. /// ParseInstructionMetadata
  1765. /// ::= !dbg !42 (',' !dbg !57)*
  1766. bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
  1767. do {
  1768. if (Lex.getKind() != lltok::MetadataVar)
  1769. return TokError("expected metadata after comma");
  1770. unsigned MDK;
  1771. MDNode *N;
  1772. if (ParseMetadataAttachment(MDK, N))
  1773. return true;
  1774. Inst.setMetadata(MDK, N);
  1775. if (MDK == LLVMContext::MD_tbaa)
  1776. InstsWithTBAATag.push_back(&Inst);
  1777. // If this is the end of the list, we're done.
  1778. } while (EatIfPresent(lltok::comma));
  1779. return false;
  1780. }
  1781. /// ParseGlobalObjectMetadataAttachment
  1782. /// ::= !dbg !57
  1783. bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
  1784. unsigned MDK;
  1785. MDNode *N;
  1786. if (ParseMetadataAttachment(MDK, N))
  1787. return true;
  1788. GO.addMetadata(MDK, *N);
  1789. return false;
  1790. }
  1791. /// ParseOptionalFunctionMetadata
  1792. /// ::= (!dbg !57)*
  1793. bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
  1794. while (Lex.getKind() == lltok::MetadataVar)
  1795. if (ParseGlobalObjectMetadataAttachment(F))
  1796. return true;
  1797. return false;
  1798. }
  1799. /// ParseOptionalAlignment
  1800. /// ::= /* empty */
  1801. /// ::= 'align' 4
  1802. bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
  1803. Alignment = 0;
  1804. if (!EatIfPresent(lltok::kw_align))
  1805. return false;
  1806. LocTy AlignLoc = Lex.getLoc();
  1807. if (ParseUInt32(Alignment)) return true;
  1808. if (!isPowerOf2_32(Alignment))
  1809. return Error(AlignLoc, "alignment is not a power of two");
  1810. if (Alignment > Value::MaximumAlignment)
  1811. return Error(AlignLoc, "huge alignments are not supported yet");
  1812. return false;
  1813. }
  1814. /// ParseOptionalDerefAttrBytes
  1815. /// ::= /* empty */
  1816. /// ::= AttrKind '(' 4 ')'
  1817. ///
  1818. /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
  1819. bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
  1820. uint64_t &Bytes) {
  1821. assert((AttrKind == lltok::kw_dereferenceable ||
  1822. AttrKind == lltok::kw_dereferenceable_or_null) &&
  1823. "contract!");
  1824. Bytes = 0;
  1825. if (!EatIfPresent(AttrKind))
  1826. return false;
  1827. LocTy ParenLoc = Lex.getLoc();
  1828. if (!EatIfPresent(lltok::lparen))
  1829. return Error(ParenLoc, "expected '('");
  1830. LocTy DerefLoc = Lex.getLoc();
  1831. if (ParseUInt64(Bytes)) return true;
  1832. ParenLoc = Lex.getLoc();
  1833. if (!EatIfPresent(lltok::rparen))
  1834. return Error(ParenLoc, "expected ')'");
  1835. if (!Bytes)
  1836. return Error(DerefLoc, "dereferenceable bytes must be non-zero");
  1837. return false;
  1838. }
  1839. /// ParseOptionalCommaAlign
  1840. /// ::=
  1841. /// ::= ',' align 4
  1842. ///
  1843. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  1844. /// end.
  1845. bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
  1846. bool &AteExtraComma) {
  1847. AteExtraComma = false;
  1848. while (EatIfPresent(lltok::comma)) {
  1849. // Metadata at the end is an early exit.
  1850. if (Lex.getKind() == lltok::MetadataVar) {
  1851. AteExtraComma = true;
  1852. return false;
  1853. }
  1854. if (Lex.getKind() != lltok::kw_align)
  1855. return Error(Lex.getLoc(), "expected metadata or 'align'");
  1856. if (ParseOptionalAlignment(Alignment)) return true;
  1857. }
  1858. return false;
  1859. }
  1860. /// ParseOptionalCommaAddrSpace
  1861. /// ::=
  1862. /// ::= ',' addrspace(1)
  1863. ///
  1864. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  1865. /// end.
  1866. bool LLParser::ParseOptionalCommaAddrSpace(unsigned &AddrSpace,
  1867. LocTy &Loc,
  1868. bool &AteExtraComma) {
  1869. AteExtraComma = false;
  1870. while (EatIfPresent(lltok::comma)) {
  1871. // Metadata at the end is an early exit.
  1872. if (Lex.getKind() == lltok::MetadataVar) {
  1873. AteExtraComma = true;
  1874. return false;
  1875. }
  1876. Loc = Lex.getLoc();
  1877. if (Lex.getKind() != lltok::kw_addrspace)
  1878. return Error(Lex.getLoc(), "expected metadata or 'addrspace'");
  1879. if (ParseOptionalAddrSpace(AddrSpace))
  1880. return true;
  1881. }
  1882. return false;
  1883. }
  1884. bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
  1885. Optional<unsigned> &HowManyArg) {
  1886. Lex.Lex();
  1887. auto StartParen = Lex.getLoc();
  1888. if (!EatIfPresent(lltok::lparen))
  1889. return Error(StartParen, "expected '('");
  1890. if (ParseUInt32(BaseSizeArg))
  1891. return true;
  1892. if (EatIfPresent(lltok::comma)) {
  1893. auto HowManyAt = Lex.getLoc();
  1894. unsigned HowMany;
  1895. if (ParseUInt32(HowMany))
  1896. return true;
  1897. if (HowMany == BaseSizeArg)
  1898. return Error(HowManyAt,
  1899. "'allocsize' indices can't refer to the same parameter");
  1900. HowManyArg = HowMany;
  1901. } else
  1902. HowManyArg = None;
  1903. auto EndParen = Lex.getLoc();
  1904. if (!EatIfPresent(lltok::rparen))
  1905. return Error(EndParen, "expected ')'");
  1906. return false;
  1907. }
  1908. /// ParseScopeAndOrdering
  1909. /// if isAtomic: ::= SyncScope? AtomicOrdering
  1910. /// else: ::=
  1911. ///
  1912. /// This sets Scope and Ordering to the parsed values.
  1913. bool LLParser::ParseScopeAndOrdering(bool isAtomic, SyncScope::ID &SSID,
  1914. AtomicOrdering &Ordering) {
  1915. if (!isAtomic)
  1916. return false;
  1917. return ParseScope(SSID) || ParseOrdering(Ordering);
  1918. }
  1919. /// ParseScope
  1920. /// ::= syncscope("singlethread" | "<target scope>")?
  1921. ///
  1922. /// This sets synchronization scope ID to the ID of the parsed value.
  1923. bool LLParser::ParseScope(SyncScope::ID &SSID) {
  1924. SSID = SyncScope::System;
  1925. if (EatIfPresent(lltok::kw_syncscope)) {
  1926. auto StartParenAt = Lex.getLoc();
  1927. if (!EatIfPresent(lltok::lparen))
  1928. return Error(StartParenAt, "Expected '(' in syncscope");
  1929. std::string SSN;
  1930. auto SSNAt = Lex.getLoc();
  1931. if (ParseStringConstant(SSN))
  1932. return Error(SSNAt, "Expected synchronization scope name");
  1933. auto EndParenAt = Lex.getLoc();
  1934. if (!EatIfPresent(lltok::rparen))
  1935. return Error(EndParenAt, "Expected ')' in syncscope");
  1936. SSID = Context.getOrInsertSyncScopeID(SSN);
  1937. }
  1938. return false;
  1939. }
  1940. /// ParseOrdering
  1941. /// ::= AtomicOrdering
  1942. ///
  1943. /// This sets Ordering to the parsed value.
  1944. bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
  1945. switch (Lex.getKind()) {
  1946. default: return TokError("Expected ordering on atomic instruction");
  1947. case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
  1948. case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
  1949. // Not specified yet:
  1950. // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
  1951. case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
  1952. case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
  1953. case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
  1954. case lltok::kw_seq_cst:
  1955. Ordering = AtomicOrdering::SequentiallyConsistent;
  1956. break;
  1957. }
  1958. Lex.Lex();
  1959. return false;
  1960. }
  1961. /// ParseOptionalStackAlignment
  1962. /// ::= /* empty */
  1963. /// ::= 'alignstack' '(' 4 ')'
  1964. bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
  1965. Alignment = 0;
  1966. if (!EatIfPresent(lltok::kw_alignstack))
  1967. return false;
  1968. LocTy ParenLoc = Lex.getLoc();
  1969. if (!EatIfPresent(lltok::lparen))
  1970. return Error(ParenLoc, "expected '('");
  1971. LocTy AlignLoc = Lex.getLoc();
  1972. if (ParseUInt32(Alignment)) return true;
  1973. ParenLoc = Lex.getLoc();
  1974. if (!EatIfPresent(lltok::rparen))
  1975. return Error(ParenLoc, "expected ')'");
  1976. if (!isPowerOf2_32(Alignment))
  1977. return Error(AlignLoc, "stack alignment is not a power of two");
  1978. return false;
  1979. }
  1980. /// ParseIndexList - This parses the index list for an insert/extractvalue
  1981. /// instruction. This sets AteExtraComma in the case where we eat an extra
  1982. /// comma at the end of the line and find that it is followed by metadata.
  1983. /// Clients that don't allow metadata can call the version of this function that
  1984. /// only takes one argument.
  1985. ///
  1986. /// ParseIndexList
  1987. /// ::= (',' uint32)+
  1988. ///
  1989. bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
  1990. bool &AteExtraComma) {
  1991. AteExtraComma = false;
  1992. if (Lex.getKind() != lltok::comma)
  1993. return TokError("expected ',' as start of index list");
  1994. while (EatIfPresent(lltok::comma)) {
  1995. if (Lex.getKind() == lltok::MetadataVar) {
  1996. if (Indices.empty()) return TokError("expected index");
  1997. AteExtraComma = true;
  1998. return false;
  1999. }
  2000. unsigned Idx = 0;
  2001. if (ParseUInt32(Idx)) return true;
  2002. Indices.push_back(Idx);
  2003. }
  2004. return false;
  2005. }
  2006. //===----------------------------------------------------------------------===//
  2007. // Type Parsing.
  2008. //===----------------------------------------------------------------------===//
  2009. /// ParseType - Parse a type.
  2010. bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
  2011. SMLoc TypeLoc = Lex.getLoc();
  2012. switch (Lex.getKind()) {
  2013. default:
  2014. return TokError(Msg);
  2015. case lltok::Type:
  2016. // Type ::= 'float' | 'void' (etc)
  2017. Result = Lex.getTyVal();
  2018. Lex.Lex();
  2019. break;
  2020. case lltok::lbrace:
  2021. // Type ::= StructType
  2022. if (ParseAnonStructType(Result, false))
  2023. return true;
  2024. break;
  2025. case lltok::lsquare:
  2026. // Type ::= '[' ... ']'
  2027. Lex.Lex(); // eat the lsquare.
  2028. if (ParseArrayVectorType(Result, false))
  2029. return true;
  2030. break;
  2031. case lltok::less: // Either vector or packed struct.
  2032. // Type ::= '<' ... '>'
  2033. Lex.Lex();
  2034. if (Lex.getKind() == lltok::lbrace) {
  2035. if (ParseAnonStructType(Result, true) ||
  2036. ParseToken(lltok::greater, "expected '>' at end of packed struct"))
  2037. return true;
  2038. } else if (ParseArrayVectorType(Result, true))
  2039. return true;
  2040. break;
  2041. case lltok::LocalVar: {
  2042. // Type ::= %foo
  2043. std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
  2044. // If the type hasn't been defined yet, create a forward definition and
  2045. // remember where that forward def'n was seen (in case it never is defined).
  2046. if (!Entry.first) {
  2047. Entry.first = StructType::create(Context, Lex.getStrVal());
  2048. Entry.second = Lex.getLoc();
  2049. }
  2050. Result = Entry.first;
  2051. Lex.Lex();
  2052. break;
  2053. }
  2054. case lltok::LocalVarID: {
  2055. // Type ::= %4
  2056. std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
  2057. // If the type hasn't been defined yet, create a forward definition and
  2058. // remember where that forward def'n was seen (in case it never is defined).
  2059. if (!Entry.first) {
  2060. Entry.first = StructType::create(Context);
  2061. Entry.second = Lex.getLoc();
  2062. }
  2063. Result = Entry.first;
  2064. Lex.Lex();
  2065. break;
  2066. }
  2067. }
  2068. // Parse the type suffixes.
  2069. while (true) {
  2070. switch (Lex.getKind()) {
  2071. // End of type.
  2072. default:
  2073. if (!AllowVoid && Result->isVoidTy())
  2074. return Error(TypeLoc, "void type only allowed for function results");
  2075. return false;
  2076. // Type ::= Type '*'
  2077. case lltok::star:
  2078. if (Result->isLabelTy())
  2079. return TokError("basic block pointers are invalid");
  2080. if (Result->isVoidTy())
  2081. return TokError("pointers to void are invalid - use i8* instead");
  2082. if (!PointerType::isValidElementType(Result))
  2083. return TokError("pointer to this type is invalid");
  2084. Result = PointerType::getUnqual(Result);
  2085. Lex.Lex();
  2086. break;
  2087. // Type ::= Type 'addrspace' '(' uint32 ')' '*'
  2088. case lltok::kw_addrspace: {
  2089. if (Result->isLabelTy())
  2090. return TokError("basic block pointers are invalid");
  2091. if (Result->isVoidTy())
  2092. return TokError("pointers to void are invalid; use i8* instead");
  2093. if (!PointerType::isValidElementType(Result))
  2094. return TokError("pointer to this type is invalid");
  2095. unsigned AddrSpace;
  2096. if (ParseOptionalAddrSpace(AddrSpace) ||
  2097. ParseToken(lltok::star, "expected '*' in address space"))
  2098. return true;
  2099. Result = PointerType::get(Result, AddrSpace);
  2100. break;
  2101. }
  2102. /// Types '(' ArgTypeListI ')' OptFuncAttrs
  2103. case lltok::lparen:
  2104. if (ParseFunctionType(Result))
  2105. return true;
  2106. break;
  2107. }
  2108. }
  2109. }
  2110. /// ParseParameterList
  2111. /// ::= '(' ')'
  2112. /// ::= '(' Arg (',' Arg)* ')'
  2113. /// Arg
  2114. /// ::= Type OptionalAttributes Value OptionalAttributes
  2115. bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
  2116. PerFunctionState &PFS, bool IsMustTailCall,
  2117. bool InVarArgsFunc) {
  2118. if (ParseToken(lltok::lparen, "expected '(' in call"))
  2119. return true;
  2120. while (Lex.getKind() != lltok::rparen) {
  2121. // If this isn't the first argument, we need a comma.
  2122. if (!ArgList.empty() &&
  2123. ParseToken(lltok::comma, "expected ',' in argument list"))
  2124. return true;
  2125. // Parse an ellipsis if this is a musttail call in a variadic function.
  2126. if (Lex.getKind() == lltok::dotdotdot) {
  2127. const char *Msg = "unexpected ellipsis in argument list for ";
  2128. if (!IsMustTailCall)
  2129. return TokError(Twine(Msg) + "non-musttail call");
  2130. if (!InVarArgsFunc)
  2131. return TokError(Twine(Msg) + "musttail call in non-varargs function");
  2132. Lex.Lex(); // Lex the '...', it is purely for readability.
  2133. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  2134. }
  2135. // Parse the argument.
  2136. LocTy ArgLoc;
  2137. Type *ArgTy = nullptr;
  2138. AttrBuilder ArgAttrs;
  2139. Value *V;
  2140. if (ParseType(ArgTy, ArgLoc))
  2141. return true;
  2142. if (ArgTy->isMetadataTy()) {
  2143. if (ParseMetadataAsValue(V, PFS))
  2144. return true;
  2145. } else {
  2146. // Otherwise, handle normal operands.
  2147. if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
  2148. return true;
  2149. }
  2150. ArgList.push_back(ParamInfo(
  2151. ArgLoc, V, AttributeSet::get(V->getContext(), ArgAttrs)));
  2152. }
  2153. if (IsMustTailCall && InVarArgsFunc)
  2154. return TokError("expected '...' at end of argument list for musttail call "
  2155. "in varargs function");
  2156. Lex.Lex(); // Lex the ')'.
  2157. return false;
  2158. }
  2159. /// ParseOptionalOperandBundles
  2160. /// ::= /*empty*/
  2161. /// ::= '[' OperandBundle [, OperandBundle ]* ']'
  2162. ///
  2163. /// OperandBundle
  2164. /// ::= bundle-tag '(' ')'
  2165. /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
  2166. ///
  2167. /// bundle-tag ::= String Constant
  2168. bool LLParser::ParseOptionalOperandBundles(
  2169. SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
  2170. LocTy BeginLoc = Lex.getLoc();
  2171. if (!EatIfPresent(lltok::lsquare))
  2172. return false;
  2173. while (Lex.getKind() != lltok::rsquare) {
  2174. // If this isn't the first operand bundle, we need a comma.
  2175. if (!BundleList.empty() &&
  2176. ParseToken(lltok::comma, "expected ',' in input list"))
  2177. return true;
  2178. std::string Tag;
  2179. if (ParseStringConstant(Tag))
  2180. return true;
  2181. if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
  2182. return true;
  2183. std::vector<Value *> Inputs;
  2184. while (Lex.getKind() != lltok::rparen) {
  2185. // If this isn't the first input, we need a comma.
  2186. if (!Inputs.empty() &&
  2187. ParseToken(lltok::comma, "expected ',' in input list"))
  2188. return true;
  2189. Type *Ty = nullptr;
  2190. Value *Input = nullptr;
  2191. if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
  2192. return true;
  2193. Inputs.push_back(Input);
  2194. }
  2195. BundleList.emplace_back(std::move(Tag), std::move(Inputs));
  2196. Lex.Lex(); // Lex the ')'.
  2197. }
  2198. if (BundleList.empty())
  2199. return Error(BeginLoc, "operand bundle set must not be empty");
  2200. Lex.Lex(); // Lex the ']'.
  2201. return false;
  2202. }
  2203. /// ParseArgumentList - Parse the argument list for a function type or function
  2204. /// prototype.
  2205. /// ::= '(' ArgTypeListI ')'
  2206. /// ArgTypeListI
  2207. /// ::= /*empty*/
  2208. /// ::= '...'
  2209. /// ::= ArgTypeList ',' '...'
  2210. /// ::= ArgType (',' ArgType)*
  2211. ///
  2212. bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
  2213. bool &isVarArg){
  2214. isVarArg = false;
  2215. assert(Lex.getKind() == lltok::lparen);
  2216. Lex.Lex(); // eat the (.
  2217. if (Lex.getKind() == lltok::rparen) {
  2218. // empty
  2219. } else if (Lex.getKind() == lltok::dotdotdot) {
  2220. isVarArg = true;
  2221. Lex.Lex();
  2222. } else {
  2223. LocTy TypeLoc = Lex.getLoc();
  2224. Type *ArgTy = nullptr;
  2225. AttrBuilder Attrs;
  2226. std::string Name;
  2227. if (ParseType(ArgTy) ||
  2228. ParseOptionalParamAttrs(Attrs)) return true;
  2229. if (ArgTy->isVoidTy())
  2230. return Error(TypeLoc, "argument can not have void type");
  2231. if (Lex.getKind() == lltok::LocalVar) {
  2232. Name = Lex.getStrVal();
  2233. Lex.Lex();
  2234. }
  2235. if (!FunctionType::isValidArgumentType(ArgTy))
  2236. return Error(TypeLoc, "invalid type for function argument");
  2237. ArgList.emplace_back(TypeLoc, ArgTy,
  2238. AttributeSet::get(ArgTy->getContext(), Attrs),
  2239. std::move(Name));
  2240. while (EatIfPresent(lltok::comma)) {
  2241. // Handle ... at end of arg list.
  2242. if (EatIfPresent(lltok::dotdotdot)) {
  2243. isVarArg = true;
  2244. break;
  2245. }
  2246. // Otherwise must be an argument type.
  2247. TypeLoc = Lex.getLoc();
  2248. if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
  2249. if (ArgTy->isVoidTy())
  2250. return Error(TypeLoc, "argument can not have void type");
  2251. if (Lex.getKind() == lltok::LocalVar) {
  2252. Name = Lex.getStrVal();
  2253. Lex.Lex();
  2254. } else {
  2255. Name = "";
  2256. }
  2257. if (!ArgTy->isFirstClassType())
  2258. return Error(TypeLoc, "invalid type for function argument");
  2259. ArgList.emplace_back(TypeLoc, ArgTy,
  2260. AttributeSet::get(ArgTy->getContext(), Attrs),
  2261. std::move(Name));
  2262. }
  2263. }
  2264. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  2265. }
  2266. /// ParseFunctionType
  2267. /// ::= Type ArgumentList OptionalAttrs
  2268. bool LLParser::ParseFunctionType(Type *&Result) {
  2269. assert(Lex.getKind() == lltok::lparen);
  2270. if (!FunctionType::isValidReturnType(Result))
  2271. return TokError("invalid function return type");
  2272. SmallVector<ArgInfo, 8> ArgList;
  2273. bool isVarArg;
  2274. if (ParseArgumentList(ArgList, isVarArg))
  2275. return true;
  2276. // Reject names on the arguments lists.
  2277. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2278. if (!ArgList[i].Name.empty())
  2279. return Error(ArgList[i].Loc, "argument name invalid in function type");
  2280. if (ArgList[i].Attrs.hasAttributes())
  2281. return Error(ArgList[i].Loc,
  2282. "argument attributes invalid in function type");
  2283. }
  2284. SmallVector<Type*, 16> ArgListTy;
  2285. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  2286. ArgListTy.push_back(ArgList[i].Ty);
  2287. Result = FunctionType::get(Result, ArgListTy, isVarArg);
  2288. return false;
  2289. }
  2290. /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
  2291. /// other structs.
  2292. bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
  2293. SmallVector<Type*, 8> Elts;
  2294. if (ParseStructBody(Elts)) return true;
  2295. Result = StructType::get(Context, Elts, Packed);
  2296. return false;
  2297. }
  2298. /// ParseStructDefinition - Parse a struct in a 'type' definition.
  2299. bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
  2300. std::pair<Type*, LocTy> &Entry,
  2301. Type *&ResultTy) {
  2302. // If the type was already defined, diagnose the redefinition.
  2303. if (Entry.first && !Entry.second.isValid())
  2304. return Error(TypeLoc, "redefinition of type");
  2305. // If we have opaque, just return without filling in the definition for the
  2306. // struct. This counts as a definition as far as the .ll file goes.
  2307. if (EatIfPresent(lltok::kw_opaque)) {
  2308. // This type is being defined, so clear the location to indicate this.
  2309. Entry.second = SMLoc();
  2310. // If this type number has never been uttered, create it.
  2311. if (!Entry.first)
  2312. Entry.first = StructType::create(Context, Name);
  2313. ResultTy = Entry.first;
  2314. return false;
  2315. }
  2316. // If the type starts with '<', then it is either a packed struct or a vector.
  2317. bool isPacked = EatIfPresent(lltok::less);
  2318. // If we don't have a struct, then we have a random type alias, which we
  2319. // accept for compatibility with old files. These types are not allowed to be
  2320. // forward referenced and not allowed to be recursive.
  2321. if (Lex.getKind() != lltok::lbrace) {
  2322. if (Entry.first)
  2323. return Error(TypeLoc, "forward references to non-struct type");
  2324. ResultTy = nullptr;
  2325. if (isPacked)
  2326. return ParseArrayVectorType(ResultTy, true);
  2327. return ParseType(ResultTy);
  2328. }
  2329. // This type is being defined, so clear the location to indicate this.
  2330. Entry.second = SMLoc();
  2331. // If this type number has never been uttered, create it.
  2332. if (!Entry.first)
  2333. Entry.first = StructType::create(Context, Name);
  2334. StructType *STy = cast<StructType>(Entry.first);
  2335. SmallVector<Type*, 8> Body;
  2336. if (ParseStructBody(Body) ||
  2337. (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
  2338. return true;
  2339. STy->setBody(Body, isPacked);
  2340. ResultTy = STy;
  2341. return false;
  2342. }
  2343. /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
  2344. /// StructType
  2345. /// ::= '{' '}'
  2346. /// ::= '{' Type (',' Type)* '}'
  2347. /// ::= '<' '{' '}' '>'
  2348. /// ::= '<' '{' Type (',' Type)* '}' '>'
  2349. bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
  2350. assert(Lex.getKind() == lltok::lbrace);
  2351. Lex.Lex(); // Consume the '{'
  2352. // Handle the empty struct.
  2353. if (EatIfPresent(lltok::rbrace))
  2354. return false;
  2355. LocTy EltTyLoc = Lex.getLoc();
  2356. Type *Ty = nullptr;
  2357. if (ParseType(Ty)) return true;
  2358. Body.push_back(Ty);
  2359. if (!StructType::isValidElementType(Ty))
  2360. return Error(EltTyLoc, "invalid element type for struct");
  2361. while (EatIfPresent(lltok::comma)) {
  2362. EltTyLoc = Lex.getLoc();
  2363. if (ParseType(Ty)) return true;
  2364. if (!StructType::isValidElementType(Ty))
  2365. return Error(EltTyLoc, "invalid element type for struct");
  2366. Body.push_back(Ty);
  2367. }
  2368. return ParseToken(lltok::rbrace, "expected '}' at end of struct");
  2369. }
  2370. /// ParseArrayVectorType - Parse an array or vector type, assuming the first
  2371. /// token has already been consumed.
  2372. /// Type
  2373. /// ::= '[' APSINTVAL 'x' Types ']'
  2374. /// ::= '<' APSINTVAL 'x' Types '>'
  2375. bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
  2376. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
  2377. Lex.getAPSIntVal().getBitWidth() > 64)
  2378. return TokError("expected number in address space");
  2379. LocTy SizeLoc = Lex.getLoc();
  2380. uint64_t Size = Lex.getAPSIntVal().getZExtValue();
  2381. Lex.Lex();
  2382. if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
  2383. return true;
  2384. LocTy TypeLoc = Lex.getLoc();
  2385. Type *EltTy = nullptr;
  2386. if (ParseType(EltTy)) return true;
  2387. if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
  2388. "expected end of sequential type"))
  2389. return true;
  2390. if (isVector) {
  2391. if (Size == 0)
  2392. return Error(SizeLoc, "zero element vector is illegal");
  2393. if ((unsigned)Size != Size)
  2394. return Error(SizeLoc, "size too large for vector");
  2395. if (!VectorType::isValidElementType(EltTy))
  2396. return Error(TypeLoc, "invalid vector element type");
  2397. Result = VectorType::get(EltTy, unsigned(Size));
  2398. } else {
  2399. if (!ArrayType::isValidElementType(EltTy))
  2400. return Error(TypeLoc, "invalid array element type");
  2401. Result = ArrayType::get(EltTy, Size);
  2402. }
  2403. return false;
  2404. }
  2405. //===----------------------------------------------------------------------===//
  2406. // Function Semantic Analysis.
  2407. //===----------------------------------------------------------------------===//
  2408. LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
  2409. int functionNumber)
  2410. : P(p), F(f), FunctionNumber(functionNumber) {
  2411. // Insert unnamed arguments into the NumberedVals list.
  2412. for (Argument &A : F.args())
  2413. if (!A.hasName())
  2414. NumberedVals.push_back(&A);
  2415. }
  2416. LLParser::PerFunctionState::~PerFunctionState() {
  2417. // If there were any forward referenced non-basicblock values, delete them.
  2418. for (const auto &P : ForwardRefVals) {
  2419. if (isa<BasicBlock>(P.second.first))
  2420. continue;
  2421. P.second.first->replaceAllUsesWith(
  2422. UndefValue::get(P.second.first->getType()));
  2423. P.second.first->deleteValue();
  2424. }
  2425. for (const auto &P : ForwardRefValIDs) {
  2426. if (isa<BasicBlock>(P.second.first))
  2427. continue;
  2428. P.second.first->replaceAllUsesWith(
  2429. UndefValue::get(P.second.first->getType()));
  2430. P.second.first->deleteValue();
  2431. }
  2432. }
  2433. bool LLParser::PerFunctionState::FinishFunction() {
  2434. if (!ForwardRefVals.empty())
  2435. return P.Error(ForwardRefVals.begin()->second.second,
  2436. "use of undefined value '%" + ForwardRefVals.begin()->first +
  2437. "'");
  2438. if (!ForwardRefValIDs.empty())
  2439. return P.Error(ForwardRefValIDs.begin()->second.second,
  2440. "use of undefined value '%" +
  2441. Twine(ForwardRefValIDs.begin()->first) + "'");
  2442. return false;
  2443. }
  2444. /// GetVal - Get a value with the specified name or ID, creating a
  2445. /// forward reference record if needed. This can return null if the value
  2446. /// exists but does not have the right type.
  2447. Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
  2448. LocTy Loc, bool IsCall) {
  2449. // Look this name up in the normal function symbol table.
  2450. Value *Val = F.getValueSymbolTable()->lookup(Name);
  2451. // If this is a forward reference for the value, see if we already created a
  2452. // forward ref record.
  2453. if (!Val) {
  2454. auto I = ForwardRefVals.find(Name);
  2455. if (I != ForwardRefVals.end())
  2456. Val = I->second.first;
  2457. }
  2458. // If we have the value in the symbol table or fwd-ref table, return it.
  2459. if (Val)
  2460. return P.checkValidVariableType(Loc, "%" + Name, Ty, Val, IsCall);
  2461. // Don't make placeholders with invalid type.
  2462. if (!Ty->isFirstClassType()) {
  2463. P.Error(Loc, "invalid use of a non-first-class type");
  2464. return nullptr;
  2465. }
  2466. // Otherwise, create a new forward reference for this value and remember it.
  2467. Value *FwdVal;
  2468. if (Ty->isLabelTy()) {
  2469. FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
  2470. } else {
  2471. FwdVal = new Argument(Ty, Name);
  2472. }
  2473. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  2474. return FwdVal;
  2475. }
  2476. Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc,
  2477. bool IsCall) {
  2478. // Look this name up in the normal function symbol table.
  2479. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  2480. // If this is a forward reference for the value, see if we already created a
  2481. // forward ref record.
  2482. if (!Val) {
  2483. auto I = ForwardRefValIDs.find(ID);
  2484. if (I != ForwardRefValIDs.end())
  2485. Val = I->second.first;
  2486. }
  2487. // If we have the value in the symbol table or fwd-ref table, return it.
  2488. if (Val)
  2489. return P.checkValidVariableType(Loc, "%" + Twine(ID), Ty, Val, IsCall);
  2490. if (!Ty->isFirstClassType()) {
  2491. P.Error(Loc, "invalid use of a non-first-class type");
  2492. return nullptr;
  2493. }
  2494. // Otherwise, create a new forward reference for this value and remember it.
  2495. Value *FwdVal;
  2496. if (Ty->isLabelTy()) {
  2497. FwdVal = BasicBlock::Create(F.getContext(), "", &F);
  2498. } else {
  2499. FwdVal = new Argument(Ty);
  2500. }
  2501. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  2502. return FwdVal;
  2503. }
  2504. /// SetInstName - After an instruction is parsed and inserted into its
  2505. /// basic block, this installs its name.
  2506. bool LLParser::PerFunctionState::SetInstName(int NameID,
  2507. const std::string &NameStr,
  2508. LocTy NameLoc, Instruction *Inst) {
  2509. // If this instruction has void type, it cannot have a name or ID specified.
  2510. if (Inst->getType()->isVoidTy()) {
  2511. if (NameID != -1 || !NameStr.empty())
  2512. return P.Error(NameLoc, "instructions returning void cannot have a name");
  2513. return false;
  2514. }
  2515. // If this was a numbered instruction, verify that the instruction is the
  2516. // expected value and resolve any forward references.
  2517. if (NameStr.empty()) {
  2518. // If neither a name nor an ID was specified, just use the next ID.
  2519. if (NameID == -1)
  2520. NameID = NumberedVals.size();
  2521. if (unsigned(NameID) != NumberedVals.size())
  2522. return P.Error(NameLoc, "instruction expected to be numbered '%" +
  2523. Twine(NumberedVals.size()) + "'");
  2524. auto FI = ForwardRefValIDs.find(NameID);
  2525. if (FI != ForwardRefValIDs.end()) {
  2526. Value *Sentinel = FI->second.first;
  2527. if (Sentinel->getType() != Inst->getType())
  2528. return P.Error(NameLoc, "instruction forward referenced with type '" +
  2529. getTypeString(FI->second.first->getType()) + "'");
  2530. Sentinel->replaceAllUsesWith(Inst);
  2531. Sentinel->deleteValue();
  2532. ForwardRefValIDs.erase(FI);
  2533. }
  2534. NumberedVals.push_back(Inst);
  2535. return false;
  2536. }
  2537. // Otherwise, the instruction had a name. Resolve forward refs and set it.
  2538. auto FI = ForwardRefVals.find(NameStr);
  2539. if (FI != ForwardRefVals.end()) {
  2540. Value *Sentinel = FI->second.first;
  2541. if (Sentinel->getType() != Inst->getType())
  2542. return P.Error(NameLoc, "instruction forward referenced with type '" +
  2543. getTypeString(FI->second.first->getType()) + "'");
  2544. Sentinel->replaceAllUsesWith(Inst);
  2545. Sentinel->deleteValue();
  2546. ForwardRefVals.erase(FI);
  2547. }
  2548. // Set the name on the instruction.
  2549. Inst->setName(NameStr);
  2550. if (Inst->getName() != NameStr)
  2551. return P.Error(NameLoc, "multiple definition of local value named '" +
  2552. NameStr + "'");
  2553. return false;
  2554. }
  2555. /// GetBB - Get a basic block with the specified name or ID, creating a
  2556. /// forward reference record if needed.
  2557. BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
  2558. LocTy Loc) {
  2559. return dyn_cast_or_null<BasicBlock>(
  2560. GetVal(Name, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
  2561. }
  2562. BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
  2563. return dyn_cast_or_null<BasicBlock>(
  2564. GetVal(ID, Type::getLabelTy(F.getContext()), Loc, /*IsCall=*/false));
  2565. }
  2566. /// DefineBB - Define the specified basic block, which is either named or
  2567. /// unnamed. If there is an error, this returns null otherwise it returns
  2568. /// the block being defined.
  2569. BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
  2570. LocTy Loc) {
  2571. BasicBlock *BB;
  2572. if (Name.empty())
  2573. BB = GetBB(NumberedVals.size(), Loc);
  2574. else
  2575. BB = GetBB(Name, Loc);
  2576. if (!BB) return nullptr; // Already diagnosed error.
  2577. // Move the block to the end of the function. Forward ref'd blocks are
  2578. // inserted wherever they happen to be referenced.
  2579. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
  2580. // Remove the block from forward ref sets.
  2581. if (Name.empty()) {
  2582. ForwardRefValIDs.erase(NumberedVals.size());
  2583. NumberedVals.push_back(BB);
  2584. } else {
  2585. // BB forward references are already in the function symbol table.
  2586. ForwardRefVals.erase(Name);
  2587. }
  2588. return BB;
  2589. }
  2590. //===----------------------------------------------------------------------===//
  2591. // Constants.
  2592. //===----------------------------------------------------------------------===//
  2593. /// ParseValID - Parse an abstract value that doesn't necessarily have a
  2594. /// type implied. For example, if we parse "4" we don't know what integer type
  2595. /// it has. The value will later be combined with its type and checked for
  2596. /// sanity. PFS is used to convert function-local operands of metadata (since
  2597. /// metadata operands are not just parsed here but also converted to values).
  2598. /// PFS can be null when we are not parsing metadata values inside a function.
  2599. bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
  2600. ID.Loc = Lex.getLoc();
  2601. switch (Lex.getKind()) {
  2602. default: return TokError("expected value token");
  2603. case lltok::GlobalID: // @42
  2604. ID.UIntVal = Lex.getUIntVal();
  2605. ID.Kind = ValID::t_GlobalID;
  2606. break;
  2607. case lltok::GlobalVar: // @foo
  2608. ID.StrVal = Lex.getStrVal();
  2609. ID.Kind = ValID::t_GlobalName;
  2610. break;
  2611. case lltok::LocalVarID: // %42
  2612. ID.UIntVal = Lex.getUIntVal();
  2613. ID.Kind = ValID::t_LocalID;
  2614. break;
  2615. case lltok::LocalVar: // %foo
  2616. ID.StrVal = Lex.getStrVal();
  2617. ID.Kind = ValID::t_LocalName;
  2618. break;
  2619. case lltok::APSInt:
  2620. ID.APSIntVal = Lex.getAPSIntVal();
  2621. ID.Kind = ValID::t_APSInt;
  2622. break;
  2623. case lltok::APFloat:
  2624. ID.APFloatVal = Lex.getAPFloatVal();
  2625. ID.Kind = ValID::t_APFloat;
  2626. break;
  2627. case lltok::kw_true:
  2628. ID.ConstantVal = ConstantInt::getTrue(Context);
  2629. ID.Kind = ValID::t_Constant;
  2630. break;
  2631. case lltok::kw_false:
  2632. ID.ConstantVal = ConstantInt::getFalse(Context);
  2633. ID.Kind = ValID::t_Constant;
  2634. break;
  2635. case lltok::kw_null: ID.Kind = ValID::t_Null; break;
  2636. case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
  2637. case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
  2638. case lltok::kw_none: ID.Kind = ValID::t_None; break;
  2639. case lltok::lbrace: {
  2640. // ValID ::= '{' ConstVector '}'
  2641. Lex.Lex();
  2642. SmallVector<Constant*, 16> Elts;
  2643. if (ParseGlobalValueVector(Elts) ||
  2644. ParseToken(lltok::rbrace, "expected end of struct constant"))
  2645. return true;
  2646. ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
  2647. ID.UIntVal = Elts.size();
  2648. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  2649. Elts.size() * sizeof(Elts[0]));
  2650. ID.Kind = ValID::t_ConstantStruct;
  2651. return false;
  2652. }
  2653. case lltok::less: {
  2654. // ValID ::= '<' ConstVector '>' --> Vector.
  2655. // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
  2656. Lex.Lex();
  2657. bool isPackedStruct = EatIfPresent(lltok::lbrace);
  2658. SmallVector<Constant*, 16> Elts;
  2659. LocTy FirstEltLoc = Lex.getLoc();
  2660. if (ParseGlobalValueVector(Elts) ||
  2661. (isPackedStruct &&
  2662. ParseToken(lltok::rbrace, "expected end of packed struct")) ||
  2663. ParseToken(lltok::greater, "expected end of constant"))
  2664. return true;
  2665. if (isPackedStruct) {
  2666. ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
  2667. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  2668. Elts.size() * sizeof(Elts[0]));
  2669. ID.UIntVal = Elts.size();
  2670. ID.Kind = ValID::t_PackedConstantStruct;
  2671. return false;
  2672. }
  2673. if (Elts.empty())
  2674. return Error(ID.Loc, "constant vector must not be empty");
  2675. if (!Elts[0]->getType()->isIntegerTy() &&
  2676. !Elts[0]->getType()->isFloatingPointTy() &&
  2677. !Elts[0]->getType()->isPointerTy())
  2678. return Error(FirstEltLoc,
  2679. "vector elements must have integer, pointer or floating point type");
  2680. // Verify that all the vector elements have the same type.
  2681. for (unsigned i = 1, e = Elts.size(); i != e; ++i)
  2682. if (Elts[i]->getType() != Elts[0]->getType())
  2683. return Error(FirstEltLoc,
  2684. "vector element #" + Twine(i) +
  2685. " is not of type '" + getTypeString(Elts[0]->getType()));
  2686. ID.ConstantVal = ConstantVector::get(Elts);
  2687. ID.Kind = ValID::t_Constant;
  2688. return false;
  2689. }
  2690. case lltok::lsquare: { // Array Constant
  2691. Lex.Lex();
  2692. SmallVector<Constant*, 16> Elts;
  2693. LocTy FirstEltLoc = Lex.getLoc();
  2694. if (ParseGlobalValueVector(Elts) ||
  2695. ParseToken(lltok::rsquare, "expected end of array constant"))
  2696. return true;
  2697. // Handle empty element.
  2698. if (Elts.empty()) {
  2699. // Use undef instead of an array because it's inconvenient to determine
  2700. // the element type at this point, there being no elements to examine.
  2701. ID.Kind = ValID::t_EmptyArray;
  2702. return false;
  2703. }
  2704. if (!Elts[0]->getType()->isFirstClassType())
  2705. return Error(FirstEltLoc, "invalid array element type: " +
  2706. getTypeString(Elts[0]->getType()));
  2707. ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
  2708. // Verify all elements are correct type!
  2709. for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
  2710. if (Elts[i]->getType() != Elts[0]->getType())
  2711. return Error(FirstEltLoc,
  2712. "array element #" + Twine(i) +
  2713. " is not of type '" + getTypeString(Elts[0]->getType()));
  2714. }
  2715. ID.ConstantVal = ConstantArray::get(ATy, Elts);
  2716. ID.Kind = ValID::t_Constant;
  2717. return false;
  2718. }
  2719. case lltok::kw_c: // c "foo"
  2720. Lex.Lex();
  2721. ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
  2722. false);
  2723. if (ParseToken(lltok::StringConstant, "expected string")) return true;
  2724. ID.Kind = ValID::t_Constant;
  2725. return false;
  2726. case lltok::kw_asm: {
  2727. // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
  2728. // STRINGCONSTANT
  2729. bool HasSideEffect, AlignStack, AsmDialect;
  2730. Lex.Lex();
  2731. if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
  2732. ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
  2733. ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
  2734. ParseStringConstant(ID.StrVal) ||
  2735. ParseToken(lltok::comma, "expected comma in inline asm expression") ||
  2736. ParseToken(lltok::StringConstant, "expected constraint string"))
  2737. return true;
  2738. ID.StrVal2 = Lex.getStrVal();
  2739. ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
  2740. (unsigned(AsmDialect)<<2);
  2741. ID.Kind = ValID::t_InlineAsm;
  2742. return false;
  2743. }
  2744. case lltok::kw_blockaddress: {
  2745. // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
  2746. Lex.Lex();
  2747. ValID Fn, Label;
  2748. if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
  2749. ParseValID(Fn) ||
  2750. ParseToken(lltok::comma, "expected comma in block address expression")||
  2751. ParseValID(Label) ||
  2752. ParseToken(lltok::rparen, "expected ')' in block address expression"))
  2753. return true;
  2754. if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
  2755. return Error(Fn.Loc, "expected function name in blockaddress");
  2756. if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
  2757. return Error(Label.Loc, "expected basic block name in blockaddress");
  2758. // Try to find the function (but skip it if it's forward-referenced).
  2759. GlobalValue *GV = nullptr;
  2760. if (Fn.Kind == ValID::t_GlobalID) {
  2761. if (Fn.UIntVal < NumberedVals.size())
  2762. GV = NumberedVals[Fn.UIntVal];
  2763. } else if (!ForwardRefVals.count(Fn.StrVal)) {
  2764. GV = M->getNamedValue(Fn.StrVal);
  2765. }
  2766. Function *F = nullptr;
  2767. if (GV) {
  2768. // Confirm that it's actually a function with a definition.
  2769. if (!isa<Function>(GV))
  2770. return Error(Fn.Loc, "expected function name in blockaddress");
  2771. F = cast<Function>(GV);
  2772. if (F->isDeclaration())
  2773. return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
  2774. }
  2775. if (!F) {
  2776. // Make a global variable as a placeholder for this reference.
  2777. GlobalValue *&FwdRef =
  2778. ForwardRefBlockAddresses.insert(std::make_pair(
  2779. std::move(Fn),
  2780. std::map<ValID, GlobalValue *>()))
  2781. .first->second.insert(std::make_pair(std::move(Label), nullptr))
  2782. .first->second;
  2783. if (!FwdRef)
  2784. FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
  2785. GlobalValue::InternalLinkage, nullptr, "");
  2786. ID.ConstantVal = FwdRef;
  2787. ID.Kind = ValID::t_Constant;
  2788. return false;
  2789. }
  2790. // We found the function; now find the basic block. Don't use PFS, since we
  2791. // might be inside a constant expression.
  2792. BasicBlock *BB;
  2793. if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
  2794. if (Label.Kind == ValID::t_LocalID)
  2795. BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
  2796. else
  2797. BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
  2798. if (!BB)
  2799. return Error(Label.Loc, "referenced value is not a basic block");
  2800. } else {
  2801. if (Label.Kind == ValID::t_LocalID)
  2802. return Error(Label.Loc, "cannot take address of numeric label after "
  2803. "the function is defined");
  2804. BB = dyn_cast_or_null<BasicBlock>(
  2805. F->getValueSymbolTable()->lookup(Label.StrVal));
  2806. if (!BB)
  2807. return Error(Label.Loc, "referenced value is not a basic block");
  2808. }
  2809. ID.ConstantVal = BlockAddress::get(F, BB);
  2810. ID.Kind = ValID::t_Constant;
  2811. return false;
  2812. }
  2813. case lltok::kw_trunc:
  2814. case lltok::kw_zext:
  2815. case lltok::kw_sext:
  2816. case lltok::kw_fptrunc:
  2817. case lltok::kw_fpext:
  2818. case lltok::kw_bitcast:
  2819. case lltok::kw_addrspacecast:
  2820. case lltok::kw_uitofp:
  2821. case lltok::kw_sitofp:
  2822. case lltok::kw_fptoui:
  2823. case lltok::kw_fptosi:
  2824. case lltok::kw_inttoptr:
  2825. case lltok::kw_ptrtoint: {
  2826. unsigned Opc = Lex.getUIntVal();
  2827. Type *DestTy = nullptr;
  2828. Constant *SrcVal;
  2829. Lex.Lex();
  2830. if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
  2831. ParseGlobalTypeAndValue(SrcVal) ||
  2832. ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
  2833. ParseType(DestTy) ||
  2834. ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
  2835. return true;
  2836. if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
  2837. return Error(ID.Loc, "invalid cast opcode for cast from '" +
  2838. getTypeString(SrcVal->getType()) + "' to '" +
  2839. getTypeString(DestTy) + "'");
  2840. ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
  2841. SrcVal, DestTy);
  2842. ID.Kind = ValID::t_Constant;
  2843. return false;
  2844. }
  2845. case lltok::kw_extractvalue: {
  2846. Lex.Lex();
  2847. Constant *Val;
  2848. SmallVector<unsigned, 4> Indices;
  2849. if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
  2850. ParseGlobalTypeAndValue(Val) ||
  2851. ParseIndexList(Indices) ||
  2852. ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
  2853. return true;
  2854. if (!Val->getType()->isAggregateType())
  2855. return Error(ID.Loc, "extractvalue operand must be aggregate type");
  2856. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  2857. return Error(ID.Loc, "invalid indices for extractvalue");
  2858. ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
  2859. ID.Kind = ValID::t_Constant;
  2860. return false;
  2861. }
  2862. case lltok::kw_insertvalue: {
  2863. Lex.Lex();
  2864. Constant *Val0, *Val1;
  2865. SmallVector<unsigned, 4> Indices;
  2866. if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
  2867. ParseGlobalTypeAndValue(Val0) ||
  2868. ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
  2869. ParseGlobalTypeAndValue(Val1) ||
  2870. ParseIndexList(Indices) ||
  2871. ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
  2872. return true;
  2873. if (!Val0->getType()->isAggregateType())
  2874. return Error(ID.Loc, "insertvalue operand must be aggregate type");
  2875. Type *IndexedType =
  2876. ExtractValueInst::getIndexedType(Val0->getType(), Indices);
  2877. if (!IndexedType)
  2878. return Error(ID.Loc, "invalid indices for insertvalue");
  2879. if (IndexedType != Val1->getType())
  2880. return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
  2881. getTypeString(Val1->getType()) +
  2882. "' instead of '" + getTypeString(IndexedType) +
  2883. "'");
  2884. ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
  2885. ID.Kind = ValID::t_Constant;
  2886. return false;
  2887. }
  2888. case lltok::kw_icmp:
  2889. case lltok::kw_fcmp: {
  2890. unsigned PredVal, Opc = Lex.getUIntVal();
  2891. Constant *Val0, *Val1;
  2892. Lex.Lex();
  2893. if (ParseCmpPredicate(PredVal, Opc) ||
  2894. ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
  2895. ParseGlobalTypeAndValue(Val0) ||
  2896. ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
  2897. ParseGlobalTypeAndValue(Val1) ||
  2898. ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
  2899. return true;
  2900. if (Val0->getType() != Val1->getType())
  2901. return Error(ID.Loc, "compare operands must have the same type");
  2902. CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
  2903. if (Opc == Instruction::FCmp) {
  2904. if (!Val0->getType()->isFPOrFPVectorTy())
  2905. return Error(ID.Loc, "fcmp requires floating point operands");
  2906. ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
  2907. } else {
  2908. assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
  2909. if (!Val0->getType()->isIntOrIntVectorTy() &&
  2910. !Val0->getType()->isPtrOrPtrVectorTy())
  2911. return Error(ID.Loc, "icmp requires pointer or integer operands");
  2912. ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
  2913. }
  2914. ID.Kind = ValID::t_Constant;
  2915. return false;
  2916. }
  2917. // Binary Operators.
  2918. case lltok::kw_add:
  2919. case lltok::kw_fadd:
  2920. case lltok::kw_sub:
  2921. case lltok::kw_fsub:
  2922. case lltok::kw_mul:
  2923. case lltok::kw_fmul:
  2924. case lltok::kw_udiv:
  2925. case lltok::kw_sdiv:
  2926. case lltok::kw_fdiv:
  2927. case lltok::kw_urem:
  2928. case lltok::kw_srem:
  2929. case lltok::kw_frem:
  2930. case lltok::kw_shl:
  2931. case lltok::kw_lshr:
  2932. case lltok::kw_ashr: {
  2933. bool NUW = false;
  2934. bool NSW = false;
  2935. bool Exact = false;
  2936. unsigned Opc = Lex.getUIntVal();
  2937. Constant *Val0, *Val1;
  2938. Lex.Lex();
  2939. LocTy ModifierLoc = Lex.getLoc();
  2940. if (Opc == Instruction::Add || Opc == Instruction::Sub ||
  2941. Opc == Instruction::Mul || Opc == Instruction::Shl) {
  2942. if (EatIfPresent(lltok::kw_nuw))
  2943. NUW = true;
  2944. if (EatIfPresent(lltok::kw_nsw)) {
  2945. NSW = true;
  2946. if (EatIfPresent(lltok::kw_nuw))
  2947. NUW = true;
  2948. }
  2949. } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
  2950. Opc == Instruction::LShr || Opc == Instruction::AShr) {
  2951. if (EatIfPresent(lltok::kw_exact))
  2952. Exact = true;
  2953. }
  2954. if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
  2955. ParseGlobalTypeAndValue(Val0) ||
  2956. ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
  2957. ParseGlobalTypeAndValue(Val1) ||
  2958. ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
  2959. return true;
  2960. if (Val0->getType() != Val1->getType())
  2961. return Error(ID.Loc, "operands of constexpr must have same type");
  2962. if (!Val0->getType()->isIntOrIntVectorTy()) {
  2963. if (NUW)
  2964. return Error(ModifierLoc, "nuw only applies to integer operations");
  2965. if (NSW)
  2966. return Error(ModifierLoc, "nsw only applies to integer operations");
  2967. }
  2968. // Check that the type is valid for the operator.
  2969. switch (Opc) {
  2970. case Instruction::Add:
  2971. case Instruction::Sub:
  2972. case Instruction::Mul:
  2973. case Instruction::UDiv:
  2974. case Instruction::SDiv:
  2975. case Instruction::URem:
  2976. case Instruction::SRem:
  2977. case Instruction::Shl:
  2978. case Instruction::AShr:
  2979. case Instruction::LShr:
  2980. if (!Val0->getType()->isIntOrIntVectorTy())
  2981. return Error(ID.Loc, "constexpr requires integer operands");
  2982. break;
  2983. case Instruction::FAdd:
  2984. case Instruction::FSub:
  2985. case Instruction::FMul:
  2986. case Instruction::FDiv:
  2987. case Instruction::FRem:
  2988. if (!Val0->getType()->isFPOrFPVectorTy())
  2989. return Error(ID.Loc, "constexpr requires fp operands");
  2990. break;
  2991. default: llvm_unreachable("Unknown binary operator!");
  2992. }
  2993. unsigned Flags = 0;
  2994. if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2995. if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2996. if (Exact) Flags |= PossiblyExactOperator::IsExact;
  2997. Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
  2998. ID.ConstantVal = C;
  2999. ID.Kind = ValID::t_Constant;
  3000. return false;
  3001. }
  3002. // Logical Operations
  3003. case lltok::kw_and:
  3004. case lltok::kw_or:
  3005. case lltok::kw_xor: {
  3006. unsigned Opc = Lex.getUIntVal();
  3007. Constant *Val0, *Val1;
  3008. Lex.Lex();
  3009. if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
  3010. ParseGlobalTypeAndValue(Val0) ||
  3011. ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
  3012. ParseGlobalTypeAndValue(Val1) ||
  3013. ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
  3014. return true;
  3015. if (Val0->getType() != Val1->getType())
  3016. return Error(ID.Loc, "operands of constexpr must have same type");
  3017. if (!Val0->getType()->isIntOrIntVectorTy())
  3018. return Error(ID.Loc,
  3019. "constexpr requires integer or integer vector operands");
  3020. ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
  3021. ID.Kind = ValID::t_Constant;
  3022. return false;
  3023. }
  3024. case lltok::kw_getelementptr:
  3025. case lltok::kw_shufflevector:
  3026. case lltok::kw_insertelement:
  3027. case lltok::kw_extractelement:
  3028. case lltok::kw_select: {
  3029. unsigned Opc = Lex.getUIntVal();
  3030. SmallVector<Constant*, 16> Elts;
  3031. bool InBounds = false;
  3032. Type *Ty;
  3033. Lex.Lex();
  3034. if (Opc == Instruction::GetElementPtr)
  3035. InBounds = EatIfPresent(lltok::kw_inbounds);
  3036. if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
  3037. return true;
  3038. LocTy ExplicitTypeLoc = Lex.getLoc();
  3039. if (Opc == Instruction::GetElementPtr) {
  3040. if (ParseType(Ty) ||
  3041. ParseToken(lltok::comma, "expected comma after getelementptr's type"))
  3042. return true;
  3043. }
  3044. Optional<unsigned> InRangeOp;
  3045. if (ParseGlobalValueVector(
  3046. Elts, Opc == Instruction::GetElementPtr ? &InRangeOp : nullptr) ||
  3047. ParseToken(lltok::rparen, "expected ')' in constantexpr"))
  3048. return true;
  3049. if (Opc == Instruction::GetElementPtr) {
  3050. if (Elts.size() == 0 ||
  3051. !Elts[0]->getType()->isPtrOrPtrVectorTy())
  3052. return Error(ID.Loc, "base of getelementptr must be a pointer");
  3053. Type *BaseType = Elts[0]->getType();
  3054. auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
  3055. if (Ty != BasePointerType->getElementType())
  3056. return Error(
  3057. ExplicitTypeLoc,
  3058. "explicit pointee type doesn't match operand's pointee type");
  3059. unsigned GEPWidth =
  3060. BaseType->isVectorTy() ? BaseType->getVectorNumElements() : 0;
  3061. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  3062. for (Constant *Val : Indices) {
  3063. Type *ValTy = Val->getType();
  3064. if (!ValTy->isIntOrIntVectorTy())
  3065. return Error(ID.Loc, "getelementptr index must be an integer");
  3066. if (ValTy->isVectorTy()) {
  3067. unsigned ValNumEl = ValTy->getVectorNumElements();
  3068. if (GEPWidth && (ValNumEl != GEPWidth))
  3069. return Error(
  3070. ID.Loc,
  3071. "getelementptr vector index has a wrong number of elements");
  3072. // GEPWidth may have been unknown because the base is a scalar,
  3073. // but it is known now.
  3074. GEPWidth = ValNumEl;
  3075. }
  3076. }
  3077. SmallPtrSet<Type*, 4> Visited;
  3078. if (!Indices.empty() && !Ty->isSized(&Visited))
  3079. return Error(ID.Loc, "base element of getelementptr must be sized");
  3080. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  3081. return Error(ID.Loc, "invalid getelementptr indices");
  3082. if (InRangeOp) {
  3083. if (*InRangeOp == 0)
  3084. return Error(ID.Loc,
  3085. "inrange keyword may not appear on pointer operand");
  3086. --*InRangeOp;
  3087. }
  3088. ID.ConstantVal = ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices,
  3089. InBounds, InRangeOp);
  3090. } else if (Opc == Instruction::Select) {
  3091. if (Elts.size() != 3)
  3092. return Error(ID.Loc, "expected three operands to select");
  3093. if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
  3094. Elts[2]))
  3095. return Error(ID.Loc, Reason);
  3096. ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
  3097. } else if (Opc == Instruction::ShuffleVector) {
  3098. if (Elts.size() != 3)
  3099. return Error(ID.Loc, "expected three operands to shufflevector");
  3100. if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  3101. return Error(ID.Loc, "invalid operands to shufflevector");
  3102. ID.ConstantVal =
  3103. ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
  3104. } else if (Opc == Instruction::ExtractElement) {
  3105. if (Elts.size() != 2)
  3106. return Error(ID.Loc, "expected two operands to extractelement");
  3107. if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
  3108. return Error(ID.Loc, "invalid extractelement operands");
  3109. ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
  3110. } else {
  3111. assert(Opc == Instruction::InsertElement && "Unknown opcode");
  3112. if (Elts.size() != 3)
  3113. return Error(ID.Loc, "expected three operands to insertelement");
  3114. if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  3115. return Error(ID.Loc, "invalid insertelement operands");
  3116. ID.ConstantVal =
  3117. ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
  3118. }
  3119. ID.Kind = ValID::t_Constant;
  3120. return false;
  3121. }
  3122. }
  3123. Lex.Lex();
  3124. return false;
  3125. }
  3126. /// ParseGlobalValue - Parse a global value with the specified type.
  3127. bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
  3128. C = nullptr;
  3129. ValID ID;
  3130. Value *V = nullptr;
  3131. bool Parsed = ParseValID(ID) ||
  3132. ConvertValIDToValue(Ty, ID, V, nullptr, /*IsCall=*/false);
  3133. if (V && !(C = dyn_cast<Constant>(V)))
  3134. return Error(ID.Loc, "global values must be constants");
  3135. return Parsed;
  3136. }
  3137. bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
  3138. Type *Ty = nullptr;
  3139. return ParseType(Ty) ||
  3140. ParseGlobalValue(Ty, V);
  3141. }
  3142. bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
  3143. C = nullptr;
  3144. LocTy KwLoc = Lex.getLoc();
  3145. if (!EatIfPresent(lltok::kw_comdat))
  3146. return false;
  3147. if (EatIfPresent(lltok::lparen)) {
  3148. if (Lex.getKind() != lltok::ComdatVar)
  3149. return TokError("expected comdat variable");
  3150. C = getComdat(Lex.getStrVal(), Lex.getLoc());
  3151. Lex.Lex();
  3152. if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
  3153. return true;
  3154. } else {
  3155. if (GlobalName.empty())
  3156. return TokError("comdat cannot be unnamed");
  3157. C = getComdat(GlobalName, KwLoc);
  3158. }
  3159. return false;
  3160. }
  3161. /// ParseGlobalValueVector
  3162. /// ::= /*empty*/
  3163. /// ::= [inrange] TypeAndValue (',' [inrange] TypeAndValue)*
  3164. bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts,
  3165. Optional<unsigned> *InRangeOp) {
  3166. // Empty list.
  3167. if (Lex.getKind() == lltok::rbrace ||
  3168. Lex.getKind() == lltok::rsquare ||
  3169. Lex.getKind() == lltok::greater ||
  3170. Lex.getKind() == lltok::rparen)
  3171. return false;
  3172. do {
  3173. if (InRangeOp && !*InRangeOp && EatIfPresent(lltok::kw_inrange))
  3174. *InRangeOp = Elts.size();
  3175. Constant *C;
  3176. if (ParseGlobalTypeAndValue(C)) return true;
  3177. Elts.push_back(C);
  3178. } while (EatIfPresent(lltok::comma));
  3179. return false;
  3180. }
  3181. bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
  3182. SmallVector<Metadata *, 16> Elts;
  3183. if (ParseMDNodeVector(Elts))
  3184. return true;
  3185. MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
  3186. return false;
  3187. }
  3188. /// MDNode:
  3189. /// ::= !{ ... }
  3190. /// ::= !7
  3191. /// ::= !DILocation(...)
  3192. bool LLParser::ParseMDNode(MDNode *&N) {
  3193. if (Lex.getKind() == lltok::MetadataVar)
  3194. return ParseSpecializedMDNode(N);
  3195. return ParseToken(lltok::exclaim, "expected '!' here") ||
  3196. ParseMDNodeTail(N);
  3197. }
  3198. bool LLParser::ParseMDNodeTail(MDNode *&N) {
  3199. // !{ ... }
  3200. if (Lex.getKind() == lltok::lbrace)
  3201. return ParseMDTuple(N);
  3202. // !42
  3203. return ParseMDNodeID(N);
  3204. }
  3205. namespace {
  3206. /// Structure to represent an optional metadata field.
  3207. template <class FieldTy> struct MDFieldImpl {
  3208. typedef MDFieldImpl ImplTy;
  3209. FieldTy Val;
  3210. bool Seen;
  3211. void assign(FieldTy Val) {
  3212. Seen = true;
  3213. this->Val = std::move(Val);
  3214. }
  3215. explicit MDFieldImpl(FieldTy Default)
  3216. : Val(std::move(Default)), Seen(false) {}
  3217. };
  3218. /// Structure to represent an optional metadata field that
  3219. /// can be of either type (A or B) and encapsulates the
  3220. /// MD<typeofA>Field and MD<typeofB>Field structs, so not
  3221. /// to reimplement the specifics for representing each Field.
  3222. template <class FieldTypeA, class FieldTypeB> struct MDEitherFieldImpl {
  3223. typedef MDEitherFieldImpl<FieldTypeA, FieldTypeB> ImplTy;
  3224. FieldTypeA A;
  3225. FieldTypeB B;
  3226. bool Seen;
  3227. enum {
  3228. IsInvalid = 0,
  3229. IsTypeA = 1,
  3230. IsTypeB = 2
  3231. } WhatIs;
  3232. void assign(FieldTypeA A) {
  3233. Seen = true;
  3234. this->A = std::move(A);
  3235. WhatIs = IsTypeA;
  3236. }
  3237. void assign(FieldTypeB B) {
  3238. Seen = true;
  3239. this->B = std::move(B);
  3240. WhatIs = IsTypeB;
  3241. }
  3242. explicit MDEitherFieldImpl(FieldTypeA DefaultA, FieldTypeB DefaultB)
  3243. : A(std::move(DefaultA)), B(std::move(DefaultB)), Seen(false),
  3244. WhatIs(IsInvalid) {}
  3245. };
  3246. struct MDUnsignedField : public MDFieldImpl<uint64_t> {
  3247. uint64_t Max;
  3248. MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
  3249. : ImplTy(Default), Max(Max) {}
  3250. };
  3251. struct LineField : public MDUnsignedField {
  3252. LineField() : MDUnsignedField(0, UINT32_MAX) {}
  3253. };
  3254. struct ColumnField : public MDUnsignedField {
  3255. ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
  3256. };
  3257. struct DwarfTagField : public MDUnsignedField {
  3258. DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
  3259. DwarfTagField(dwarf::Tag DefaultTag)
  3260. : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
  3261. };
  3262. struct DwarfMacinfoTypeField : public MDUnsignedField {
  3263. DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
  3264. DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
  3265. : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
  3266. };
  3267. struct DwarfAttEncodingField : public MDUnsignedField {
  3268. DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
  3269. };
  3270. struct DwarfVirtualityField : public MDUnsignedField {
  3271. DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
  3272. };
  3273. struct DwarfLangField : public MDUnsignedField {
  3274. DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
  3275. };
  3276. struct DwarfCCField : public MDUnsignedField {
  3277. DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
  3278. };
  3279. struct EmissionKindField : public MDUnsignedField {
  3280. EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
  3281. };
  3282. struct NameTableKindField : public MDUnsignedField {
  3283. NameTableKindField()
  3284. : MDUnsignedField(
  3285. 0, (unsigned)
  3286. DICompileUnit::DebugNameTableKind::LastDebugNameTableKind) {}
  3287. };
  3288. struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
  3289. DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
  3290. };
  3291. struct MDSignedField : public MDFieldImpl<int64_t> {
  3292. int64_t Min;
  3293. int64_t Max;
  3294. MDSignedField(int64_t Default = 0)
  3295. : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
  3296. MDSignedField(int64_t Default, int64_t Min, int64_t Max)
  3297. : ImplTy(Default), Min(Min), Max(Max) {}
  3298. };
  3299. struct MDBoolField : public MDFieldImpl<bool> {
  3300. MDBoolField(bool Default = false) : ImplTy(Default) {}
  3301. };
  3302. struct MDField : public MDFieldImpl<Metadata *> {
  3303. bool AllowNull;
  3304. MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
  3305. };
  3306. struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
  3307. MDConstant() : ImplTy(nullptr) {}
  3308. };
  3309. struct MDStringField : public MDFieldImpl<MDString *> {
  3310. bool AllowEmpty;
  3311. MDStringField(bool AllowEmpty = true)
  3312. : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
  3313. };
  3314. struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
  3315. MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
  3316. };
  3317. struct ChecksumKindField : public MDFieldImpl<DIFile::ChecksumKind> {
  3318. ChecksumKindField(DIFile::ChecksumKind CSKind) : ImplTy(CSKind) {}
  3319. };
  3320. struct MDSignedOrMDField : MDEitherFieldImpl<MDSignedField, MDField> {
  3321. MDSignedOrMDField(int64_t Default = 0, bool AllowNull = true)
  3322. : ImplTy(MDSignedField(Default), MDField(AllowNull)) {}
  3323. MDSignedOrMDField(int64_t Default, int64_t Min, int64_t Max,
  3324. bool AllowNull = true)
  3325. : ImplTy(MDSignedField(Default, Min, Max), MDField(AllowNull)) {}
  3326. bool isMDSignedField() const { return WhatIs == IsTypeA; }
  3327. bool isMDField() const { return WhatIs == IsTypeB; }
  3328. int64_t getMDSignedValue() const {
  3329. assert(isMDSignedField() && "Wrong field type");
  3330. return A.Val;
  3331. }
  3332. Metadata *getMDFieldValue() const {
  3333. assert(isMDField() && "Wrong field type");
  3334. return B.Val;
  3335. }
  3336. };
  3337. struct MDSignedOrUnsignedField
  3338. : MDEitherFieldImpl<MDSignedField, MDUnsignedField> {
  3339. MDSignedOrUnsignedField() : ImplTy(MDSignedField(0), MDUnsignedField(0)) {}
  3340. bool isMDSignedField() const { return WhatIs == IsTypeA; }
  3341. bool isMDUnsignedField() const { return WhatIs == IsTypeB; }
  3342. int64_t getMDSignedValue() const {
  3343. assert(isMDSignedField() && "Wrong field type");
  3344. return A.Val;
  3345. }
  3346. uint64_t getMDUnsignedValue() const {
  3347. assert(isMDUnsignedField() && "Wrong field type");
  3348. return B.Val;
  3349. }
  3350. };
  3351. } // end anonymous namespace
  3352. namespace llvm {
  3353. template <>
  3354. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3355. MDUnsignedField &Result) {
  3356. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  3357. return TokError("expected unsigned integer");
  3358. auto &U = Lex.getAPSIntVal();
  3359. if (U.ugt(Result.Max))
  3360. return TokError("value for '" + Name + "' too large, limit is " +
  3361. Twine(Result.Max));
  3362. Result.assign(U.getZExtValue());
  3363. assert(Result.Val <= Result.Max && "Expected value in range");
  3364. Lex.Lex();
  3365. return false;
  3366. }
  3367. template <>
  3368. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
  3369. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3370. }
  3371. template <>
  3372. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
  3373. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3374. }
  3375. template <>
  3376. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
  3377. if (Lex.getKind() == lltok::APSInt)
  3378. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3379. if (Lex.getKind() != lltok::DwarfTag)
  3380. return TokError("expected DWARF tag");
  3381. unsigned Tag = dwarf::getTag(Lex.getStrVal());
  3382. if (Tag == dwarf::DW_TAG_invalid)
  3383. return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
  3384. assert(Tag <= Result.Max && "Expected valid DWARF tag");
  3385. Result.assign(Tag);
  3386. Lex.Lex();
  3387. return false;
  3388. }
  3389. template <>
  3390. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3391. DwarfMacinfoTypeField &Result) {
  3392. if (Lex.getKind() == lltok::APSInt)
  3393. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3394. if (Lex.getKind() != lltok::DwarfMacinfo)
  3395. return TokError("expected DWARF macinfo type");
  3396. unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
  3397. if (Macinfo == dwarf::DW_MACINFO_invalid)
  3398. return TokError(
  3399. "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
  3400. assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
  3401. Result.assign(Macinfo);
  3402. Lex.Lex();
  3403. return false;
  3404. }
  3405. template <>
  3406. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3407. DwarfVirtualityField &Result) {
  3408. if (Lex.getKind() == lltok::APSInt)
  3409. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3410. if (Lex.getKind() != lltok::DwarfVirtuality)
  3411. return TokError("expected DWARF virtuality code");
  3412. unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
  3413. if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
  3414. return TokError("invalid DWARF virtuality code" + Twine(" '") +
  3415. Lex.getStrVal() + "'");
  3416. assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
  3417. Result.assign(Virtuality);
  3418. Lex.Lex();
  3419. return false;
  3420. }
  3421. template <>
  3422. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
  3423. if (Lex.getKind() == lltok::APSInt)
  3424. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3425. if (Lex.getKind() != lltok::DwarfLang)
  3426. return TokError("expected DWARF language");
  3427. unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
  3428. if (!Lang)
  3429. return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
  3430. "'");
  3431. assert(Lang <= Result.Max && "Expected valid DWARF language");
  3432. Result.assign(Lang);
  3433. Lex.Lex();
  3434. return false;
  3435. }
  3436. template <>
  3437. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
  3438. if (Lex.getKind() == lltok::APSInt)
  3439. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3440. if (Lex.getKind() != lltok::DwarfCC)
  3441. return TokError("expected DWARF calling convention");
  3442. unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
  3443. if (!CC)
  3444. return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
  3445. "'");
  3446. assert(CC <= Result.Max && "Expected valid DWARF calling convention");
  3447. Result.assign(CC);
  3448. Lex.Lex();
  3449. return false;
  3450. }
  3451. template <>
  3452. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
  3453. if (Lex.getKind() == lltok::APSInt)
  3454. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3455. if (Lex.getKind() != lltok::EmissionKind)
  3456. return TokError("expected emission kind");
  3457. auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
  3458. if (!Kind)
  3459. return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
  3460. "'");
  3461. assert(*Kind <= Result.Max && "Expected valid emission kind");
  3462. Result.assign(*Kind);
  3463. Lex.Lex();
  3464. return false;
  3465. }
  3466. template <>
  3467. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3468. NameTableKindField &Result) {
  3469. if (Lex.getKind() == lltok::APSInt)
  3470. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3471. if (Lex.getKind() != lltok::NameTableKind)
  3472. return TokError("expected nameTable kind");
  3473. auto Kind = DICompileUnit::getNameTableKind(Lex.getStrVal());
  3474. if (!Kind)
  3475. return TokError("invalid nameTable kind" + Twine(" '") + Lex.getStrVal() +
  3476. "'");
  3477. assert(((unsigned)*Kind) <= Result.Max && "Expected valid nameTable kind");
  3478. Result.assign((unsigned)*Kind);
  3479. Lex.Lex();
  3480. return false;
  3481. }
  3482. template <>
  3483. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3484. DwarfAttEncodingField &Result) {
  3485. if (Lex.getKind() == lltok::APSInt)
  3486. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3487. if (Lex.getKind() != lltok::DwarfAttEncoding)
  3488. return TokError("expected DWARF type attribute encoding");
  3489. unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
  3490. if (!Encoding)
  3491. return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
  3492. Lex.getStrVal() + "'");
  3493. assert(Encoding <= Result.Max && "Expected valid DWARF language");
  3494. Result.assign(Encoding);
  3495. Lex.Lex();
  3496. return false;
  3497. }
  3498. /// DIFlagField
  3499. /// ::= uint32
  3500. /// ::= DIFlagVector
  3501. /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
  3502. template <>
  3503. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
  3504. // Parser for a single flag.
  3505. auto parseFlag = [&](DINode::DIFlags &Val) {
  3506. if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
  3507. uint32_t TempVal = static_cast<uint32_t>(Val);
  3508. bool Res = ParseUInt32(TempVal);
  3509. Val = static_cast<DINode::DIFlags>(TempVal);
  3510. return Res;
  3511. }
  3512. if (Lex.getKind() != lltok::DIFlag)
  3513. return TokError("expected debug info flag");
  3514. Val = DINode::getFlag(Lex.getStrVal());
  3515. if (!Val)
  3516. return TokError(Twine("invalid debug info flag flag '") +
  3517. Lex.getStrVal() + "'");
  3518. Lex.Lex();
  3519. return false;
  3520. };
  3521. // Parse the flags and combine them together.
  3522. DINode::DIFlags Combined = DINode::FlagZero;
  3523. do {
  3524. DINode::DIFlags Val;
  3525. if (parseFlag(Val))
  3526. return true;
  3527. Combined |= Val;
  3528. } while (EatIfPresent(lltok::bar));
  3529. Result.assign(Combined);
  3530. return false;
  3531. }
  3532. template <>
  3533. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3534. MDSignedField &Result) {
  3535. if (Lex.getKind() != lltok::APSInt)
  3536. return TokError("expected signed integer");
  3537. auto &S = Lex.getAPSIntVal();
  3538. if (S < Result.Min)
  3539. return TokError("value for '" + Name + "' too small, limit is " +
  3540. Twine(Result.Min));
  3541. if (S > Result.Max)
  3542. return TokError("value for '" + Name + "' too large, limit is " +
  3543. Twine(Result.Max));
  3544. Result.assign(S.getExtValue());
  3545. assert(Result.Val >= Result.Min && "Expected value in range");
  3546. assert(Result.Val <= Result.Max && "Expected value in range");
  3547. Lex.Lex();
  3548. return false;
  3549. }
  3550. template <>
  3551. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
  3552. switch (Lex.getKind()) {
  3553. default:
  3554. return TokError("expected 'true' or 'false'");
  3555. case lltok::kw_true:
  3556. Result.assign(true);
  3557. break;
  3558. case lltok::kw_false:
  3559. Result.assign(false);
  3560. break;
  3561. }
  3562. Lex.Lex();
  3563. return false;
  3564. }
  3565. template <>
  3566. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
  3567. if (Lex.getKind() == lltok::kw_null) {
  3568. if (!Result.AllowNull)
  3569. return TokError("'" + Name + "' cannot be null");
  3570. Lex.Lex();
  3571. Result.assign(nullptr);
  3572. return false;
  3573. }
  3574. Metadata *MD;
  3575. if (ParseMetadata(MD, nullptr))
  3576. return true;
  3577. Result.assign(MD);
  3578. return false;
  3579. }
  3580. template <>
  3581. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3582. MDSignedOrMDField &Result) {
  3583. // Try to parse a signed int.
  3584. if (Lex.getKind() == lltok::APSInt) {
  3585. MDSignedField Res = Result.A;
  3586. if (!ParseMDField(Loc, Name, Res)) {
  3587. Result.assign(Res);
  3588. return false;
  3589. }
  3590. return true;
  3591. }
  3592. // Otherwise, try to parse as an MDField.
  3593. MDField Res = Result.B;
  3594. if (!ParseMDField(Loc, Name, Res)) {
  3595. Result.assign(Res);
  3596. return false;
  3597. }
  3598. return true;
  3599. }
  3600. template <>
  3601. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3602. MDSignedOrUnsignedField &Result) {
  3603. if (Lex.getKind() != lltok::APSInt)
  3604. return false;
  3605. if (Lex.getAPSIntVal().isSigned()) {
  3606. MDSignedField Res = Result.A;
  3607. if (ParseMDField(Loc, Name, Res))
  3608. return true;
  3609. Result.assign(Res);
  3610. return false;
  3611. }
  3612. MDUnsignedField Res = Result.B;
  3613. if (ParseMDField(Loc, Name, Res))
  3614. return true;
  3615. Result.assign(Res);
  3616. return false;
  3617. }
  3618. template <>
  3619. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
  3620. LocTy ValueLoc = Lex.getLoc();
  3621. std::string S;
  3622. if (ParseStringConstant(S))
  3623. return true;
  3624. if (!Result.AllowEmpty && S.empty())
  3625. return Error(ValueLoc, "'" + Name + "' cannot be empty");
  3626. Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
  3627. return false;
  3628. }
  3629. template <>
  3630. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
  3631. SmallVector<Metadata *, 4> MDs;
  3632. if (ParseMDNodeVector(MDs))
  3633. return true;
  3634. Result.assign(std::move(MDs));
  3635. return false;
  3636. }
  3637. template <>
  3638. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3639. ChecksumKindField &Result) {
  3640. Optional<DIFile::ChecksumKind> CSKind =
  3641. DIFile::getChecksumKind(Lex.getStrVal());
  3642. if (Lex.getKind() != lltok::ChecksumKind || !CSKind)
  3643. return TokError(
  3644. "invalid checksum kind" + Twine(" '") + Lex.getStrVal() + "'");
  3645. Result.assign(*CSKind);
  3646. Lex.Lex();
  3647. return false;
  3648. }
  3649. } // end namespace llvm
  3650. template <class ParserTy>
  3651. bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
  3652. do {
  3653. if (Lex.getKind() != lltok::LabelStr)
  3654. return TokError("expected field label here");
  3655. if (parseField())
  3656. return true;
  3657. } while (EatIfPresent(lltok::comma));
  3658. return false;
  3659. }
  3660. template <class ParserTy>
  3661. bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
  3662. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  3663. Lex.Lex();
  3664. if (ParseToken(lltok::lparen, "expected '(' here"))
  3665. return true;
  3666. if (Lex.getKind() != lltok::rparen)
  3667. if (ParseMDFieldsImplBody(parseField))
  3668. return true;
  3669. ClosingLoc = Lex.getLoc();
  3670. return ParseToken(lltok::rparen, "expected ')' here");
  3671. }
  3672. template <class FieldTy>
  3673. bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
  3674. if (Result.Seen)
  3675. return TokError("field '" + Name + "' cannot be specified more than once");
  3676. LocTy Loc = Lex.getLoc();
  3677. Lex.Lex();
  3678. return ParseMDField(Loc, Name, Result);
  3679. }
  3680. bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
  3681. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  3682. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
  3683. if (Lex.getStrVal() == #CLASS) \
  3684. return Parse##CLASS(N, IsDistinct);
  3685. #include "llvm/IR/Metadata.def"
  3686. return TokError("expected metadata type");
  3687. }
  3688. #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
  3689. #define NOP_FIELD(NAME, TYPE, INIT)
  3690. #define REQUIRE_FIELD(NAME, TYPE, INIT) \
  3691. if (!NAME.Seen) \
  3692. return Error(ClosingLoc, "missing required field '" #NAME "'");
  3693. #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
  3694. if (Lex.getStrVal() == #NAME) \
  3695. return ParseMDField(#NAME, NAME);
  3696. #define PARSE_MD_FIELDS() \
  3697. VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
  3698. do { \
  3699. LocTy ClosingLoc; \
  3700. if (ParseMDFieldsImpl([&]() -> bool { \
  3701. VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
  3702. return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
  3703. }, ClosingLoc)) \
  3704. return true; \
  3705. VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
  3706. } while (false)
  3707. #define GET_OR_DISTINCT(CLASS, ARGS) \
  3708. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  3709. /// ParseDILocationFields:
  3710. /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6,
  3711. /// isImplicitCode: true)
  3712. bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
  3713. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3714. OPTIONAL(line, LineField, ); \
  3715. OPTIONAL(column, ColumnField, ); \
  3716. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3717. OPTIONAL(inlinedAt, MDField, ); \
  3718. OPTIONAL(isImplicitCode, MDBoolField, (false));
  3719. PARSE_MD_FIELDS();
  3720. #undef VISIT_MD_FIELDS
  3721. Result =
  3722. GET_OR_DISTINCT(DILocation, (Context, line.Val, column.Val, scope.Val,
  3723. inlinedAt.Val, isImplicitCode.Val));
  3724. return false;
  3725. }
  3726. /// ParseGenericDINode:
  3727. /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
  3728. bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
  3729. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3730. REQUIRED(tag, DwarfTagField, ); \
  3731. OPTIONAL(header, MDStringField, ); \
  3732. OPTIONAL(operands, MDFieldList, );
  3733. PARSE_MD_FIELDS();
  3734. #undef VISIT_MD_FIELDS
  3735. Result = GET_OR_DISTINCT(GenericDINode,
  3736. (Context, tag.Val, header.Val, operands.Val));
  3737. return false;
  3738. }
  3739. /// ParseDISubrange:
  3740. /// ::= !DISubrange(count: 30, lowerBound: 2)
  3741. /// ::= !DISubrange(count: !node, lowerBound: 2)
  3742. bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
  3743. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3744. REQUIRED(count, MDSignedOrMDField, (-1, -1, INT64_MAX, false)); \
  3745. OPTIONAL(lowerBound, MDSignedField, );
  3746. PARSE_MD_FIELDS();
  3747. #undef VISIT_MD_FIELDS
  3748. if (count.isMDSignedField())
  3749. Result = GET_OR_DISTINCT(
  3750. DISubrange, (Context, count.getMDSignedValue(), lowerBound.Val));
  3751. else if (count.isMDField())
  3752. Result = GET_OR_DISTINCT(
  3753. DISubrange, (Context, count.getMDFieldValue(), lowerBound.Val));
  3754. else
  3755. return true;
  3756. return false;
  3757. }
  3758. /// ParseDIEnumerator:
  3759. /// ::= !DIEnumerator(value: 30, isUnsigned: true, name: "SomeKind")
  3760. bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
  3761. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3762. REQUIRED(name, MDStringField, ); \
  3763. REQUIRED(value, MDSignedOrUnsignedField, ); \
  3764. OPTIONAL(isUnsigned, MDBoolField, (false));
  3765. PARSE_MD_FIELDS();
  3766. #undef VISIT_MD_FIELDS
  3767. if (isUnsigned.Val && value.isMDSignedField())
  3768. return TokError("unsigned enumerator with negative value");
  3769. int64_t Value = value.isMDSignedField()
  3770. ? value.getMDSignedValue()
  3771. : static_cast<int64_t>(value.getMDUnsignedValue());
  3772. Result =
  3773. GET_OR_DISTINCT(DIEnumerator, (Context, Value, isUnsigned.Val, name.Val));
  3774. return false;
  3775. }
  3776. /// ParseDIBasicType:
  3777. /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32,
  3778. /// encoding: DW_ATE_encoding, flags: 0)
  3779. bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
  3780. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3781. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
  3782. OPTIONAL(name, MDStringField, ); \
  3783. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3784. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  3785. OPTIONAL(encoding, DwarfAttEncodingField, ); \
  3786. OPTIONAL(flags, DIFlagField, );
  3787. PARSE_MD_FIELDS();
  3788. #undef VISIT_MD_FIELDS
  3789. Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
  3790. align.Val, encoding.Val, flags.Val));
  3791. return false;
  3792. }
  3793. /// ParseDIDerivedType:
  3794. /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
  3795. /// line: 7, scope: !1, baseType: !2, size: 32,
  3796. /// align: 32, offset: 0, flags: 0, extraData: !3,
  3797. /// dwarfAddressSpace: 3)
  3798. bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
  3799. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3800. REQUIRED(tag, DwarfTagField, ); \
  3801. OPTIONAL(name, MDStringField, ); \
  3802. OPTIONAL(file, MDField, ); \
  3803. OPTIONAL(line, LineField, ); \
  3804. OPTIONAL(scope, MDField, ); \
  3805. REQUIRED(baseType, MDField, ); \
  3806. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3807. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  3808. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  3809. OPTIONAL(flags, DIFlagField, ); \
  3810. OPTIONAL(extraData, MDField, ); \
  3811. OPTIONAL(dwarfAddressSpace, MDUnsignedField, (UINT32_MAX, UINT32_MAX));
  3812. PARSE_MD_FIELDS();
  3813. #undef VISIT_MD_FIELDS
  3814. Optional<unsigned> DWARFAddressSpace;
  3815. if (dwarfAddressSpace.Val != UINT32_MAX)
  3816. DWARFAddressSpace = dwarfAddressSpace.Val;
  3817. Result = GET_OR_DISTINCT(DIDerivedType,
  3818. (Context, tag.Val, name.Val, file.Val, line.Val,
  3819. scope.Val, baseType.Val, size.Val, align.Val,
  3820. offset.Val, DWARFAddressSpace, flags.Val,
  3821. extraData.Val));
  3822. return false;
  3823. }
  3824. bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
  3825. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3826. REQUIRED(tag, DwarfTagField, ); \
  3827. OPTIONAL(name, MDStringField, ); \
  3828. OPTIONAL(file, MDField, ); \
  3829. OPTIONAL(line, LineField, ); \
  3830. OPTIONAL(scope, MDField, ); \
  3831. OPTIONAL(baseType, MDField, ); \
  3832. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3833. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX)); \
  3834. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  3835. OPTIONAL(flags, DIFlagField, ); \
  3836. OPTIONAL(elements, MDField, ); \
  3837. OPTIONAL(runtimeLang, DwarfLangField, ); \
  3838. OPTIONAL(vtableHolder, MDField, ); \
  3839. OPTIONAL(templateParams, MDField, ); \
  3840. OPTIONAL(identifier, MDStringField, ); \
  3841. OPTIONAL(discriminator, MDField, );
  3842. PARSE_MD_FIELDS();
  3843. #undef VISIT_MD_FIELDS
  3844. // If this has an identifier try to build an ODR type.
  3845. if (identifier.Val)
  3846. if (auto *CT = DICompositeType::buildODRType(
  3847. Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
  3848. scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
  3849. elements.Val, runtimeLang.Val, vtableHolder.Val,
  3850. templateParams.Val, discriminator.Val)) {
  3851. Result = CT;
  3852. return false;
  3853. }
  3854. // Create a new node, and save it in the context if it belongs in the type
  3855. // map.
  3856. Result = GET_OR_DISTINCT(
  3857. DICompositeType,
  3858. (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
  3859. size.Val, align.Val, offset.Val, flags.Val, elements.Val,
  3860. runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val,
  3861. discriminator.Val));
  3862. return false;
  3863. }
  3864. bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
  3865. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3866. OPTIONAL(flags, DIFlagField, ); \
  3867. OPTIONAL(cc, DwarfCCField, ); \
  3868. REQUIRED(types, MDField, );
  3869. PARSE_MD_FIELDS();
  3870. #undef VISIT_MD_FIELDS
  3871. Result = GET_OR_DISTINCT(DISubroutineType,
  3872. (Context, flags.Val, cc.Val, types.Val));
  3873. return false;
  3874. }
  3875. /// ParseDIFileType:
  3876. /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir",
  3877. /// checksumkind: CSK_MD5,
  3878. /// checksum: "000102030405060708090a0b0c0d0e0f",
  3879. /// source: "source file contents")
  3880. bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
  3881. // The default constructed value for checksumkind is required, but will never
  3882. // be used, as the parser checks if the field was actually Seen before using
  3883. // the Val.
  3884. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3885. REQUIRED(filename, MDStringField, ); \
  3886. REQUIRED(directory, MDStringField, ); \
  3887. OPTIONAL(checksumkind, ChecksumKindField, (DIFile::CSK_MD5)); \
  3888. OPTIONAL(checksum, MDStringField, ); \
  3889. OPTIONAL(source, MDStringField, );
  3890. PARSE_MD_FIELDS();
  3891. #undef VISIT_MD_FIELDS
  3892. Optional<DIFile::ChecksumInfo<MDString *>> OptChecksum;
  3893. if (checksumkind.Seen && checksum.Seen)
  3894. OptChecksum.emplace(checksumkind.Val, checksum.Val);
  3895. else if (checksumkind.Seen || checksum.Seen)
  3896. return Lex.Error("'checksumkind' and 'checksum' must be provided together");
  3897. Optional<MDString *> OptSource;
  3898. if (source.Seen)
  3899. OptSource = source.Val;
  3900. Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val,
  3901. OptChecksum, OptSource));
  3902. return false;
  3903. }
  3904. /// ParseDICompileUnit:
  3905. /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
  3906. /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
  3907. /// splitDebugFilename: "abc.debug",
  3908. /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
  3909. /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
  3910. bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
  3911. if (!IsDistinct)
  3912. return Lex.Error("missing 'distinct', required for !DICompileUnit");
  3913. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3914. REQUIRED(language, DwarfLangField, ); \
  3915. REQUIRED(file, MDField, (/* AllowNull */ false)); \
  3916. OPTIONAL(producer, MDStringField, ); \
  3917. OPTIONAL(isOptimized, MDBoolField, ); \
  3918. OPTIONAL(flags, MDStringField, ); \
  3919. OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
  3920. OPTIONAL(splitDebugFilename, MDStringField, ); \
  3921. OPTIONAL(emissionKind, EmissionKindField, ); \
  3922. OPTIONAL(enums, MDField, ); \
  3923. OPTIONAL(retainedTypes, MDField, ); \
  3924. OPTIONAL(globals, MDField, ); \
  3925. OPTIONAL(imports, MDField, ); \
  3926. OPTIONAL(macros, MDField, ); \
  3927. OPTIONAL(dwoId, MDUnsignedField, ); \
  3928. OPTIONAL(splitDebugInlining, MDBoolField, = true); \
  3929. OPTIONAL(debugInfoForProfiling, MDBoolField, = false); \
  3930. OPTIONAL(nameTableKind, NameTableKindField, );
  3931. PARSE_MD_FIELDS();
  3932. #undef VISIT_MD_FIELDS
  3933. Result = DICompileUnit::getDistinct(
  3934. Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
  3935. runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
  3936. retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
  3937. splitDebugInlining.Val, debugInfoForProfiling.Val, nameTableKind.Val);
  3938. return false;
  3939. }
  3940. /// ParseDISubprogram:
  3941. /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
  3942. /// file: !1, line: 7, type: !2, isLocal: false,
  3943. /// isDefinition: true, scopeLine: 8, containingType: !3,
  3944. /// virtuality: DW_VIRTUALTIY_pure_virtual,
  3945. /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
  3946. /// isOptimized: false, templateParams: !4, declaration: !5,
  3947. /// retainedNodes: !6, thrownTypes: !7)
  3948. bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
  3949. auto Loc = Lex.getLoc();
  3950. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3951. OPTIONAL(scope, MDField, ); \
  3952. OPTIONAL(name, MDStringField, ); \
  3953. OPTIONAL(linkageName, MDStringField, ); \
  3954. OPTIONAL(file, MDField, ); \
  3955. OPTIONAL(line, LineField, ); \
  3956. OPTIONAL(type, MDField, ); \
  3957. OPTIONAL(isLocal, MDBoolField, ); \
  3958. OPTIONAL(isDefinition, MDBoolField, (true)); \
  3959. OPTIONAL(scopeLine, LineField, ); \
  3960. OPTIONAL(containingType, MDField, ); \
  3961. OPTIONAL(virtuality, DwarfVirtualityField, ); \
  3962. OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
  3963. OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
  3964. OPTIONAL(flags, DIFlagField, ); \
  3965. OPTIONAL(isOptimized, MDBoolField, ); \
  3966. OPTIONAL(unit, MDField, ); \
  3967. OPTIONAL(templateParams, MDField, ); \
  3968. OPTIONAL(declaration, MDField, ); \
  3969. OPTIONAL(retainedNodes, MDField, ); \
  3970. OPTIONAL(thrownTypes, MDField, );
  3971. PARSE_MD_FIELDS();
  3972. #undef VISIT_MD_FIELDS
  3973. if (isDefinition.Val && !IsDistinct)
  3974. return Lex.Error(
  3975. Loc,
  3976. "missing 'distinct', required for !DISubprogram when 'isDefinition'");
  3977. Result = GET_OR_DISTINCT(
  3978. DISubprogram,
  3979. (Context, scope.Val, name.Val, linkageName.Val, file.Val, line.Val,
  3980. type.Val, isLocal.Val, isDefinition.Val, scopeLine.Val,
  3981. containingType.Val, virtuality.Val, virtualIndex.Val, thisAdjustment.Val,
  3982. flags.Val, isOptimized.Val, unit.Val, templateParams.Val,
  3983. declaration.Val, retainedNodes.Val, thrownTypes.Val));
  3984. return false;
  3985. }
  3986. /// ParseDILexicalBlock:
  3987. /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
  3988. bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
  3989. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3990. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3991. OPTIONAL(file, MDField, ); \
  3992. OPTIONAL(line, LineField, ); \
  3993. OPTIONAL(column, ColumnField, );
  3994. PARSE_MD_FIELDS();
  3995. #undef VISIT_MD_FIELDS
  3996. Result = GET_OR_DISTINCT(
  3997. DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
  3998. return false;
  3999. }
  4000. /// ParseDILexicalBlockFile:
  4001. /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
  4002. bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
  4003. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4004. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4005. OPTIONAL(file, MDField, ); \
  4006. REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
  4007. PARSE_MD_FIELDS();
  4008. #undef VISIT_MD_FIELDS
  4009. Result = GET_OR_DISTINCT(DILexicalBlockFile,
  4010. (Context, scope.Val, file.Val, discriminator.Val));
  4011. return false;
  4012. }
  4013. /// ParseDINamespace:
  4014. /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
  4015. bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
  4016. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4017. REQUIRED(scope, MDField, ); \
  4018. OPTIONAL(name, MDStringField, ); \
  4019. OPTIONAL(exportSymbols, MDBoolField, );
  4020. PARSE_MD_FIELDS();
  4021. #undef VISIT_MD_FIELDS
  4022. Result = GET_OR_DISTINCT(DINamespace,
  4023. (Context, scope.Val, name.Val, exportSymbols.Val));
  4024. return false;
  4025. }
  4026. /// ParseDIMacro:
  4027. /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
  4028. bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
  4029. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4030. REQUIRED(type, DwarfMacinfoTypeField, ); \
  4031. OPTIONAL(line, LineField, ); \
  4032. REQUIRED(name, MDStringField, ); \
  4033. OPTIONAL(value, MDStringField, );
  4034. PARSE_MD_FIELDS();
  4035. #undef VISIT_MD_FIELDS
  4036. Result = GET_OR_DISTINCT(DIMacro,
  4037. (Context, type.Val, line.Val, name.Val, value.Val));
  4038. return false;
  4039. }
  4040. /// ParseDIMacroFile:
  4041. /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
  4042. bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
  4043. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4044. OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
  4045. OPTIONAL(line, LineField, ); \
  4046. REQUIRED(file, MDField, ); \
  4047. OPTIONAL(nodes, MDField, );
  4048. PARSE_MD_FIELDS();
  4049. #undef VISIT_MD_FIELDS
  4050. Result = GET_OR_DISTINCT(DIMacroFile,
  4051. (Context, type.Val, line.Val, file.Val, nodes.Val));
  4052. return false;
  4053. }
  4054. /// ParseDIModule:
  4055. /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
  4056. /// includePath: "/usr/include", isysroot: "/")
  4057. bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
  4058. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4059. REQUIRED(scope, MDField, ); \
  4060. REQUIRED(name, MDStringField, ); \
  4061. OPTIONAL(configMacros, MDStringField, ); \
  4062. OPTIONAL(includePath, MDStringField, ); \
  4063. OPTIONAL(isysroot, MDStringField, );
  4064. PARSE_MD_FIELDS();
  4065. #undef VISIT_MD_FIELDS
  4066. Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
  4067. configMacros.Val, includePath.Val, isysroot.Val));
  4068. return false;
  4069. }
  4070. /// ParseDITemplateTypeParameter:
  4071. /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
  4072. bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
  4073. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4074. OPTIONAL(name, MDStringField, ); \
  4075. REQUIRED(type, MDField, );
  4076. PARSE_MD_FIELDS();
  4077. #undef VISIT_MD_FIELDS
  4078. Result =
  4079. GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
  4080. return false;
  4081. }
  4082. /// ParseDITemplateValueParameter:
  4083. /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
  4084. /// name: "V", type: !1, value: i32 7)
  4085. bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
  4086. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4087. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
  4088. OPTIONAL(name, MDStringField, ); \
  4089. OPTIONAL(type, MDField, ); \
  4090. REQUIRED(value, MDField, );
  4091. PARSE_MD_FIELDS();
  4092. #undef VISIT_MD_FIELDS
  4093. Result = GET_OR_DISTINCT(DITemplateValueParameter,
  4094. (Context, tag.Val, name.Val, type.Val, value.Val));
  4095. return false;
  4096. }
  4097. /// ParseDIGlobalVariable:
  4098. /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
  4099. /// file: !1, line: 7, type: !2, isLocal: false,
  4100. /// isDefinition: true, templateParams: !3,
  4101. /// declaration: !4, align: 8)
  4102. bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
  4103. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4104. REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
  4105. OPTIONAL(scope, MDField, ); \
  4106. OPTIONAL(linkageName, MDStringField, ); \
  4107. OPTIONAL(file, MDField, ); \
  4108. OPTIONAL(line, LineField, ); \
  4109. OPTIONAL(type, MDField, ); \
  4110. OPTIONAL(isLocal, MDBoolField, ); \
  4111. OPTIONAL(isDefinition, MDBoolField, (true)); \
  4112. OPTIONAL(templateParams, MDField, ); \
  4113. OPTIONAL(declaration, MDField, ); \
  4114. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
  4115. PARSE_MD_FIELDS();
  4116. #undef VISIT_MD_FIELDS
  4117. Result =
  4118. GET_OR_DISTINCT(DIGlobalVariable,
  4119. (Context, scope.Val, name.Val, linkageName.Val, file.Val,
  4120. line.Val, type.Val, isLocal.Val, isDefinition.Val,
  4121. declaration.Val, templateParams.Val, align.Val));
  4122. return false;
  4123. }
  4124. /// ParseDILocalVariable:
  4125. /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
  4126. /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
  4127. /// align: 8)
  4128. /// ::= !DILocalVariable(scope: !0, name: "foo",
  4129. /// file: !1, line: 7, type: !2, arg: 2, flags: 7,
  4130. /// align: 8)
  4131. bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
  4132. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4133. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4134. OPTIONAL(name, MDStringField, ); \
  4135. OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
  4136. OPTIONAL(file, MDField, ); \
  4137. OPTIONAL(line, LineField, ); \
  4138. OPTIONAL(type, MDField, ); \
  4139. OPTIONAL(flags, DIFlagField, ); \
  4140. OPTIONAL(align, MDUnsignedField, (0, UINT32_MAX));
  4141. PARSE_MD_FIELDS();
  4142. #undef VISIT_MD_FIELDS
  4143. Result = GET_OR_DISTINCT(DILocalVariable,
  4144. (Context, scope.Val, name.Val, file.Val, line.Val,
  4145. type.Val, arg.Val, flags.Val, align.Val));
  4146. return false;
  4147. }
  4148. /// ParseDILabel:
  4149. /// ::= !DILabel(scope: !0, name: "foo", file: !1, line: 7)
  4150. bool LLParser::ParseDILabel(MDNode *&Result, bool IsDistinct) {
  4151. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4152. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  4153. REQUIRED(name, MDStringField, ); \
  4154. REQUIRED(file, MDField, ); \
  4155. REQUIRED(line, LineField, );
  4156. PARSE_MD_FIELDS();
  4157. #undef VISIT_MD_FIELDS
  4158. Result = GET_OR_DISTINCT(DILabel,
  4159. (Context, scope.Val, name.Val, file.Val, line.Val));
  4160. return false;
  4161. }
  4162. /// ParseDIExpression:
  4163. /// ::= !DIExpression(0, 7, -1)
  4164. bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
  4165. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  4166. Lex.Lex();
  4167. if (ParseToken(lltok::lparen, "expected '(' here"))
  4168. return true;
  4169. SmallVector<uint64_t, 8> Elements;
  4170. if (Lex.getKind() != lltok::rparen)
  4171. do {
  4172. if (Lex.getKind() == lltok::DwarfOp) {
  4173. if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
  4174. Lex.Lex();
  4175. Elements.push_back(Op);
  4176. continue;
  4177. }
  4178. return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
  4179. }
  4180. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  4181. return TokError("expected unsigned integer");
  4182. auto &U = Lex.getAPSIntVal();
  4183. if (U.ugt(UINT64_MAX))
  4184. return TokError("element too large, limit is " + Twine(UINT64_MAX));
  4185. Elements.push_back(U.getZExtValue());
  4186. Lex.Lex();
  4187. } while (EatIfPresent(lltok::comma));
  4188. if (ParseToken(lltok::rparen, "expected ')' here"))
  4189. return true;
  4190. Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
  4191. return false;
  4192. }
  4193. /// ParseDIGlobalVariableExpression:
  4194. /// ::= !DIGlobalVariableExpression(var: !0, expr: !1)
  4195. bool LLParser::ParseDIGlobalVariableExpression(MDNode *&Result,
  4196. bool IsDistinct) {
  4197. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4198. REQUIRED(var, MDField, ); \
  4199. REQUIRED(expr, MDField, );
  4200. PARSE_MD_FIELDS();
  4201. #undef VISIT_MD_FIELDS
  4202. Result =
  4203. GET_OR_DISTINCT(DIGlobalVariableExpression, (Context, var.Val, expr.Val));
  4204. return false;
  4205. }
  4206. /// ParseDIObjCProperty:
  4207. /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
  4208. /// getter: "getFoo", attributes: 7, type: !2)
  4209. bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
  4210. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4211. OPTIONAL(name, MDStringField, ); \
  4212. OPTIONAL(file, MDField, ); \
  4213. OPTIONAL(line, LineField, ); \
  4214. OPTIONAL(setter, MDStringField, ); \
  4215. OPTIONAL(getter, MDStringField, ); \
  4216. OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
  4217. OPTIONAL(type, MDField, );
  4218. PARSE_MD_FIELDS();
  4219. #undef VISIT_MD_FIELDS
  4220. Result = GET_OR_DISTINCT(DIObjCProperty,
  4221. (Context, name.Val, file.Val, line.Val, setter.Val,
  4222. getter.Val, attributes.Val, type.Val));
  4223. return false;
  4224. }
  4225. /// ParseDIImportedEntity:
  4226. /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
  4227. /// line: 7, name: "foo")
  4228. bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
  4229. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  4230. REQUIRED(tag, DwarfTagField, ); \
  4231. REQUIRED(scope, MDField, ); \
  4232. OPTIONAL(entity, MDField, ); \
  4233. OPTIONAL(file, MDField, ); \
  4234. OPTIONAL(line, LineField, ); \
  4235. OPTIONAL(name, MDStringField, );
  4236. PARSE_MD_FIELDS();
  4237. #undef VISIT_MD_FIELDS
  4238. Result = GET_OR_DISTINCT(
  4239. DIImportedEntity,
  4240. (Context, tag.Val, scope.Val, entity.Val, file.Val, line.Val, name.Val));
  4241. return false;
  4242. }
  4243. #undef PARSE_MD_FIELD
  4244. #undef NOP_FIELD
  4245. #undef REQUIRE_FIELD
  4246. #undef DECLARE_FIELD
  4247. /// ParseMetadataAsValue
  4248. /// ::= metadata i32 %local
  4249. /// ::= metadata i32 @global
  4250. /// ::= metadata i32 7
  4251. /// ::= metadata !0
  4252. /// ::= metadata !{...}
  4253. /// ::= metadata !"string"
  4254. bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
  4255. // Note: the type 'metadata' has already been parsed.
  4256. Metadata *MD;
  4257. if (ParseMetadata(MD, &PFS))
  4258. return true;
  4259. V = MetadataAsValue::get(Context, MD);
  4260. return false;
  4261. }
  4262. /// ParseValueAsMetadata
  4263. /// ::= i32 %local
  4264. /// ::= i32 @global
  4265. /// ::= i32 7
  4266. bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
  4267. PerFunctionState *PFS) {
  4268. Type *Ty;
  4269. LocTy Loc;
  4270. if (ParseType(Ty, TypeMsg, Loc))
  4271. return true;
  4272. if (Ty->isMetadataTy())
  4273. return Error(Loc, "invalid metadata-value-metadata roundtrip");
  4274. Value *V;
  4275. if (ParseValue(Ty, V, PFS))
  4276. return true;
  4277. MD = ValueAsMetadata::get(V);
  4278. return false;
  4279. }
  4280. /// ParseMetadata
  4281. /// ::= i32 %local
  4282. /// ::= i32 @global
  4283. /// ::= i32 7
  4284. /// ::= !42
  4285. /// ::= !{...}
  4286. /// ::= !"string"
  4287. /// ::= !DILocation(...)
  4288. bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
  4289. if (Lex.getKind() == lltok::MetadataVar) {
  4290. MDNode *N;
  4291. if (ParseSpecializedMDNode(N))
  4292. return true;
  4293. MD = N;
  4294. return false;
  4295. }
  4296. // ValueAsMetadata:
  4297. // <type> <value>
  4298. if (Lex.getKind() != lltok::exclaim)
  4299. return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
  4300. // '!'.
  4301. assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
  4302. Lex.Lex();
  4303. // MDString:
  4304. // ::= '!' STRINGCONSTANT
  4305. if (Lex.getKind() == lltok::StringConstant) {
  4306. MDString *S;
  4307. if (ParseMDString(S))
  4308. return true;
  4309. MD = S;
  4310. return false;
  4311. }
  4312. // MDNode:
  4313. // !{ ... }
  4314. // !7
  4315. MDNode *N;
  4316. if (ParseMDNodeTail(N))
  4317. return true;
  4318. MD = N;
  4319. return false;
  4320. }
  4321. //===----------------------------------------------------------------------===//
  4322. // Function Parsing.
  4323. //===----------------------------------------------------------------------===//
  4324. bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
  4325. PerFunctionState *PFS, bool IsCall) {
  4326. if (Ty->isFunctionTy())
  4327. return Error(ID.Loc, "functions are not values, refer to them as pointers");
  4328. switch (ID.Kind) {
  4329. case ValID::t_LocalID:
  4330. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  4331. V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc, IsCall);
  4332. return V == nullptr;
  4333. case ValID::t_LocalName:
  4334. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  4335. V = PFS->GetVal(ID.StrVal, Ty, ID.Loc, IsCall);
  4336. return V == nullptr;
  4337. case ValID::t_InlineAsm: {
  4338. if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
  4339. return Error(ID.Loc, "invalid type for inline asm constraint string");
  4340. V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
  4341. (ID.UIntVal >> 1) & 1,
  4342. (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
  4343. return false;
  4344. }
  4345. case ValID::t_GlobalName:
  4346. V = GetGlobalVal(ID.StrVal, Ty, ID.Loc, IsCall);
  4347. return V == nullptr;
  4348. case ValID::t_GlobalID:
  4349. V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc, IsCall);
  4350. return V == nullptr;
  4351. case ValID::t_APSInt:
  4352. if (!Ty->isIntegerTy())
  4353. return Error(ID.Loc, "integer constant must have integer type");
  4354. ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
  4355. V = ConstantInt::get(Context, ID.APSIntVal);
  4356. return false;
  4357. case ValID::t_APFloat:
  4358. if (!Ty->isFloatingPointTy() ||
  4359. !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
  4360. return Error(ID.Loc, "floating point constant invalid for type");
  4361. // The lexer has no type info, so builds all half, float, and double FP
  4362. // constants as double. Fix this here. Long double does not need this.
  4363. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble()) {
  4364. bool Ignored;
  4365. if (Ty->isHalfTy())
  4366. ID.APFloatVal.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven,
  4367. &Ignored);
  4368. else if (Ty->isFloatTy())
  4369. ID.APFloatVal.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  4370. &Ignored);
  4371. }
  4372. V = ConstantFP::get(Context, ID.APFloatVal);
  4373. if (V->getType() != Ty)
  4374. return Error(ID.Loc, "floating point constant does not have type '" +
  4375. getTypeString(Ty) + "'");
  4376. return false;
  4377. case ValID::t_Null:
  4378. if (!Ty->isPointerTy())
  4379. return Error(ID.Loc, "null must be a pointer type");
  4380. V = ConstantPointerNull::get(cast<PointerType>(Ty));
  4381. return false;
  4382. case ValID::t_Undef:
  4383. // FIXME: LabelTy should not be a first-class type.
  4384. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  4385. return Error(ID.Loc, "invalid type for undef constant");
  4386. V = UndefValue::get(Ty);
  4387. return false;
  4388. case ValID::t_EmptyArray:
  4389. if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
  4390. return Error(ID.Loc, "invalid empty array initializer");
  4391. V = UndefValue::get(Ty);
  4392. return false;
  4393. case ValID::t_Zero:
  4394. // FIXME: LabelTy should not be a first-class type.
  4395. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  4396. return Error(ID.Loc, "invalid type for null constant");
  4397. V = Constant::getNullValue(Ty);
  4398. return false;
  4399. case ValID::t_None:
  4400. if (!Ty->isTokenTy())
  4401. return Error(ID.Loc, "invalid type for none constant");
  4402. V = Constant::getNullValue(Ty);
  4403. return false;
  4404. case ValID::t_Constant:
  4405. if (ID.ConstantVal->getType() != Ty)
  4406. return Error(ID.Loc, "constant expression type mismatch");
  4407. V = ID.ConstantVal;
  4408. return false;
  4409. case ValID::t_ConstantStruct:
  4410. case ValID::t_PackedConstantStruct:
  4411. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  4412. if (ST->getNumElements() != ID.UIntVal)
  4413. return Error(ID.Loc,
  4414. "initializer with struct type has wrong # elements");
  4415. if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
  4416. return Error(ID.Loc, "packed'ness of initializer and type don't match");
  4417. // Verify that the elements are compatible with the structtype.
  4418. for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
  4419. if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
  4420. return Error(ID.Loc, "element " + Twine(i) +
  4421. " of struct initializer doesn't match struct element type");
  4422. V = ConstantStruct::get(
  4423. ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
  4424. } else
  4425. return Error(ID.Loc, "constant expression type mismatch");
  4426. return false;
  4427. }
  4428. llvm_unreachable("Invalid ValID");
  4429. }
  4430. bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
  4431. C = nullptr;
  4432. ValID ID;
  4433. auto Loc = Lex.getLoc();
  4434. if (ParseValID(ID, /*PFS=*/nullptr))
  4435. return true;
  4436. switch (ID.Kind) {
  4437. case ValID::t_APSInt:
  4438. case ValID::t_APFloat:
  4439. case ValID::t_Undef:
  4440. case ValID::t_Constant:
  4441. case ValID::t_ConstantStruct:
  4442. case ValID::t_PackedConstantStruct: {
  4443. Value *V;
  4444. if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr, /*IsCall=*/false))
  4445. return true;
  4446. assert(isa<Constant>(V) && "Expected a constant value");
  4447. C = cast<Constant>(V);
  4448. return false;
  4449. }
  4450. case ValID::t_Null:
  4451. C = Constant::getNullValue(Ty);
  4452. return false;
  4453. default:
  4454. return Error(Loc, "expected a constant value");
  4455. }
  4456. }
  4457. bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
  4458. V = nullptr;
  4459. ValID ID;
  4460. return ParseValID(ID, PFS) ||
  4461. ConvertValIDToValue(Ty, ID, V, PFS, /*IsCall=*/false);
  4462. }
  4463. bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
  4464. Type *Ty = nullptr;
  4465. return ParseType(Ty) ||
  4466. ParseValue(Ty, V, PFS);
  4467. }
  4468. bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
  4469. PerFunctionState &PFS) {
  4470. Value *V;
  4471. Loc = Lex.getLoc();
  4472. if (ParseTypeAndValue(V, PFS)) return true;
  4473. if (!isa<BasicBlock>(V))
  4474. return Error(Loc, "expected a basic block");
  4475. BB = cast<BasicBlock>(V);
  4476. return false;
  4477. }
  4478. /// FunctionHeader
  4479. /// ::= OptionalLinkage OptionalPreemptionSpecifier OptionalVisibility
  4480. /// OptionalCallingConv OptRetAttrs OptUnnamedAddr Type GlobalName
  4481. /// '(' ArgList ')' OptAddrSpace OptFuncAttrs OptSection OptionalAlign
  4482. /// OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
  4483. bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
  4484. // Parse the linkage.
  4485. LocTy LinkageLoc = Lex.getLoc();
  4486. unsigned Linkage;
  4487. unsigned Visibility;
  4488. unsigned DLLStorageClass;
  4489. bool DSOLocal;
  4490. AttrBuilder RetAttrs;
  4491. unsigned CC;
  4492. bool HasLinkage;
  4493. Type *RetType = nullptr;
  4494. LocTy RetTypeLoc = Lex.getLoc();
  4495. if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass,
  4496. DSOLocal) ||
  4497. ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  4498. ParseType(RetType, RetTypeLoc, true /*void allowed*/))
  4499. return true;
  4500. // Verify that the linkage is ok.
  4501. switch ((GlobalValue::LinkageTypes)Linkage) {
  4502. case GlobalValue::ExternalLinkage:
  4503. break; // always ok.
  4504. case GlobalValue::ExternalWeakLinkage:
  4505. if (isDefine)
  4506. return Error(LinkageLoc, "invalid linkage for function definition");
  4507. break;
  4508. case GlobalValue::PrivateLinkage:
  4509. case GlobalValue::InternalLinkage:
  4510. case GlobalValue::AvailableExternallyLinkage:
  4511. case GlobalValue::LinkOnceAnyLinkage:
  4512. case GlobalValue::LinkOnceODRLinkage:
  4513. case GlobalValue::WeakAnyLinkage:
  4514. case GlobalValue::WeakODRLinkage:
  4515. if (!isDefine)
  4516. return Error(LinkageLoc, "invalid linkage for function declaration");
  4517. break;
  4518. case GlobalValue::AppendingLinkage:
  4519. case GlobalValue::CommonLinkage:
  4520. return Error(LinkageLoc, "invalid function linkage type");
  4521. }
  4522. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  4523. return Error(LinkageLoc,
  4524. "symbol with local linkage must have default visibility");
  4525. if (!FunctionType::isValidReturnType(RetType))
  4526. return Error(RetTypeLoc, "invalid function return type");
  4527. LocTy NameLoc = Lex.getLoc();
  4528. std::string FunctionName;
  4529. if (Lex.getKind() == lltok::GlobalVar) {
  4530. FunctionName = Lex.getStrVal();
  4531. } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
  4532. unsigned NameID = Lex.getUIntVal();
  4533. if (NameID != NumberedVals.size())
  4534. return TokError("function expected to be numbered '%" +
  4535. Twine(NumberedVals.size()) + "'");
  4536. } else {
  4537. return TokError("expected function name");
  4538. }
  4539. Lex.Lex();
  4540. if (Lex.getKind() != lltok::lparen)
  4541. return TokError("expected '(' in function argument list");
  4542. SmallVector<ArgInfo, 8> ArgList;
  4543. bool isVarArg;
  4544. AttrBuilder FuncAttrs;
  4545. std::vector<unsigned> FwdRefAttrGrps;
  4546. LocTy BuiltinLoc;
  4547. std::string Section;
  4548. unsigned Alignment;
  4549. std::string GC;
  4550. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  4551. unsigned AddrSpace = 0;
  4552. Constant *Prefix = nullptr;
  4553. Constant *Prologue = nullptr;
  4554. Constant *PersonalityFn = nullptr;
  4555. Comdat *C;
  4556. if (ParseArgumentList(ArgList, isVarArg) ||
  4557. ParseOptionalUnnamedAddr(UnnamedAddr) ||
  4558. ParseOptionalProgramAddrSpace(AddrSpace) ||
  4559. ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
  4560. BuiltinLoc) ||
  4561. (EatIfPresent(lltok::kw_section) &&
  4562. ParseStringConstant(Section)) ||
  4563. parseOptionalComdat(FunctionName, C) ||
  4564. ParseOptionalAlignment(Alignment) ||
  4565. (EatIfPresent(lltok::kw_gc) &&
  4566. ParseStringConstant(GC)) ||
  4567. (EatIfPresent(lltok::kw_prefix) &&
  4568. ParseGlobalTypeAndValue(Prefix)) ||
  4569. (EatIfPresent(lltok::kw_prologue) &&
  4570. ParseGlobalTypeAndValue(Prologue)) ||
  4571. (EatIfPresent(lltok::kw_personality) &&
  4572. ParseGlobalTypeAndValue(PersonalityFn)))
  4573. return true;
  4574. if (FuncAttrs.contains(Attribute::Builtin))
  4575. return Error(BuiltinLoc, "'builtin' attribute not valid on function");
  4576. // If the alignment was parsed as an attribute, move to the alignment field.
  4577. if (FuncAttrs.hasAlignmentAttr()) {
  4578. Alignment = FuncAttrs.getAlignment();
  4579. FuncAttrs.removeAttribute(Attribute::Alignment);
  4580. }
  4581. // Okay, if we got here, the function is syntactically valid. Convert types
  4582. // and do semantic checks.
  4583. std::vector<Type*> ParamTypeList;
  4584. SmallVector<AttributeSet, 8> Attrs;
  4585. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  4586. ParamTypeList.push_back(ArgList[i].Ty);
  4587. Attrs.push_back(ArgList[i].Attrs);
  4588. }
  4589. AttributeList PAL =
  4590. AttributeList::get(Context, AttributeSet::get(Context, FuncAttrs),
  4591. AttributeSet::get(Context, RetAttrs), Attrs);
  4592. if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
  4593. return Error(RetTypeLoc, "functions with 'sret' argument must return void");
  4594. FunctionType *FT =
  4595. FunctionType::get(RetType, ParamTypeList, isVarArg);
  4596. PointerType *PFT = PointerType::get(FT, AddrSpace);
  4597. Fn = nullptr;
  4598. if (!FunctionName.empty()) {
  4599. // If this was a definition of a forward reference, remove the definition
  4600. // from the forward reference table and fill in the forward ref.
  4601. auto FRVI = ForwardRefVals.find(FunctionName);
  4602. if (FRVI != ForwardRefVals.end()) {
  4603. Fn = M->getFunction(FunctionName);
  4604. if (!Fn)
  4605. return Error(FRVI->second.second, "invalid forward reference to "
  4606. "function as global value!");
  4607. if (Fn->getType() != PFT)
  4608. return Error(FRVI->second.second, "invalid forward reference to "
  4609. "function '" + FunctionName + "' with wrong type: "
  4610. "expected '" + getTypeString(PFT) + "' but was '" +
  4611. getTypeString(Fn->getType()) + "'");
  4612. ForwardRefVals.erase(FRVI);
  4613. } else if ((Fn = M->getFunction(FunctionName))) {
  4614. // Reject redefinitions.
  4615. return Error(NameLoc, "invalid redefinition of function '" +
  4616. FunctionName + "'");
  4617. } else if (M->getNamedValue(FunctionName)) {
  4618. return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
  4619. }
  4620. } else {
  4621. // If this is a definition of a forward referenced function, make sure the
  4622. // types agree.
  4623. auto I = ForwardRefValIDs.find(NumberedVals.size());
  4624. if (I != ForwardRefValIDs.end()) {
  4625. Fn = cast<Function>(I->second.first);
  4626. if (Fn->getType() != PFT)
  4627. return Error(NameLoc, "type of definition and forward reference of '@" +
  4628. Twine(NumberedVals.size()) + "' disagree: "
  4629. "expected '" + getTypeString(PFT) + "' but was '" +
  4630. getTypeString(Fn->getType()) + "'");
  4631. ForwardRefValIDs.erase(I);
  4632. }
  4633. }
  4634. if (!Fn)
  4635. Fn = Function::Create(FT, GlobalValue::ExternalLinkage, AddrSpace,
  4636. FunctionName, M);
  4637. else // Move the forward-reference to the correct spot in the module.
  4638. M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
  4639. assert(Fn->getAddressSpace() == AddrSpace && "Created function in wrong AS");
  4640. if (FunctionName.empty())
  4641. NumberedVals.push_back(Fn);
  4642. Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
  4643. maybeSetDSOLocal(DSOLocal, *Fn);
  4644. Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  4645. Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  4646. Fn->setCallingConv(CC);
  4647. Fn->setAttributes(PAL);
  4648. Fn->setUnnamedAddr(UnnamedAddr);
  4649. Fn->setAlignment(Alignment);
  4650. Fn->setSection(Section);
  4651. Fn->setComdat(C);
  4652. Fn->setPersonalityFn(PersonalityFn);
  4653. if (!GC.empty()) Fn->setGC(GC);
  4654. Fn->setPrefixData(Prefix);
  4655. Fn->setPrologueData(Prologue);
  4656. ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
  4657. // Add all of the arguments we parsed to the function.
  4658. Function::arg_iterator ArgIt = Fn->arg_begin();
  4659. for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
  4660. // If the argument has a name, insert it into the argument symbol table.
  4661. if (ArgList[i].Name.empty()) continue;
  4662. // Set the name, if it conflicted, it will be auto-renamed.
  4663. ArgIt->setName(ArgList[i].Name);
  4664. if (ArgIt->getName() != ArgList[i].Name)
  4665. return Error(ArgList[i].Loc, "redefinition of argument '%" +
  4666. ArgList[i].Name + "'");
  4667. }
  4668. if (isDefine)
  4669. return false;
  4670. // Check the declaration has no block address forward references.
  4671. ValID ID;
  4672. if (FunctionName.empty()) {
  4673. ID.Kind = ValID::t_GlobalID;
  4674. ID.UIntVal = NumberedVals.size() - 1;
  4675. } else {
  4676. ID.Kind = ValID::t_GlobalName;
  4677. ID.StrVal = FunctionName;
  4678. }
  4679. auto Blocks = ForwardRefBlockAddresses.find(ID);
  4680. if (Blocks != ForwardRefBlockAddresses.end())
  4681. return Error(Blocks->first.Loc,
  4682. "cannot take blockaddress inside a declaration");
  4683. return false;
  4684. }
  4685. bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
  4686. ValID ID;
  4687. if (FunctionNumber == -1) {
  4688. ID.Kind = ValID::t_GlobalName;
  4689. ID.StrVal = F.getName();
  4690. } else {
  4691. ID.Kind = ValID::t_GlobalID;
  4692. ID.UIntVal = FunctionNumber;
  4693. }
  4694. auto Blocks = P.ForwardRefBlockAddresses.find(ID);
  4695. if (Blocks == P.ForwardRefBlockAddresses.end())
  4696. return false;
  4697. for (const auto &I : Blocks->second) {
  4698. const ValID &BBID = I.first;
  4699. GlobalValue *GV = I.second;
  4700. assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
  4701. "Expected local id or name");
  4702. BasicBlock *BB;
  4703. if (BBID.Kind == ValID::t_LocalName)
  4704. BB = GetBB(BBID.StrVal, BBID.Loc);
  4705. else
  4706. BB = GetBB(BBID.UIntVal, BBID.Loc);
  4707. if (!BB)
  4708. return P.Error(BBID.Loc, "referenced value is not a basic block");
  4709. GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
  4710. GV->eraseFromParent();
  4711. }
  4712. P.ForwardRefBlockAddresses.erase(Blocks);
  4713. return false;
  4714. }
  4715. /// ParseFunctionBody
  4716. /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
  4717. bool LLParser::ParseFunctionBody(Function &Fn) {
  4718. if (Lex.getKind() != lltok::lbrace)
  4719. return TokError("expected '{' in function body");
  4720. Lex.Lex(); // eat the {.
  4721. int FunctionNumber = -1;
  4722. if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
  4723. PerFunctionState PFS(*this, Fn, FunctionNumber);
  4724. // Resolve block addresses and allow basic blocks to be forward-declared
  4725. // within this function.
  4726. if (PFS.resolveForwardRefBlockAddresses())
  4727. return true;
  4728. SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
  4729. // We need at least one basic block.
  4730. if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
  4731. return TokError("function body requires at least one basic block");
  4732. while (Lex.getKind() != lltok::rbrace &&
  4733. Lex.getKind() != lltok::kw_uselistorder)
  4734. if (ParseBasicBlock(PFS)) return true;
  4735. while (Lex.getKind() != lltok::rbrace)
  4736. if (ParseUseListOrder(&PFS))
  4737. return true;
  4738. // Eat the }.
  4739. Lex.Lex();
  4740. // Verify function is ok.
  4741. return PFS.FinishFunction();
  4742. }
  4743. /// ParseBasicBlock
  4744. /// ::= LabelStr? Instruction*
  4745. bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
  4746. // If this basic block starts out with a name, remember it.
  4747. std::string Name;
  4748. LocTy NameLoc = Lex.getLoc();
  4749. if (Lex.getKind() == lltok::LabelStr) {
  4750. Name = Lex.getStrVal();
  4751. Lex.Lex();
  4752. }
  4753. BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
  4754. if (!BB)
  4755. return Error(NameLoc,
  4756. "unable to create block named '" + Name + "'");
  4757. std::string NameStr;
  4758. // Parse the instructions in this block until we get a terminator.
  4759. Instruction *Inst;
  4760. do {
  4761. // This instruction may have three possibilities for a name: a) none
  4762. // specified, b) name specified "%foo =", c) number specified: "%4 =".
  4763. LocTy NameLoc = Lex.getLoc();
  4764. int NameID = -1;
  4765. NameStr = "";
  4766. if (Lex.getKind() == lltok::LocalVarID) {
  4767. NameID = Lex.getUIntVal();
  4768. Lex.Lex();
  4769. if (ParseToken(lltok::equal, "expected '=' after instruction id"))
  4770. return true;
  4771. } else if (Lex.getKind() == lltok::LocalVar) {
  4772. NameStr = Lex.getStrVal();
  4773. Lex.Lex();
  4774. if (ParseToken(lltok::equal, "expected '=' after instruction name"))
  4775. return true;
  4776. }
  4777. switch (ParseInstruction(Inst, BB, PFS)) {
  4778. default: llvm_unreachable("Unknown ParseInstruction result!");
  4779. case InstError: return true;
  4780. case InstNormal:
  4781. BB->getInstList().push_back(Inst);
  4782. // With a normal result, we check to see if the instruction is followed by
  4783. // a comma and metadata.
  4784. if (EatIfPresent(lltok::comma))
  4785. if (ParseInstructionMetadata(*Inst))
  4786. return true;
  4787. break;
  4788. case InstExtraComma:
  4789. BB->getInstList().push_back(Inst);
  4790. // If the instruction parser ate an extra comma at the end of it, it
  4791. // *must* be followed by metadata.
  4792. if (ParseInstructionMetadata(*Inst))
  4793. return true;
  4794. break;
  4795. }
  4796. // Set the name on the instruction.
  4797. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
  4798. } while (!Inst->isTerminator());
  4799. return false;
  4800. }
  4801. //===----------------------------------------------------------------------===//
  4802. // Instruction Parsing.
  4803. //===----------------------------------------------------------------------===//
  4804. /// ParseInstruction - Parse one of the many different instructions.
  4805. ///
  4806. int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
  4807. PerFunctionState &PFS) {
  4808. lltok::Kind Token = Lex.getKind();
  4809. if (Token == lltok::Eof)
  4810. return TokError("found end of file when expecting more instructions");
  4811. LocTy Loc = Lex.getLoc();
  4812. unsigned KeywordVal = Lex.getUIntVal();
  4813. Lex.Lex(); // Eat the keyword.
  4814. switch (Token) {
  4815. default: return Error(Loc, "expected instruction opcode");
  4816. // Terminator Instructions.
  4817. case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
  4818. case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
  4819. case lltok::kw_br: return ParseBr(Inst, PFS);
  4820. case lltok::kw_switch: return ParseSwitch(Inst, PFS);
  4821. case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
  4822. case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
  4823. case lltok::kw_resume: return ParseResume(Inst, PFS);
  4824. case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
  4825. case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
  4826. case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
  4827. case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
  4828. case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
  4829. // Binary Operators.
  4830. case lltok::kw_add:
  4831. case lltok::kw_sub:
  4832. case lltok::kw_mul:
  4833. case lltok::kw_shl: {
  4834. bool NUW = EatIfPresent(lltok::kw_nuw);
  4835. bool NSW = EatIfPresent(lltok::kw_nsw);
  4836. if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
  4837. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  4838. if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
  4839. if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
  4840. return false;
  4841. }
  4842. case lltok::kw_fadd:
  4843. case lltok::kw_fsub:
  4844. case lltok::kw_fmul:
  4845. case lltok::kw_fdiv:
  4846. case lltok::kw_frem: {
  4847. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  4848. int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
  4849. if (Res != 0)
  4850. return Res;
  4851. if (FMF.any())
  4852. Inst->setFastMathFlags(FMF);
  4853. return 0;
  4854. }
  4855. case lltok::kw_sdiv:
  4856. case lltok::kw_udiv:
  4857. case lltok::kw_lshr:
  4858. case lltok::kw_ashr: {
  4859. bool Exact = EatIfPresent(lltok::kw_exact);
  4860. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  4861. if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
  4862. return false;
  4863. }
  4864. case lltok::kw_urem:
  4865. case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
  4866. case lltok::kw_and:
  4867. case lltok::kw_or:
  4868. case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
  4869. case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
  4870. case lltok::kw_fcmp: {
  4871. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  4872. int Res = ParseCompare(Inst, PFS, KeywordVal);
  4873. if (Res != 0)
  4874. return Res;
  4875. if (FMF.any())
  4876. Inst->setFastMathFlags(FMF);
  4877. return 0;
  4878. }
  4879. // Casts.
  4880. case lltok::kw_trunc:
  4881. case lltok::kw_zext:
  4882. case lltok::kw_sext:
  4883. case lltok::kw_fptrunc:
  4884. case lltok::kw_fpext:
  4885. case lltok::kw_bitcast:
  4886. case lltok::kw_addrspacecast:
  4887. case lltok::kw_uitofp:
  4888. case lltok::kw_sitofp:
  4889. case lltok::kw_fptoui:
  4890. case lltok::kw_fptosi:
  4891. case lltok::kw_inttoptr:
  4892. case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
  4893. // Other.
  4894. case lltok::kw_select: return ParseSelect(Inst, PFS);
  4895. case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
  4896. case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
  4897. case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
  4898. case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
  4899. case lltok::kw_phi: return ParsePHI(Inst, PFS);
  4900. case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
  4901. // Call.
  4902. case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
  4903. case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
  4904. case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
  4905. case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
  4906. // Memory.
  4907. case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
  4908. case lltok::kw_load: return ParseLoad(Inst, PFS);
  4909. case lltok::kw_store: return ParseStore(Inst, PFS);
  4910. case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
  4911. case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
  4912. case lltok::kw_fence: return ParseFence(Inst, PFS);
  4913. case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
  4914. case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
  4915. case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
  4916. }
  4917. }
  4918. /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
  4919. bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
  4920. if (Opc == Instruction::FCmp) {
  4921. switch (Lex.getKind()) {
  4922. default: return TokError("expected fcmp predicate (e.g. 'oeq')");
  4923. case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
  4924. case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
  4925. case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
  4926. case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
  4927. case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
  4928. case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
  4929. case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
  4930. case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
  4931. case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
  4932. case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
  4933. case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
  4934. case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
  4935. case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
  4936. case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
  4937. case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
  4938. case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
  4939. }
  4940. } else {
  4941. switch (Lex.getKind()) {
  4942. default: return TokError("expected icmp predicate (e.g. 'eq')");
  4943. case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
  4944. case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
  4945. case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
  4946. case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
  4947. case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
  4948. case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
  4949. case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
  4950. case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
  4951. case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
  4952. case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
  4953. }
  4954. }
  4955. Lex.Lex();
  4956. return false;
  4957. }
  4958. //===----------------------------------------------------------------------===//
  4959. // Terminator Instructions.
  4960. //===----------------------------------------------------------------------===//
  4961. /// ParseRet - Parse a return instruction.
  4962. /// ::= 'ret' void (',' !dbg, !1)*
  4963. /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
  4964. bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
  4965. PerFunctionState &PFS) {
  4966. SMLoc TypeLoc = Lex.getLoc();
  4967. Type *Ty = nullptr;
  4968. if (ParseType(Ty, true /*void allowed*/)) return true;
  4969. Type *ResType = PFS.getFunction().getReturnType();
  4970. if (Ty->isVoidTy()) {
  4971. if (!ResType->isVoidTy())
  4972. return Error(TypeLoc, "value doesn't match function result type '" +
  4973. getTypeString(ResType) + "'");
  4974. Inst = ReturnInst::Create(Context);
  4975. return false;
  4976. }
  4977. Value *RV;
  4978. if (ParseValue(Ty, RV, PFS)) return true;
  4979. if (ResType != RV->getType())
  4980. return Error(TypeLoc, "value doesn't match function result type '" +
  4981. getTypeString(ResType) + "'");
  4982. Inst = ReturnInst::Create(Context, RV);
  4983. return false;
  4984. }
  4985. /// ParseBr
  4986. /// ::= 'br' TypeAndValue
  4987. /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  4988. bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
  4989. LocTy Loc, Loc2;
  4990. Value *Op0;
  4991. BasicBlock *Op1, *Op2;
  4992. if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
  4993. if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
  4994. Inst = BranchInst::Create(BB);
  4995. return false;
  4996. }
  4997. if (Op0->getType() != Type::getInt1Ty(Context))
  4998. return Error(Loc, "branch condition must have 'i1' type");
  4999. if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
  5000. ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
  5001. ParseToken(lltok::comma, "expected ',' after true destination") ||
  5002. ParseTypeAndBasicBlock(Op2, Loc2, PFS))
  5003. return true;
  5004. Inst = BranchInst::Create(Op1, Op2, Op0);
  5005. return false;
  5006. }
  5007. /// ParseSwitch
  5008. /// Instruction
  5009. /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
  5010. /// JumpTable
  5011. /// ::= (TypeAndValue ',' TypeAndValue)*
  5012. bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  5013. LocTy CondLoc, BBLoc;
  5014. Value *Cond;
  5015. BasicBlock *DefaultBB;
  5016. if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
  5017. ParseToken(lltok::comma, "expected ',' after switch condition") ||
  5018. ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
  5019. ParseToken(lltok::lsquare, "expected '[' with switch table"))
  5020. return true;
  5021. if (!Cond->getType()->isIntegerTy())
  5022. return Error(CondLoc, "switch condition must have integer type");
  5023. // Parse the jump table pairs.
  5024. SmallPtrSet<Value*, 32> SeenCases;
  5025. SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
  5026. while (Lex.getKind() != lltok::rsquare) {
  5027. Value *Constant;
  5028. BasicBlock *DestBB;
  5029. if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
  5030. ParseToken(lltok::comma, "expected ',' after case value") ||
  5031. ParseTypeAndBasicBlock(DestBB, PFS))
  5032. return true;
  5033. if (!SeenCases.insert(Constant).second)
  5034. return Error(CondLoc, "duplicate case value in switch");
  5035. if (!isa<ConstantInt>(Constant))
  5036. return Error(CondLoc, "case value is not a constant integer");
  5037. Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
  5038. }
  5039. Lex.Lex(); // Eat the ']'.
  5040. SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
  5041. for (unsigned i = 0, e = Table.size(); i != e; ++i)
  5042. SI->addCase(Table[i].first, Table[i].second);
  5043. Inst = SI;
  5044. return false;
  5045. }
  5046. /// ParseIndirectBr
  5047. /// Instruction
  5048. /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
  5049. bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
  5050. LocTy AddrLoc;
  5051. Value *Address;
  5052. if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
  5053. ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
  5054. ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
  5055. return true;
  5056. if (!Address->getType()->isPointerTy())
  5057. return Error(AddrLoc, "indirectbr address must have pointer type");
  5058. // Parse the destination list.
  5059. SmallVector<BasicBlock*, 16> DestList;
  5060. if (Lex.getKind() != lltok::rsquare) {
  5061. BasicBlock *DestBB;
  5062. if (ParseTypeAndBasicBlock(DestBB, PFS))
  5063. return true;
  5064. DestList.push_back(DestBB);
  5065. while (EatIfPresent(lltok::comma)) {
  5066. if (ParseTypeAndBasicBlock(DestBB, PFS))
  5067. return true;
  5068. DestList.push_back(DestBB);
  5069. }
  5070. }
  5071. if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
  5072. return true;
  5073. IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
  5074. for (unsigned i = 0, e = DestList.size(); i != e; ++i)
  5075. IBI->addDestination(DestList[i]);
  5076. Inst = IBI;
  5077. return false;
  5078. }
  5079. /// ParseInvoke
  5080. /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
  5081. /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
  5082. bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
  5083. LocTy CallLoc = Lex.getLoc();
  5084. AttrBuilder RetAttrs, FnAttrs;
  5085. std::vector<unsigned> FwdRefAttrGrps;
  5086. LocTy NoBuiltinLoc;
  5087. unsigned CC;
  5088. unsigned InvokeAddrSpace;
  5089. Type *RetType = nullptr;
  5090. LocTy RetTypeLoc;
  5091. ValID CalleeID;
  5092. SmallVector<ParamInfo, 16> ArgList;
  5093. SmallVector<OperandBundleDef, 2> BundleList;
  5094. BasicBlock *NormalBB, *UnwindBB;
  5095. if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  5096. ParseOptionalProgramAddrSpace(InvokeAddrSpace) ||
  5097. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  5098. ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
  5099. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  5100. NoBuiltinLoc) ||
  5101. ParseOptionalOperandBundles(BundleList, PFS) ||
  5102. ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
  5103. ParseTypeAndBasicBlock(NormalBB, PFS) ||
  5104. ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
  5105. ParseTypeAndBasicBlock(UnwindBB, PFS))
  5106. return true;
  5107. // If RetType is a non-function pointer type, then this is the short syntax
  5108. // for the call, which means that RetType is just the return type. Infer the
  5109. // rest of the function argument types from the arguments that are present.
  5110. FunctionType *Ty = dyn_cast<FunctionType>(RetType);
  5111. if (!Ty) {
  5112. // Pull out the types of all of the arguments...
  5113. std::vector<Type*> ParamTypes;
  5114. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  5115. ParamTypes.push_back(ArgList[i].V->getType());
  5116. if (!FunctionType::isValidReturnType(RetType))
  5117. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  5118. Ty = FunctionType::get(RetType, ParamTypes, false);
  5119. }
  5120. CalleeID.FTy = Ty;
  5121. // Look up the callee.
  5122. Value *Callee;
  5123. if (ConvertValIDToValue(PointerType::get(Ty, InvokeAddrSpace), CalleeID,
  5124. Callee, &PFS, /*IsCall=*/true))
  5125. return true;
  5126. // Set up the Attribute for the function.
  5127. SmallVector<Value *, 8> Args;
  5128. SmallVector<AttributeSet, 8> ArgAttrs;
  5129. // Loop through FunctionType's arguments and ensure they are specified
  5130. // correctly. Also, gather any parameter attributes.
  5131. FunctionType::param_iterator I = Ty->param_begin();
  5132. FunctionType::param_iterator E = Ty->param_end();
  5133. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  5134. Type *ExpectedTy = nullptr;
  5135. if (I != E) {
  5136. ExpectedTy = *I++;
  5137. } else if (!Ty->isVarArg()) {
  5138. return Error(ArgList[i].Loc, "too many arguments specified");
  5139. }
  5140. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  5141. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  5142. getTypeString(ExpectedTy) + "'");
  5143. Args.push_back(ArgList[i].V);
  5144. ArgAttrs.push_back(ArgList[i].Attrs);
  5145. }
  5146. if (I != E)
  5147. return Error(CallLoc, "not enough parameters specified for call");
  5148. if (FnAttrs.hasAlignmentAttr())
  5149. return Error(CallLoc, "invoke instructions may not have an alignment");
  5150. // Finish off the Attribute and check them
  5151. AttributeList PAL =
  5152. AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
  5153. AttributeSet::get(Context, RetAttrs), ArgAttrs);
  5154. InvokeInst *II =
  5155. InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
  5156. II->setCallingConv(CC);
  5157. II->setAttributes(PAL);
  5158. ForwardRefAttrGroups[II] = FwdRefAttrGrps;
  5159. Inst = II;
  5160. return false;
  5161. }
  5162. /// ParseResume
  5163. /// ::= 'resume' TypeAndValue
  5164. bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
  5165. Value *Exn; LocTy ExnLoc;
  5166. if (ParseTypeAndValue(Exn, ExnLoc, PFS))
  5167. return true;
  5168. ResumeInst *RI = ResumeInst::Create(Exn);
  5169. Inst = RI;
  5170. return false;
  5171. }
  5172. bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
  5173. PerFunctionState &PFS) {
  5174. if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
  5175. return true;
  5176. while (Lex.getKind() != lltok::rsquare) {
  5177. // If this isn't the first argument, we need a comma.
  5178. if (!Args.empty() &&
  5179. ParseToken(lltok::comma, "expected ',' in argument list"))
  5180. return true;
  5181. // Parse the argument.
  5182. LocTy ArgLoc;
  5183. Type *ArgTy = nullptr;
  5184. if (ParseType(ArgTy, ArgLoc))
  5185. return true;
  5186. Value *V;
  5187. if (ArgTy->isMetadataTy()) {
  5188. if (ParseMetadataAsValue(V, PFS))
  5189. return true;
  5190. } else {
  5191. if (ParseValue(ArgTy, V, PFS))
  5192. return true;
  5193. }
  5194. Args.push_back(V);
  5195. }
  5196. Lex.Lex(); // Lex the ']'.
  5197. return false;
  5198. }
  5199. /// ParseCleanupRet
  5200. /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
  5201. bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
  5202. Value *CleanupPad = nullptr;
  5203. if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
  5204. return true;
  5205. if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
  5206. return true;
  5207. if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
  5208. return true;
  5209. BasicBlock *UnwindBB = nullptr;
  5210. if (Lex.getKind() == lltok::kw_to) {
  5211. Lex.Lex();
  5212. if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
  5213. return true;
  5214. } else {
  5215. if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
  5216. return true;
  5217. }
  5218. }
  5219. Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
  5220. return false;
  5221. }
  5222. /// ParseCatchRet
  5223. /// ::= 'catchret' from Parent Value 'to' TypeAndValue
  5224. bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
  5225. Value *CatchPad = nullptr;
  5226. if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
  5227. return true;
  5228. if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
  5229. return true;
  5230. BasicBlock *BB;
  5231. if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
  5232. ParseTypeAndBasicBlock(BB, PFS))
  5233. return true;
  5234. Inst = CatchReturnInst::Create(CatchPad, BB);
  5235. return false;
  5236. }
  5237. /// ParseCatchSwitch
  5238. /// ::= 'catchswitch' within Parent
  5239. bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  5240. Value *ParentPad;
  5241. if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
  5242. return true;
  5243. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  5244. Lex.getKind() != lltok::LocalVarID)
  5245. return TokError("expected scope value for catchswitch");
  5246. if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
  5247. return true;
  5248. if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
  5249. return true;
  5250. SmallVector<BasicBlock *, 32> Table;
  5251. do {
  5252. BasicBlock *DestBB;
  5253. if (ParseTypeAndBasicBlock(DestBB, PFS))
  5254. return true;
  5255. Table.push_back(DestBB);
  5256. } while (EatIfPresent(lltok::comma));
  5257. if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
  5258. return true;
  5259. if (ParseToken(lltok::kw_unwind,
  5260. "expected 'unwind' after catchswitch scope"))
  5261. return true;
  5262. BasicBlock *UnwindBB = nullptr;
  5263. if (EatIfPresent(lltok::kw_to)) {
  5264. if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
  5265. return true;
  5266. } else {
  5267. if (ParseTypeAndBasicBlock(UnwindBB, PFS))
  5268. return true;
  5269. }
  5270. auto *CatchSwitch =
  5271. CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
  5272. for (BasicBlock *DestBB : Table)
  5273. CatchSwitch->addHandler(DestBB);
  5274. Inst = CatchSwitch;
  5275. return false;
  5276. }
  5277. /// ParseCatchPad
  5278. /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
  5279. bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
  5280. Value *CatchSwitch = nullptr;
  5281. if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
  5282. return true;
  5283. if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
  5284. return TokError("expected scope value for catchpad");
  5285. if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
  5286. return true;
  5287. SmallVector<Value *, 8> Args;
  5288. if (ParseExceptionArgs(Args, PFS))
  5289. return true;
  5290. Inst = CatchPadInst::Create(CatchSwitch, Args);
  5291. return false;
  5292. }
  5293. /// ParseCleanupPad
  5294. /// ::= 'cleanuppad' within Parent ParamList
  5295. bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
  5296. Value *ParentPad = nullptr;
  5297. if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
  5298. return true;
  5299. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  5300. Lex.getKind() != lltok::LocalVarID)
  5301. return TokError("expected scope value for cleanuppad");
  5302. if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
  5303. return true;
  5304. SmallVector<Value *, 8> Args;
  5305. if (ParseExceptionArgs(Args, PFS))
  5306. return true;
  5307. Inst = CleanupPadInst::Create(ParentPad, Args);
  5308. return false;
  5309. }
  5310. //===----------------------------------------------------------------------===//
  5311. // Binary Operators.
  5312. //===----------------------------------------------------------------------===//
  5313. /// ParseArithmetic
  5314. /// ::= ArithmeticOps TypeAndValue ',' Value
  5315. ///
  5316. /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
  5317. /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
  5318. bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
  5319. unsigned Opc, unsigned OperandType) {
  5320. LocTy Loc; Value *LHS, *RHS;
  5321. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  5322. ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
  5323. ParseValue(LHS->getType(), RHS, PFS))
  5324. return true;
  5325. bool Valid;
  5326. switch (OperandType) {
  5327. default: llvm_unreachable("Unknown operand type!");
  5328. case 0: // int or FP.
  5329. Valid = LHS->getType()->isIntOrIntVectorTy() ||
  5330. LHS->getType()->isFPOrFPVectorTy();
  5331. break;
  5332. case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
  5333. case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
  5334. }
  5335. if (!Valid)
  5336. return Error(Loc, "invalid operand type for instruction");
  5337. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  5338. return false;
  5339. }
  5340. /// ParseLogical
  5341. /// ::= ArithmeticOps TypeAndValue ',' Value {
  5342. bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
  5343. unsigned Opc) {
  5344. LocTy Loc; Value *LHS, *RHS;
  5345. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  5346. ParseToken(lltok::comma, "expected ',' in logical operation") ||
  5347. ParseValue(LHS->getType(), RHS, PFS))
  5348. return true;
  5349. if (!LHS->getType()->isIntOrIntVectorTy())
  5350. return Error(Loc,"instruction requires integer or integer vector operands");
  5351. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  5352. return false;
  5353. }
  5354. /// ParseCompare
  5355. /// ::= 'icmp' IPredicates TypeAndValue ',' Value
  5356. /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
  5357. bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
  5358. unsigned Opc) {
  5359. // Parse the integer/fp comparison predicate.
  5360. LocTy Loc;
  5361. unsigned Pred;
  5362. Value *LHS, *RHS;
  5363. if (ParseCmpPredicate(Pred, Opc) ||
  5364. ParseTypeAndValue(LHS, Loc, PFS) ||
  5365. ParseToken(lltok::comma, "expected ',' after compare value") ||
  5366. ParseValue(LHS->getType(), RHS, PFS))
  5367. return true;
  5368. if (Opc == Instruction::FCmp) {
  5369. if (!LHS->getType()->isFPOrFPVectorTy())
  5370. return Error(Loc, "fcmp requires floating point operands");
  5371. Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  5372. } else {
  5373. assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
  5374. if (!LHS->getType()->isIntOrIntVectorTy() &&
  5375. !LHS->getType()->isPtrOrPtrVectorTy())
  5376. return Error(Loc, "icmp requires integer operands");
  5377. Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  5378. }
  5379. return false;
  5380. }
  5381. //===----------------------------------------------------------------------===//
  5382. // Other Instructions.
  5383. //===----------------------------------------------------------------------===//
  5384. /// ParseCast
  5385. /// ::= CastOpc TypeAndValue 'to' Type
  5386. bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
  5387. unsigned Opc) {
  5388. LocTy Loc;
  5389. Value *Op;
  5390. Type *DestTy = nullptr;
  5391. if (ParseTypeAndValue(Op, Loc, PFS) ||
  5392. ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
  5393. ParseType(DestTy))
  5394. return true;
  5395. if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
  5396. CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
  5397. return Error(Loc, "invalid cast opcode for cast from '" +
  5398. getTypeString(Op->getType()) + "' to '" +
  5399. getTypeString(DestTy) + "'");
  5400. }
  5401. Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
  5402. return false;
  5403. }
  5404. /// ParseSelect
  5405. /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  5406. bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
  5407. LocTy Loc;
  5408. Value *Op0, *Op1, *Op2;
  5409. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5410. ParseToken(lltok::comma, "expected ',' after select condition") ||
  5411. ParseTypeAndValue(Op1, PFS) ||
  5412. ParseToken(lltok::comma, "expected ',' after select value") ||
  5413. ParseTypeAndValue(Op2, PFS))
  5414. return true;
  5415. if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
  5416. return Error(Loc, Reason);
  5417. Inst = SelectInst::Create(Op0, Op1, Op2);
  5418. return false;
  5419. }
  5420. /// ParseVA_Arg
  5421. /// ::= 'va_arg' TypeAndValue ',' Type
  5422. bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
  5423. Value *Op;
  5424. Type *EltTy = nullptr;
  5425. LocTy TypeLoc;
  5426. if (ParseTypeAndValue(Op, PFS) ||
  5427. ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
  5428. ParseType(EltTy, TypeLoc))
  5429. return true;
  5430. if (!EltTy->isFirstClassType())
  5431. return Error(TypeLoc, "va_arg requires operand with first class type");
  5432. Inst = new VAArgInst(Op, EltTy);
  5433. return false;
  5434. }
  5435. /// ParseExtractElement
  5436. /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
  5437. bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
  5438. LocTy Loc;
  5439. Value *Op0, *Op1;
  5440. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5441. ParseToken(lltok::comma, "expected ',' after extract value") ||
  5442. ParseTypeAndValue(Op1, PFS))
  5443. return true;
  5444. if (!ExtractElementInst::isValidOperands(Op0, Op1))
  5445. return Error(Loc, "invalid extractelement operands");
  5446. Inst = ExtractElementInst::Create(Op0, Op1);
  5447. return false;
  5448. }
  5449. /// ParseInsertElement
  5450. /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  5451. bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
  5452. LocTy Loc;
  5453. Value *Op0, *Op1, *Op2;
  5454. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5455. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5456. ParseTypeAndValue(Op1, PFS) ||
  5457. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5458. ParseTypeAndValue(Op2, PFS))
  5459. return true;
  5460. if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
  5461. return Error(Loc, "invalid insertelement operands");
  5462. Inst = InsertElementInst::Create(Op0, Op1, Op2);
  5463. return false;
  5464. }
  5465. /// ParseShuffleVector
  5466. /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  5467. bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
  5468. LocTy Loc;
  5469. Value *Op0, *Op1, *Op2;
  5470. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5471. ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
  5472. ParseTypeAndValue(Op1, PFS) ||
  5473. ParseToken(lltok::comma, "expected ',' after shuffle value") ||
  5474. ParseTypeAndValue(Op2, PFS))
  5475. return true;
  5476. if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
  5477. return Error(Loc, "invalid shufflevector operands");
  5478. Inst = new ShuffleVectorInst(Op0, Op1, Op2);
  5479. return false;
  5480. }
  5481. /// ParsePHI
  5482. /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
  5483. int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
  5484. Type *Ty = nullptr; LocTy TypeLoc;
  5485. Value *Op0, *Op1;
  5486. if (ParseType(Ty, TypeLoc) ||
  5487. ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  5488. ParseValue(Ty, Op0, PFS) ||
  5489. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5490. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  5491. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  5492. return true;
  5493. bool AteExtraComma = false;
  5494. SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
  5495. while (true) {
  5496. PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
  5497. if (!EatIfPresent(lltok::comma))
  5498. break;
  5499. if (Lex.getKind() == lltok::MetadataVar) {
  5500. AteExtraComma = true;
  5501. break;
  5502. }
  5503. if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  5504. ParseValue(Ty, Op0, PFS) ||
  5505. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5506. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  5507. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  5508. return true;
  5509. }
  5510. if (!Ty->isFirstClassType())
  5511. return Error(TypeLoc, "phi node must have first class type");
  5512. PHINode *PN = PHINode::Create(Ty, PHIVals.size());
  5513. for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
  5514. PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
  5515. Inst = PN;
  5516. return AteExtraComma ? InstExtraComma : InstNormal;
  5517. }
  5518. /// ParseLandingPad
  5519. /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
  5520. /// Clause
  5521. /// ::= 'catch' TypeAndValue
  5522. /// ::= 'filter'
  5523. /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
  5524. bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
  5525. Type *Ty = nullptr; LocTy TyLoc;
  5526. if (ParseType(Ty, TyLoc))
  5527. return true;
  5528. std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
  5529. LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
  5530. while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
  5531. LandingPadInst::ClauseType CT;
  5532. if (EatIfPresent(lltok::kw_catch))
  5533. CT = LandingPadInst::Catch;
  5534. else if (EatIfPresent(lltok::kw_filter))
  5535. CT = LandingPadInst::Filter;
  5536. else
  5537. return TokError("expected 'catch' or 'filter' clause type");
  5538. Value *V;
  5539. LocTy VLoc;
  5540. if (ParseTypeAndValue(V, VLoc, PFS))
  5541. return true;
  5542. // A 'catch' type expects a non-array constant. A filter clause expects an
  5543. // array constant.
  5544. if (CT == LandingPadInst::Catch) {
  5545. if (isa<ArrayType>(V->getType()))
  5546. Error(VLoc, "'catch' clause has an invalid type");
  5547. } else {
  5548. if (!isa<ArrayType>(V->getType()))
  5549. Error(VLoc, "'filter' clause has an invalid type");
  5550. }
  5551. Constant *CV = dyn_cast<Constant>(V);
  5552. if (!CV)
  5553. return Error(VLoc, "clause argument must be a constant");
  5554. LP->addClause(CV);
  5555. }
  5556. Inst = LP.release();
  5557. return false;
  5558. }
  5559. /// ParseCall
  5560. /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
  5561. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5562. /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
  5563. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5564. /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
  5565. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5566. /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
  5567. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5568. bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
  5569. CallInst::TailCallKind TCK) {
  5570. AttrBuilder RetAttrs, FnAttrs;
  5571. std::vector<unsigned> FwdRefAttrGrps;
  5572. LocTy BuiltinLoc;
  5573. unsigned CallAddrSpace;
  5574. unsigned CC;
  5575. Type *RetType = nullptr;
  5576. LocTy RetTypeLoc;
  5577. ValID CalleeID;
  5578. SmallVector<ParamInfo, 16> ArgList;
  5579. SmallVector<OperandBundleDef, 2> BundleList;
  5580. LocTy CallLoc = Lex.getLoc();
  5581. if (TCK != CallInst::TCK_None &&
  5582. ParseToken(lltok::kw_call,
  5583. "expected 'tail call', 'musttail call', or 'notail call'"))
  5584. return true;
  5585. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5586. if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  5587. ParseOptionalProgramAddrSpace(CallAddrSpace) ||
  5588. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  5589. ParseValID(CalleeID) ||
  5590. ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
  5591. PFS.getFunction().isVarArg()) ||
  5592. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
  5593. ParseOptionalOperandBundles(BundleList, PFS))
  5594. return true;
  5595. if (FMF.any() && !RetType->isFPOrFPVectorTy())
  5596. return Error(CallLoc, "fast-math-flags specified for call without "
  5597. "floating-point scalar or vector return type");
  5598. // If RetType is a non-function pointer type, then this is the short syntax
  5599. // for the call, which means that RetType is just the return type. Infer the
  5600. // rest of the function argument types from the arguments that are present.
  5601. FunctionType *Ty = dyn_cast<FunctionType>(RetType);
  5602. if (!Ty) {
  5603. // Pull out the types of all of the arguments...
  5604. std::vector<Type*> ParamTypes;
  5605. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  5606. ParamTypes.push_back(ArgList[i].V->getType());
  5607. if (!FunctionType::isValidReturnType(RetType))
  5608. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  5609. Ty = FunctionType::get(RetType, ParamTypes, false);
  5610. }
  5611. CalleeID.FTy = Ty;
  5612. // Look up the callee.
  5613. Value *Callee;
  5614. if (ConvertValIDToValue(PointerType::get(Ty, CallAddrSpace), CalleeID, Callee,
  5615. &PFS, /*IsCall=*/true))
  5616. return true;
  5617. // Set up the Attribute for the function.
  5618. SmallVector<AttributeSet, 8> Attrs;
  5619. SmallVector<Value*, 8> Args;
  5620. // Loop through FunctionType's arguments and ensure they are specified
  5621. // correctly. Also, gather any parameter attributes.
  5622. FunctionType::param_iterator I = Ty->param_begin();
  5623. FunctionType::param_iterator E = Ty->param_end();
  5624. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  5625. Type *ExpectedTy = nullptr;
  5626. if (I != E) {
  5627. ExpectedTy = *I++;
  5628. } else if (!Ty->isVarArg()) {
  5629. return Error(ArgList[i].Loc, "too many arguments specified");
  5630. }
  5631. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  5632. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  5633. getTypeString(ExpectedTy) + "'");
  5634. Args.push_back(ArgList[i].V);
  5635. Attrs.push_back(ArgList[i].Attrs);
  5636. }
  5637. if (I != E)
  5638. return Error(CallLoc, "not enough parameters specified for call");
  5639. if (FnAttrs.hasAlignmentAttr())
  5640. return Error(CallLoc, "call instructions may not have an alignment");
  5641. // Finish off the Attribute and check them
  5642. AttributeList PAL =
  5643. AttributeList::get(Context, AttributeSet::get(Context, FnAttrs),
  5644. AttributeSet::get(Context, RetAttrs), Attrs);
  5645. CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
  5646. CI->setTailCallKind(TCK);
  5647. CI->setCallingConv(CC);
  5648. if (FMF.any())
  5649. CI->setFastMathFlags(FMF);
  5650. CI->setAttributes(PAL);
  5651. ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
  5652. Inst = CI;
  5653. return false;
  5654. }
  5655. //===----------------------------------------------------------------------===//
  5656. // Memory Instructions.
  5657. //===----------------------------------------------------------------------===//
  5658. /// ParseAlloc
  5659. /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
  5660. /// (',' 'align' i32)? (',', 'addrspace(n))?
  5661. int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
  5662. Value *Size = nullptr;
  5663. LocTy SizeLoc, TyLoc, ASLoc;
  5664. unsigned Alignment = 0;
  5665. unsigned AddrSpace = 0;
  5666. Type *Ty = nullptr;
  5667. bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
  5668. bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
  5669. if (ParseType(Ty, TyLoc)) return true;
  5670. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  5671. return Error(TyLoc, "invalid type for alloca");
  5672. bool AteExtraComma = false;
  5673. if (EatIfPresent(lltok::comma)) {
  5674. if (Lex.getKind() == lltok::kw_align) {
  5675. if (ParseOptionalAlignment(Alignment))
  5676. return true;
  5677. if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
  5678. return true;
  5679. } else if (Lex.getKind() == lltok::kw_addrspace) {
  5680. ASLoc = Lex.getLoc();
  5681. if (ParseOptionalAddrSpace(AddrSpace))
  5682. return true;
  5683. } else if (Lex.getKind() == lltok::MetadataVar) {
  5684. AteExtraComma = true;
  5685. } else {
  5686. if (ParseTypeAndValue(Size, SizeLoc, PFS))
  5687. return true;
  5688. if (EatIfPresent(lltok::comma)) {
  5689. if (Lex.getKind() == lltok::kw_align) {
  5690. if (ParseOptionalAlignment(Alignment))
  5691. return true;
  5692. if (ParseOptionalCommaAddrSpace(AddrSpace, ASLoc, AteExtraComma))
  5693. return true;
  5694. } else if (Lex.getKind() == lltok::kw_addrspace) {
  5695. ASLoc = Lex.getLoc();
  5696. if (ParseOptionalAddrSpace(AddrSpace))
  5697. return true;
  5698. } else if (Lex.getKind() == lltok::MetadataVar) {
  5699. AteExtraComma = true;
  5700. }
  5701. }
  5702. }
  5703. }
  5704. if (Size && !Size->getType()->isIntegerTy())
  5705. return Error(SizeLoc, "element count must have integer type");
  5706. AllocaInst *AI = new AllocaInst(Ty, AddrSpace, Size, Alignment);
  5707. AI->setUsedWithInAlloca(IsInAlloca);
  5708. AI->setSwiftError(IsSwiftError);
  5709. Inst = AI;
  5710. return AteExtraComma ? InstExtraComma : InstNormal;
  5711. }
  5712. /// ParseLoad
  5713. /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
  5714. /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
  5715. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  5716. int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
  5717. Value *Val; LocTy Loc;
  5718. unsigned Alignment = 0;
  5719. bool AteExtraComma = false;
  5720. bool isAtomic = false;
  5721. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5722. SyncScope::ID SSID = SyncScope::System;
  5723. if (Lex.getKind() == lltok::kw_atomic) {
  5724. isAtomic = true;
  5725. Lex.Lex();
  5726. }
  5727. bool isVolatile = false;
  5728. if (Lex.getKind() == lltok::kw_volatile) {
  5729. isVolatile = true;
  5730. Lex.Lex();
  5731. }
  5732. Type *Ty;
  5733. LocTy ExplicitTypeLoc = Lex.getLoc();
  5734. if (ParseType(Ty) ||
  5735. ParseToken(lltok::comma, "expected comma after load's type") ||
  5736. ParseTypeAndValue(Val, Loc, PFS) ||
  5737. ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
  5738. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  5739. return true;
  5740. if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
  5741. return Error(Loc, "load operand must be a pointer to a first class type");
  5742. if (isAtomic && !Alignment)
  5743. return Error(Loc, "atomic load must have explicit non-zero alignment");
  5744. if (Ordering == AtomicOrdering::Release ||
  5745. Ordering == AtomicOrdering::AcquireRelease)
  5746. return Error(Loc, "atomic load cannot use Release ordering");
  5747. if (Ty != cast<PointerType>(Val->getType())->getElementType())
  5748. return Error(ExplicitTypeLoc,
  5749. "explicit pointee type doesn't match operand's pointee type");
  5750. Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, SSID);
  5751. return AteExtraComma ? InstExtraComma : InstNormal;
  5752. }
  5753. /// ParseStore
  5754. /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
  5755. /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
  5756. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  5757. int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
  5758. Value *Val, *Ptr; LocTy Loc, PtrLoc;
  5759. unsigned Alignment = 0;
  5760. bool AteExtraComma = false;
  5761. bool isAtomic = false;
  5762. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5763. SyncScope::ID SSID = SyncScope::System;
  5764. if (Lex.getKind() == lltok::kw_atomic) {
  5765. isAtomic = true;
  5766. Lex.Lex();
  5767. }
  5768. bool isVolatile = false;
  5769. if (Lex.getKind() == lltok::kw_volatile) {
  5770. isVolatile = true;
  5771. Lex.Lex();
  5772. }
  5773. if (ParseTypeAndValue(Val, Loc, PFS) ||
  5774. ParseToken(lltok::comma, "expected ',' after store operand") ||
  5775. ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5776. ParseScopeAndOrdering(isAtomic, SSID, Ordering) ||
  5777. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  5778. return true;
  5779. if (!Ptr->getType()->isPointerTy())
  5780. return Error(PtrLoc, "store operand must be a pointer");
  5781. if (!Val->getType()->isFirstClassType())
  5782. return Error(Loc, "store operand must be a first class value");
  5783. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  5784. return Error(Loc, "stored value and pointer type do not match");
  5785. if (isAtomic && !Alignment)
  5786. return Error(Loc, "atomic store must have explicit non-zero alignment");
  5787. if (Ordering == AtomicOrdering::Acquire ||
  5788. Ordering == AtomicOrdering::AcquireRelease)
  5789. return Error(Loc, "atomic store cannot use Acquire ordering");
  5790. Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, SSID);
  5791. return AteExtraComma ? InstExtraComma : InstNormal;
  5792. }
  5793. /// ParseCmpXchg
  5794. /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
  5795. /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
  5796. int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
  5797. Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
  5798. bool AteExtraComma = false;
  5799. AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
  5800. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
  5801. SyncScope::ID SSID = SyncScope::System;
  5802. bool isVolatile = false;
  5803. bool isWeak = false;
  5804. if (EatIfPresent(lltok::kw_weak))
  5805. isWeak = true;
  5806. if (EatIfPresent(lltok::kw_volatile))
  5807. isVolatile = true;
  5808. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5809. ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
  5810. ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
  5811. ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
  5812. ParseTypeAndValue(New, NewLoc, PFS) ||
  5813. ParseScopeAndOrdering(true /*Always atomic*/, SSID, SuccessOrdering) ||
  5814. ParseOrdering(FailureOrdering))
  5815. return true;
  5816. if (SuccessOrdering == AtomicOrdering::Unordered ||
  5817. FailureOrdering == AtomicOrdering::Unordered)
  5818. return TokError("cmpxchg cannot be unordered");
  5819. if (isStrongerThan(FailureOrdering, SuccessOrdering))
  5820. return TokError("cmpxchg failure argument shall be no stronger than the "
  5821. "success argument");
  5822. if (FailureOrdering == AtomicOrdering::Release ||
  5823. FailureOrdering == AtomicOrdering::AcquireRelease)
  5824. return TokError(
  5825. "cmpxchg failure ordering cannot include release semantics");
  5826. if (!Ptr->getType()->isPointerTy())
  5827. return Error(PtrLoc, "cmpxchg operand must be a pointer");
  5828. if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
  5829. return Error(CmpLoc, "compare value and pointer type do not match");
  5830. if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
  5831. return Error(NewLoc, "new value and pointer type do not match");
  5832. if (!New->getType()->isFirstClassType())
  5833. return Error(NewLoc, "cmpxchg operand must be a first class value");
  5834. AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
  5835. Ptr, Cmp, New, SuccessOrdering, FailureOrdering, SSID);
  5836. CXI->setVolatile(isVolatile);
  5837. CXI->setWeak(isWeak);
  5838. Inst = CXI;
  5839. return AteExtraComma ? InstExtraComma : InstNormal;
  5840. }
  5841. /// ParseAtomicRMW
  5842. /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
  5843. /// 'singlethread'? AtomicOrdering
  5844. int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
  5845. Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
  5846. bool AteExtraComma = false;
  5847. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5848. SyncScope::ID SSID = SyncScope::System;
  5849. bool isVolatile = false;
  5850. AtomicRMWInst::BinOp Operation;
  5851. if (EatIfPresent(lltok::kw_volatile))
  5852. isVolatile = true;
  5853. switch (Lex.getKind()) {
  5854. default: return TokError("expected binary operation in atomicrmw");
  5855. case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
  5856. case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
  5857. case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
  5858. case lltok::kw_and: Operation = AtomicRMWInst::And; break;
  5859. case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
  5860. case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
  5861. case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
  5862. case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
  5863. case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
  5864. case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
  5865. case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
  5866. }
  5867. Lex.Lex(); // Eat the operation.
  5868. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5869. ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
  5870. ParseTypeAndValue(Val, ValLoc, PFS) ||
  5871. ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
  5872. return true;
  5873. if (Ordering == AtomicOrdering::Unordered)
  5874. return TokError("atomicrmw cannot be unordered");
  5875. if (!Ptr->getType()->isPointerTy())
  5876. return Error(PtrLoc, "atomicrmw operand must be a pointer");
  5877. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  5878. return Error(ValLoc, "atomicrmw value and pointer type do not match");
  5879. if (!Val->getType()->isIntegerTy()) {
  5880. return Error(ValLoc, "atomicrmw " +
  5881. AtomicRMWInst::getOperationName(Operation) +
  5882. " operand must be an integer");
  5883. }
  5884. unsigned Size = Val->getType()->getPrimitiveSizeInBits();
  5885. if (Size < 8 || (Size & (Size - 1)))
  5886. return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
  5887. " integer");
  5888. AtomicRMWInst *RMWI =
  5889. new AtomicRMWInst(Operation, Ptr, Val, Ordering, SSID);
  5890. RMWI->setVolatile(isVolatile);
  5891. Inst = RMWI;
  5892. return AteExtraComma ? InstExtraComma : InstNormal;
  5893. }
  5894. /// ParseFence
  5895. /// ::= 'fence' 'singlethread'? AtomicOrdering
  5896. int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
  5897. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5898. SyncScope::ID SSID = SyncScope::System;
  5899. if (ParseScopeAndOrdering(true /*Always atomic*/, SSID, Ordering))
  5900. return true;
  5901. if (Ordering == AtomicOrdering::Unordered)
  5902. return TokError("fence cannot be unordered");
  5903. if (Ordering == AtomicOrdering::Monotonic)
  5904. return TokError("fence cannot be monotonic");
  5905. Inst = new FenceInst(Context, Ordering, SSID);
  5906. return InstNormal;
  5907. }
  5908. /// ParseGetElementPtr
  5909. /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
  5910. int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
  5911. Value *Ptr = nullptr;
  5912. Value *Val = nullptr;
  5913. LocTy Loc, EltLoc;
  5914. bool InBounds = EatIfPresent(lltok::kw_inbounds);
  5915. Type *Ty = nullptr;
  5916. LocTy ExplicitTypeLoc = Lex.getLoc();
  5917. if (ParseType(Ty) ||
  5918. ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
  5919. ParseTypeAndValue(Ptr, Loc, PFS))
  5920. return true;
  5921. Type *BaseType = Ptr->getType();
  5922. PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
  5923. if (!BasePointerType)
  5924. return Error(Loc, "base of getelementptr must be a pointer");
  5925. if (Ty != BasePointerType->getElementType())
  5926. return Error(ExplicitTypeLoc,
  5927. "explicit pointee type doesn't match operand's pointee type");
  5928. SmallVector<Value*, 16> Indices;
  5929. bool AteExtraComma = false;
  5930. // GEP returns a vector of pointers if at least one of parameters is a vector.
  5931. // All vector parameters should have the same vector width.
  5932. unsigned GEPWidth = BaseType->isVectorTy() ?
  5933. BaseType->getVectorNumElements() : 0;
  5934. while (EatIfPresent(lltok::comma)) {
  5935. if (Lex.getKind() == lltok::MetadataVar) {
  5936. AteExtraComma = true;
  5937. break;
  5938. }
  5939. if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
  5940. if (!Val->getType()->isIntOrIntVectorTy())
  5941. return Error(EltLoc, "getelementptr index must be an integer");
  5942. if (Val->getType()->isVectorTy()) {
  5943. unsigned ValNumEl = Val->getType()->getVectorNumElements();
  5944. if (GEPWidth && GEPWidth != ValNumEl)
  5945. return Error(EltLoc,
  5946. "getelementptr vector index has a wrong number of elements");
  5947. GEPWidth = ValNumEl;
  5948. }
  5949. Indices.push_back(Val);
  5950. }
  5951. SmallPtrSet<Type*, 4> Visited;
  5952. if (!Indices.empty() && !Ty->isSized(&Visited))
  5953. return Error(Loc, "base element of getelementptr must be sized");
  5954. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  5955. return Error(Loc, "invalid getelementptr indices");
  5956. Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
  5957. if (InBounds)
  5958. cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
  5959. return AteExtraComma ? InstExtraComma : InstNormal;
  5960. }
  5961. /// ParseExtractValue
  5962. /// ::= 'extractvalue' TypeAndValue (',' uint32)+
  5963. int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
  5964. Value *Val; LocTy Loc;
  5965. SmallVector<unsigned, 4> Indices;
  5966. bool AteExtraComma;
  5967. if (ParseTypeAndValue(Val, Loc, PFS) ||
  5968. ParseIndexList(Indices, AteExtraComma))
  5969. return true;
  5970. if (!Val->getType()->isAggregateType())
  5971. return Error(Loc, "extractvalue operand must be aggregate type");
  5972. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  5973. return Error(Loc, "invalid indices for extractvalue");
  5974. Inst = ExtractValueInst::Create(Val, Indices);
  5975. return AteExtraComma ? InstExtraComma : InstNormal;
  5976. }
  5977. /// ParseInsertValue
  5978. /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
  5979. int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
  5980. Value *Val0, *Val1; LocTy Loc0, Loc1;
  5981. SmallVector<unsigned, 4> Indices;
  5982. bool AteExtraComma;
  5983. if (ParseTypeAndValue(Val0, Loc0, PFS) ||
  5984. ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
  5985. ParseTypeAndValue(Val1, Loc1, PFS) ||
  5986. ParseIndexList(Indices, AteExtraComma))
  5987. return true;
  5988. if (!Val0->getType()->isAggregateType())
  5989. return Error(Loc0, "insertvalue operand must be aggregate type");
  5990. Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
  5991. if (!IndexedType)
  5992. return Error(Loc0, "invalid indices for insertvalue");
  5993. if (IndexedType != Val1->getType())
  5994. return Error(Loc1, "insertvalue operand and field disagree in type: '" +
  5995. getTypeString(Val1->getType()) + "' instead of '" +
  5996. getTypeString(IndexedType) + "'");
  5997. Inst = InsertValueInst::Create(Val0, Val1, Indices);
  5998. return AteExtraComma ? InstExtraComma : InstNormal;
  5999. }
  6000. //===----------------------------------------------------------------------===//
  6001. // Embedded metadata.
  6002. //===----------------------------------------------------------------------===//
  6003. /// ParseMDNodeVector
  6004. /// ::= { Element (',' Element)* }
  6005. /// Element
  6006. /// ::= 'null' | TypeAndValue
  6007. bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
  6008. if (ParseToken(lltok::lbrace, "expected '{' here"))
  6009. return true;
  6010. // Check for an empty list.
  6011. if (EatIfPresent(lltok::rbrace))
  6012. return false;
  6013. do {
  6014. // Null is a special case since it is typeless.
  6015. if (EatIfPresent(lltok::kw_null)) {
  6016. Elts.push_back(nullptr);
  6017. continue;
  6018. }
  6019. Metadata *MD;
  6020. if (ParseMetadata(MD, nullptr))
  6021. return true;
  6022. Elts.push_back(MD);
  6023. } while (EatIfPresent(lltok::comma));
  6024. return ParseToken(lltok::rbrace, "expected end of metadata node");
  6025. }
  6026. //===----------------------------------------------------------------------===//
  6027. // Use-list order directives.
  6028. //===----------------------------------------------------------------------===//
  6029. bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
  6030. SMLoc Loc) {
  6031. if (V->use_empty())
  6032. return Error(Loc, "value has no uses");
  6033. unsigned NumUses = 0;
  6034. SmallDenseMap<const Use *, unsigned, 16> Order;
  6035. for (const Use &U : V->uses()) {
  6036. if (++NumUses > Indexes.size())
  6037. break;
  6038. Order[&U] = Indexes[NumUses - 1];
  6039. }
  6040. if (NumUses < 2)
  6041. return Error(Loc, "value only has one use");
  6042. if (Order.size() != Indexes.size() || NumUses > Indexes.size())
  6043. return Error(Loc,
  6044. "wrong number of indexes, expected " + Twine(V->getNumUses()));
  6045. V->sortUseList([&](const Use &L, const Use &R) {
  6046. return Order.lookup(&L) < Order.lookup(&R);
  6047. });
  6048. return false;
  6049. }
  6050. /// ParseUseListOrderIndexes
  6051. /// ::= '{' uint32 (',' uint32)+ '}'
  6052. bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
  6053. SMLoc Loc = Lex.getLoc();
  6054. if (ParseToken(lltok::lbrace, "expected '{' here"))
  6055. return true;
  6056. if (Lex.getKind() == lltok::rbrace)
  6057. return Lex.Error("expected non-empty list of uselistorder indexes");
  6058. // Use Offset, Max, and IsOrdered to check consistency of indexes. The
  6059. // indexes should be distinct numbers in the range [0, size-1], and should
  6060. // not be in order.
  6061. unsigned Offset = 0;
  6062. unsigned Max = 0;
  6063. bool IsOrdered = true;
  6064. assert(Indexes.empty() && "Expected empty order vector");
  6065. do {
  6066. unsigned Index;
  6067. if (ParseUInt32(Index))
  6068. return true;
  6069. // Update consistency checks.
  6070. Offset += Index - Indexes.size();
  6071. Max = std::max(Max, Index);
  6072. IsOrdered &= Index == Indexes.size();
  6073. Indexes.push_back(Index);
  6074. } while (EatIfPresent(lltok::comma));
  6075. if (ParseToken(lltok::rbrace, "expected '}' here"))
  6076. return true;
  6077. if (Indexes.size() < 2)
  6078. return Error(Loc, "expected >= 2 uselistorder indexes");
  6079. if (Offset != 0 || Max >= Indexes.size())
  6080. return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
  6081. if (IsOrdered)
  6082. return Error(Loc, "expected uselistorder indexes to change the order");
  6083. return false;
  6084. }
  6085. /// ParseUseListOrder
  6086. /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
  6087. bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
  6088. SMLoc Loc = Lex.getLoc();
  6089. if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
  6090. return true;
  6091. Value *V;
  6092. SmallVector<unsigned, 16> Indexes;
  6093. if (ParseTypeAndValue(V, PFS) ||
  6094. ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
  6095. ParseUseListOrderIndexes(Indexes))
  6096. return true;
  6097. return sortUseListOrder(V, Indexes, Loc);
  6098. }
  6099. /// ParseUseListOrderBB
  6100. /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
  6101. bool LLParser::ParseUseListOrderBB() {
  6102. assert(Lex.getKind() == lltok::kw_uselistorder_bb);
  6103. SMLoc Loc = Lex.getLoc();
  6104. Lex.Lex();
  6105. ValID Fn, Label;
  6106. SmallVector<unsigned, 16> Indexes;
  6107. if (ParseValID(Fn) ||
  6108. ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  6109. ParseValID(Label) ||
  6110. ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  6111. ParseUseListOrderIndexes(Indexes))
  6112. return true;
  6113. // Check the function.
  6114. GlobalValue *GV;
  6115. if (Fn.Kind == ValID::t_GlobalName)
  6116. GV = M->getNamedValue(Fn.StrVal);
  6117. else if (Fn.Kind == ValID::t_GlobalID)
  6118. GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
  6119. else
  6120. return Error(Fn.Loc, "expected function name in uselistorder_bb");
  6121. if (!GV)
  6122. return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
  6123. auto *F = dyn_cast<Function>(GV);
  6124. if (!F)
  6125. return Error(Fn.Loc, "expected function name in uselistorder_bb");
  6126. if (F->isDeclaration())
  6127. return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
  6128. // Check the basic block.
  6129. if (Label.Kind == ValID::t_LocalID)
  6130. return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
  6131. if (Label.Kind != ValID::t_LocalName)
  6132. return Error(Label.Loc, "expected basic block name in uselistorder_bb");
  6133. Value *V = F->getValueSymbolTable()->lookup(Label.StrVal);
  6134. if (!V)
  6135. return Error(Label.Loc, "invalid basic block in uselistorder_bb");
  6136. if (!isa<BasicBlock>(V))
  6137. return Error(Label.Loc, "expected basic block in uselistorder_bb");
  6138. return sortUseListOrder(V, Indexes, Loc);
  6139. }
  6140. /// ModuleEntry
  6141. /// ::= 'module' ':' '(' 'path' ':' STRINGCONSTANT ',' 'hash' ':' Hash ')'
  6142. /// Hash ::= '(' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ',' UInt32 ')'
  6143. bool LLParser::ParseModuleEntry(unsigned ID) {
  6144. assert(Lex.getKind() == lltok::kw_module);
  6145. Lex.Lex();
  6146. std::string Path;
  6147. if (ParseToken(lltok::colon, "expected ':' here") ||
  6148. ParseToken(lltok::lparen, "expected '(' here") ||
  6149. ParseToken(lltok::kw_path, "expected 'path' here") ||
  6150. ParseToken(lltok::colon, "expected ':' here") ||
  6151. ParseStringConstant(Path) ||
  6152. ParseToken(lltok::comma, "expected ',' here") ||
  6153. ParseToken(lltok::kw_hash, "expected 'hash' here") ||
  6154. ParseToken(lltok::colon, "expected ':' here") ||
  6155. ParseToken(lltok::lparen, "expected '(' here"))
  6156. return true;
  6157. ModuleHash Hash;
  6158. if (ParseUInt32(Hash[0]) || ParseToken(lltok::comma, "expected ',' here") ||
  6159. ParseUInt32(Hash[1]) || ParseToken(lltok::comma, "expected ',' here") ||
  6160. ParseUInt32(Hash[2]) || ParseToken(lltok::comma, "expected ',' here") ||
  6161. ParseUInt32(Hash[3]) || ParseToken(lltok::comma, "expected ',' here") ||
  6162. ParseUInt32(Hash[4]))
  6163. return true;
  6164. if (ParseToken(lltok::rparen, "expected ')' here") ||
  6165. ParseToken(lltok::rparen, "expected ')' here"))
  6166. return true;
  6167. auto ModuleEntry = Index->addModule(Path, ID, Hash);
  6168. ModuleIdMap[ID] = ModuleEntry->first();
  6169. return false;
  6170. }
  6171. /// TypeIdEntry
  6172. /// ::= 'typeid' ':' '(' 'name' ':' STRINGCONSTANT ',' TypeIdSummary ')'
  6173. bool LLParser::ParseTypeIdEntry(unsigned ID) {
  6174. assert(Lex.getKind() == lltok::kw_typeid);
  6175. Lex.Lex();
  6176. std::string Name;
  6177. if (ParseToken(lltok::colon, "expected ':' here") ||
  6178. ParseToken(lltok::lparen, "expected '(' here") ||
  6179. ParseToken(lltok::kw_name, "expected 'name' here") ||
  6180. ParseToken(lltok::colon, "expected ':' here") ||
  6181. ParseStringConstant(Name))
  6182. return true;
  6183. TypeIdSummary &TIS = Index->getOrInsertTypeIdSummary(Name);
  6184. if (ParseToken(lltok::comma, "expected ',' here") ||
  6185. ParseTypeIdSummary(TIS) || ParseToken(lltok::rparen, "expected ')' here"))
  6186. return true;
  6187. // Check if this ID was forward referenced, and if so, update the
  6188. // corresponding GUIDs.
  6189. auto FwdRefTIDs = ForwardRefTypeIds.find(ID);
  6190. if (FwdRefTIDs != ForwardRefTypeIds.end()) {
  6191. for (auto TIDRef : FwdRefTIDs->second) {
  6192. assert(!*TIDRef.first &&
  6193. "Forward referenced type id GUID expected to be 0");
  6194. *TIDRef.first = GlobalValue::getGUID(Name);
  6195. }
  6196. ForwardRefTypeIds.erase(FwdRefTIDs);
  6197. }
  6198. return false;
  6199. }
  6200. /// TypeIdSummary
  6201. /// ::= 'summary' ':' '(' TypeTestResolution [',' OptionalWpdResolutions]? ')'
  6202. bool LLParser::ParseTypeIdSummary(TypeIdSummary &TIS) {
  6203. if (ParseToken(lltok::kw_summary, "expected 'summary' here") ||
  6204. ParseToken(lltok::colon, "expected ':' here") ||
  6205. ParseToken(lltok::lparen, "expected '(' here") ||
  6206. ParseTypeTestResolution(TIS.TTRes))
  6207. return true;
  6208. if (EatIfPresent(lltok::comma)) {
  6209. // Expect optional wpdResolutions field
  6210. if (ParseOptionalWpdResolutions(TIS.WPDRes))
  6211. return true;
  6212. }
  6213. if (ParseToken(lltok::rparen, "expected ')' here"))
  6214. return true;
  6215. return false;
  6216. }
  6217. /// TypeTestResolution
  6218. /// ::= 'typeTestRes' ':' '(' 'kind' ':'
  6219. /// ( 'unsat' | 'byteArray' | 'inline' | 'single' | 'allOnes' ) ','
  6220. /// 'sizeM1BitWidth' ':' SizeM1BitWidth [',' 'alignLog2' ':' UInt64]?
  6221. /// [',' 'sizeM1' ':' UInt64]? [',' 'bitMask' ':' UInt8]?
  6222. /// [',' 'inlinesBits' ':' UInt64]? ')'
  6223. bool LLParser::ParseTypeTestResolution(TypeTestResolution &TTRes) {
  6224. if (ParseToken(lltok::kw_typeTestRes, "expected 'typeTestRes' here") ||
  6225. ParseToken(lltok::colon, "expected ':' here") ||
  6226. ParseToken(lltok::lparen, "expected '(' here") ||
  6227. ParseToken(lltok::kw_kind, "expected 'kind' here") ||
  6228. ParseToken(lltok::colon, "expected ':' here"))
  6229. return true;
  6230. switch (Lex.getKind()) {
  6231. case lltok::kw_unsat:
  6232. TTRes.TheKind = TypeTestResolution::Unsat;
  6233. break;
  6234. case lltok::kw_byteArray:
  6235. TTRes.TheKind = TypeTestResolution::ByteArray;
  6236. break;
  6237. case lltok::kw_inline:
  6238. TTRes.TheKind = TypeTestResolution::Inline;
  6239. break;
  6240. case lltok::kw_single:
  6241. TTRes.TheKind = TypeTestResolution::Single;
  6242. break;
  6243. case lltok::kw_allOnes:
  6244. TTRes.TheKind = TypeTestResolution::AllOnes;
  6245. break;
  6246. default:
  6247. return Error(Lex.getLoc(), "unexpected TypeTestResolution kind");
  6248. }
  6249. Lex.Lex();
  6250. if (ParseToken(lltok::comma, "expected ',' here") ||
  6251. ParseToken(lltok::kw_sizeM1BitWidth, "expected 'sizeM1BitWidth' here") ||
  6252. ParseToken(lltok::colon, "expected ':' here") ||
  6253. ParseUInt32(TTRes.SizeM1BitWidth))
  6254. return true;
  6255. // Parse optional fields
  6256. while (EatIfPresent(lltok::comma)) {
  6257. switch (Lex.getKind()) {
  6258. case lltok::kw_alignLog2:
  6259. Lex.Lex();
  6260. if (ParseToken(lltok::colon, "expected ':'") ||
  6261. ParseUInt64(TTRes.AlignLog2))
  6262. return true;
  6263. break;
  6264. case lltok::kw_sizeM1:
  6265. Lex.Lex();
  6266. if (ParseToken(lltok::colon, "expected ':'") || ParseUInt64(TTRes.SizeM1))
  6267. return true;
  6268. break;
  6269. case lltok::kw_bitMask: {
  6270. unsigned Val;
  6271. Lex.Lex();
  6272. if (ParseToken(lltok::colon, "expected ':'") || ParseUInt32(Val))
  6273. return true;
  6274. assert(Val <= 0xff);
  6275. TTRes.BitMask = (uint8_t)Val;
  6276. break;
  6277. }
  6278. case lltok::kw_inlineBits:
  6279. Lex.Lex();
  6280. if (ParseToken(lltok::colon, "expected ':'") ||
  6281. ParseUInt64(TTRes.InlineBits))
  6282. return true;
  6283. break;
  6284. default:
  6285. return Error(Lex.getLoc(), "expected optional TypeTestResolution field");
  6286. }
  6287. }
  6288. if (ParseToken(lltok::rparen, "expected ')' here"))
  6289. return true;
  6290. return false;
  6291. }
  6292. /// OptionalWpdResolutions
  6293. /// ::= 'wpsResolutions' ':' '(' WpdResolution [',' WpdResolution]* ')'
  6294. /// WpdResolution ::= '(' 'offset' ':' UInt64 ',' WpdRes ')'
  6295. bool LLParser::ParseOptionalWpdResolutions(
  6296. std::map<uint64_t, WholeProgramDevirtResolution> &WPDResMap) {
  6297. if (ParseToken(lltok::kw_wpdResolutions, "expected 'wpdResolutions' here") ||
  6298. ParseToken(lltok::colon, "expected ':' here") ||
  6299. ParseToken(lltok::lparen, "expected '(' here"))
  6300. return true;
  6301. do {
  6302. uint64_t Offset;
  6303. WholeProgramDevirtResolution WPDRes;
  6304. if (ParseToken(lltok::lparen, "expected '(' here") ||
  6305. ParseToken(lltok::kw_offset, "expected 'offset' here") ||
  6306. ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(Offset) ||
  6307. ParseToken(lltok::comma, "expected ',' here") || ParseWpdRes(WPDRes) ||
  6308. ParseToken(lltok::rparen, "expected ')' here"))
  6309. return true;
  6310. WPDResMap[Offset] = WPDRes;
  6311. } while (EatIfPresent(lltok::comma));
  6312. if (ParseToken(lltok::rparen, "expected ')' here"))
  6313. return true;
  6314. return false;
  6315. }
  6316. /// WpdRes
  6317. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'indir'
  6318. /// [',' OptionalResByArg]? ')'
  6319. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'singleImpl'
  6320. /// ',' 'singleImplName' ':' STRINGCONSTANT ','
  6321. /// [',' OptionalResByArg]? ')'
  6322. /// ::= 'wpdRes' ':' '(' 'kind' ':' 'branchFunnel'
  6323. /// [',' OptionalResByArg]? ')'
  6324. bool LLParser::ParseWpdRes(WholeProgramDevirtResolution &WPDRes) {
  6325. if (ParseToken(lltok::kw_wpdRes, "expected 'wpdRes' here") ||
  6326. ParseToken(lltok::colon, "expected ':' here") ||
  6327. ParseToken(lltok::lparen, "expected '(' here") ||
  6328. ParseToken(lltok::kw_kind, "expected 'kind' here") ||
  6329. ParseToken(lltok::colon, "expected ':' here"))
  6330. return true;
  6331. switch (Lex.getKind()) {
  6332. case lltok::kw_indir:
  6333. WPDRes.TheKind = WholeProgramDevirtResolution::Indir;
  6334. break;
  6335. case lltok::kw_singleImpl:
  6336. WPDRes.TheKind = WholeProgramDevirtResolution::SingleImpl;
  6337. break;
  6338. case lltok::kw_branchFunnel:
  6339. WPDRes.TheKind = WholeProgramDevirtResolution::BranchFunnel;
  6340. break;
  6341. default:
  6342. return Error(Lex.getLoc(), "unexpected WholeProgramDevirtResolution kind");
  6343. }
  6344. Lex.Lex();
  6345. // Parse optional fields
  6346. while (EatIfPresent(lltok::comma)) {
  6347. switch (Lex.getKind()) {
  6348. case lltok::kw_singleImplName:
  6349. Lex.Lex();
  6350. if (ParseToken(lltok::colon, "expected ':' here") ||
  6351. ParseStringConstant(WPDRes.SingleImplName))
  6352. return true;
  6353. break;
  6354. case lltok::kw_resByArg:
  6355. if (ParseOptionalResByArg(WPDRes.ResByArg))
  6356. return true;
  6357. break;
  6358. default:
  6359. return Error(Lex.getLoc(),
  6360. "expected optional WholeProgramDevirtResolution field");
  6361. }
  6362. }
  6363. if (ParseToken(lltok::rparen, "expected ')' here"))
  6364. return true;
  6365. return false;
  6366. }
  6367. /// OptionalResByArg
  6368. /// ::= 'wpdRes' ':' '(' ResByArg[, ResByArg]* ')'
  6369. /// ResByArg ::= Args ',' 'byArg' ':' '(' 'kind' ':'
  6370. /// ( 'indir' | 'uniformRetVal' | 'UniqueRetVal' |
  6371. /// 'virtualConstProp' )
  6372. /// [',' 'info' ':' UInt64]? [',' 'byte' ':' UInt32]?
  6373. /// [',' 'bit' ':' UInt32]? ')'
  6374. bool LLParser::ParseOptionalResByArg(
  6375. std::map<std::vector<uint64_t>, WholeProgramDevirtResolution::ByArg>
  6376. &ResByArg) {
  6377. if (ParseToken(lltok::kw_resByArg, "expected 'resByArg' here") ||
  6378. ParseToken(lltok::colon, "expected ':' here") ||
  6379. ParseToken(lltok::lparen, "expected '(' here"))
  6380. return true;
  6381. do {
  6382. std::vector<uint64_t> Args;
  6383. if (ParseArgs(Args) || ParseToken(lltok::comma, "expected ',' here") ||
  6384. ParseToken(lltok::kw_byArg, "expected 'byArg here") ||
  6385. ParseToken(lltok::colon, "expected ':' here") ||
  6386. ParseToken(lltok::lparen, "expected '(' here") ||
  6387. ParseToken(lltok::kw_kind, "expected 'kind' here") ||
  6388. ParseToken(lltok::colon, "expected ':' here"))
  6389. return true;
  6390. WholeProgramDevirtResolution::ByArg ByArg;
  6391. switch (Lex.getKind()) {
  6392. case lltok::kw_indir:
  6393. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::Indir;
  6394. break;
  6395. case lltok::kw_uniformRetVal:
  6396. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniformRetVal;
  6397. break;
  6398. case lltok::kw_uniqueRetVal:
  6399. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::UniqueRetVal;
  6400. break;
  6401. case lltok::kw_virtualConstProp:
  6402. ByArg.TheKind = WholeProgramDevirtResolution::ByArg::VirtualConstProp;
  6403. break;
  6404. default:
  6405. return Error(Lex.getLoc(),
  6406. "unexpected WholeProgramDevirtResolution::ByArg kind");
  6407. }
  6408. Lex.Lex();
  6409. // Parse optional fields
  6410. while (EatIfPresent(lltok::comma)) {
  6411. switch (Lex.getKind()) {
  6412. case lltok::kw_info:
  6413. Lex.Lex();
  6414. if (ParseToken(lltok::colon, "expected ':' here") ||
  6415. ParseUInt64(ByArg.Info))
  6416. return true;
  6417. break;
  6418. case lltok::kw_byte:
  6419. Lex.Lex();
  6420. if (ParseToken(lltok::colon, "expected ':' here") ||
  6421. ParseUInt32(ByArg.Byte))
  6422. return true;
  6423. break;
  6424. case lltok::kw_bit:
  6425. Lex.Lex();
  6426. if (ParseToken(lltok::colon, "expected ':' here") ||
  6427. ParseUInt32(ByArg.Bit))
  6428. return true;
  6429. break;
  6430. default:
  6431. return Error(Lex.getLoc(),
  6432. "expected optional whole program devirt field");
  6433. }
  6434. }
  6435. if (ParseToken(lltok::rparen, "expected ')' here"))
  6436. return true;
  6437. ResByArg[Args] = ByArg;
  6438. } while (EatIfPresent(lltok::comma));
  6439. if (ParseToken(lltok::rparen, "expected ')' here"))
  6440. return true;
  6441. return false;
  6442. }
  6443. /// OptionalResByArg
  6444. /// ::= 'args' ':' '(' UInt64[, UInt64]* ')'
  6445. bool LLParser::ParseArgs(std::vector<uint64_t> &Args) {
  6446. if (ParseToken(lltok::kw_args, "expected 'args' here") ||
  6447. ParseToken(lltok::colon, "expected ':' here") ||
  6448. ParseToken(lltok::lparen, "expected '(' here"))
  6449. return true;
  6450. do {
  6451. uint64_t Val;
  6452. if (ParseUInt64(Val))
  6453. return true;
  6454. Args.push_back(Val);
  6455. } while (EatIfPresent(lltok::comma));
  6456. if (ParseToken(lltok::rparen, "expected ')' here"))
  6457. return true;
  6458. return false;
  6459. }
  6460. static ValueInfo EmptyVI =
  6461. ValueInfo(false, (GlobalValueSummaryMapTy::value_type *)-8);
  6462. /// Stores the given Name/GUID and associated summary into the Index.
  6463. /// Also updates any forward references to the associated entry ID.
  6464. void LLParser::AddGlobalValueToIndex(
  6465. std::string Name, GlobalValue::GUID GUID, GlobalValue::LinkageTypes Linkage,
  6466. unsigned ID, std::unique_ptr<GlobalValueSummary> Summary) {
  6467. // First create the ValueInfo utilizing the Name or GUID.
  6468. ValueInfo VI;
  6469. if (GUID != 0) {
  6470. assert(Name.empty());
  6471. VI = Index->getOrInsertValueInfo(GUID);
  6472. } else {
  6473. assert(!Name.empty());
  6474. if (M) {
  6475. auto *GV = M->getNamedValue(Name);
  6476. assert(GV);
  6477. VI = Index->getOrInsertValueInfo(GV);
  6478. } else {
  6479. assert(
  6480. (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
  6481. "Need a source_filename to compute GUID for local");
  6482. GUID = GlobalValue::getGUID(
  6483. GlobalValue::getGlobalIdentifier(Name, Linkage, SourceFileName));
  6484. VI = Index->getOrInsertValueInfo(GUID, Index->saveString(Name));
  6485. }
  6486. }
  6487. // Add the summary if one was provided.
  6488. if (Summary)
  6489. Index->addGlobalValueSummary(VI, std::move(Summary));
  6490. // Resolve forward references from calls/refs
  6491. auto FwdRefVIs = ForwardRefValueInfos.find(ID);
  6492. if (FwdRefVIs != ForwardRefValueInfos.end()) {
  6493. for (auto VIRef : FwdRefVIs->second) {
  6494. assert(*VIRef.first == EmptyVI &&
  6495. "Forward referenced ValueInfo expected to be empty");
  6496. *VIRef.first = VI;
  6497. }
  6498. ForwardRefValueInfos.erase(FwdRefVIs);
  6499. }
  6500. // Resolve forward references from aliases
  6501. auto FwdRefAliasees = ForwardRefAliasees.find(ID);
  6502. if (FwdRefAliasees != ForwardRefAliasees.end()) {
  6503. for (auto AliaseeRef : FwdRefAliasees->second) {
  6504. assert(!AliaseeRef.first->hasAliasee() &&
  6505. "Forward referencing alias already has aliasee");
  6506. AliaseeRef.first->setAliasee(VI.getSummaryList().front().get());
  6507. }
  6508. ForwardRefAliasees.erase(FwdRefAliasees);
  6509. }
  6510. // Save the associated ValueInfo for use in later references by ID.
  6511. if (ID == NumberedValueInfos.size())
  6512. NumberedValueInfos.push_back(VI);
  6513. else {
  6514. // Handle non-continuous numbers (to make test simplification easier).
  6515. if (ID > NumberedValueInfos.size())
  6516. NumberedValueInfos.resize(ID + 1);
  6517. NumberedValueInfos[ID] = VI;
  6518. }
  6519. }
  6520. /// ParseGVEntry
  6521. /// ::= 'gv' ':' '(' ('name' ':' STRINGCONSTANT | 'guid' ':' UInt64)
  6522. /// [',' 'summaries' ':' Summary[',' Summary]* ]? ')'
  6523. /// Summary ::= '(' (FunctionSummary | VariableSummary | AliasSummary) ')'
  6524. bool LLParser::ParseGVEntry(unsigned ID) {
  6525. assert(Lex.getKind() == lltok::kw_gv);
  6526. Lex.Lex();
  6527. if (ParseToken(lltok::colon, "expected ':' here") ||
  6528. ParseToken(lltok::lparen, "expected '(' here"))
  6529. return true;
  6530. std::string Name;
  6531. GlobalValue::GUID GUID = 0;
  6532. switch (Lex.getKind()) {
  6533. case lltok::kw_name:
  6534. Lex.Lex();
  6535. if (ParseToken(lltok::colon, "expected ':' here") ||
  6536. ParseStringConstant(Name))
  6537. return true;
  6538. // Can't create GUID/ValueInfo until we have the linkage.
  6539. break;
  6540. case lltok::kw_guid:
  6541. Lex.Lex();
  6542. if (ParseToken(lltok::colon, "expected ':' here") || ParseUInt64(GUID))
  6543. return true;
  6544. break;
  6545. default:
  6546. return Error(Lex.getLoc(), "expected name or guid tag");
  6547. }
  6548. if (!EatIfPresent(lltok::comma)) {
  6549. // No summaries. Wrap up.
  6550. if (ParseToken(lltok::rparen, "expected ')' here"))
  6551. return true;
  6552. // This was created for a call to an external or indirect target.
  6553. // A GUID with no summary came from a VALUE_GUID record, dummy GUID
  6554. // created for indirect calls with VP. A Name with no GUID came from
  6555. // an external definition. We pass ExternalLinkage since that is only
  6556. // used when the GUID must be computed from Name, and in that case
  6557. // the symbol must have external linkage.
  6558. AddGlobalValueToIndex(Name, GUID, GlobalValue::ExternalLinkage, ID,
  6559. nullptr);
  6560. return false;
  6561. }
  6562. // Have a list of summaries
  6563. if (ParseToken(lltok::kw_summaries, "expected 'summaries' here") ||
  6564. ParseToken(lltok::colon, "expected ':' here"))
  6565. return true;
  6566. do {
  6567. if (ParseToken(lltok::lparen, "expected '(' here"))
  6568. return true;
  6569. switch (Lex.getKind()) {
  6570. case lltok::kw_function:
  6571. if (ParseFunctionSummary(Name, GUID, ID))
  6572. return true;
  6573. break;
  6574. case lltok::kw_variable:
  6575. if (ParseVariableSummary(Name, GUID, ID))
  6576. return true;
  6577. break;
  6578. case lltok::kw_alias:
  6579. if (ParseAliasSummary(Name, GUID, ID))
  6580. return true;
  6581. break;
  6582. default:
  6583. return Error(Lex.getLoc(), "expected summary type");
  6584. }
  6585. if (ParseToken(lltok::rparen, "expected ')' here"))
  6586. return true;
  6587. } while (EatIfPresent(lltok::comma));
  6588. if (ParseToken(lltok::rparen, "expected ')' here"))
  6589. return true;
  6590. return false;
  6591. }
  6592. /// FunctionSummary
  6593. /// ::= 'function' ':' '(' 'module' ':' ModuleReference ',' GVFlags
  6594. /// ',' 'insts' ':' UInt32 [',' OptionalFFlags]? [',' OptionalCalls]?
  6595. /// [',' OptionalTypeIdInfo]? [',' OptionalRefs]? ')'
  6596. bool LLParser::ParseFunctionSummary(std::string Name, GlobalValue::GUID GUID,
  6597. unsigned ID) {
  6598. assert(Lex.getKind() == lltok::kw_function);
  6599. Lex.Lex();
  6600. StringRef ModulePath;
  6601. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  6602. /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
  6603. /*Live=*/false, /*IsLocal=*/false);
  6604. unsigned InstCount;
  6605. std::vector<FunctionSummary::EdgeTy> Calls;
  6606. FunctionSummary::TypeIdInfo TypeIdInfo;
  6607. std::vector<ValueInfo> Refs;
  6608. // Default is all-zeros (conservative values).
  6609. FunctionSummary::FFlags FFlags = {};
  6610. if (ParseToken(lltok::colon, "expected ':' here") ||
  6611. ParseToken(lltok::lparen, "expected '(' here") ||
  6612. ParseModuleReference(ModulePath) ||
  6613. ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
  6614. ParseToken(lltok::comma, "expected ',' here") ||
  6615. ParseToken(lltok::kw_insts, "expected 'insts' here") ||
  6616. ParseToken(lltok::colon, "expected ':' here") || ParseUInt32(InstCount))
  6617. return true;
  6618. // Parse optional fields
  6619. while (EatIfPresent(lltok::comma)) {
  6620. switch (Lex.getKind()) {
  6621. case lltok::kw_funcFlags:
  6622. if (ParseOptionalFFlags(FFlags))
  6623. return true;
  6624. break;
  6625. case lltok::kw_calls:
  6626. if (ParseOptionalCalls(Calls))
  6627. return true;
  6628. break;
  6629. case lltok::kw_typeIdInfo:
  6630. if (ParseOptionalTypeIdInfo(TypeIdInfo))
  6631. return true;
  6632. break;
  6633. case lltok::kw_refs:
  6634. if (ParseOptionalRefs(Refs))
  6635. return true;
  6636. break;
  6637. default:
  6638. return Error(Lex.getLoc(), "expected optional function summary field");
  6639. }
  6640. }
  6641. if (ParseToken(lltok::rparen, "expected ')' here"))
  6642. return true;
  6643. auto FS = llvm::make_unique<FunctionSummary>(
  6644. GVFlags, InstCount, FFlags, std::move(Refs), std::move(Calls),
  6645. std::move(TypeIdInfo.TypeTests),
  6646. std::move(TypeIdInfo.TypeTestAssumeVCalls),
  6647. std::move(TypeIdInfo.TypeCheckedLoadVCalls),
  6648. std::move(TypeIdInfo.TypeTestAssumeConstVCalls),
  6649. std::move(TypeIdInfo.TypeCheckedLoadConstVCalls));
  6650. FS->setModulePath(ModulePath);
  6651. AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  6652. ID, std::move(FS));
  6653. return false;
  6654. }
  6655. /// VariableSummary
  6656. /// ::= 'variable' ':' '(' 'module' ':' ModuleReference ',' GVFlags
  6657. /// [',' OptionalRefs]? ')'
  6658. bool LLParser::ParseVariableSummary(std::string Name, GlobalValue::GUID GUID,
  6659. unsigned ID) {
  6660. assert(Lex.getKind() == lltok::kw_variable);
  6661. Lex.Lex();
  6662. StringRef ModulePath;
  6663. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  6664. /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
  6665. /*Live=*/false, /*IsLocal=*/false);
  6666. std::vector<ValueInfo> Refs;
  6667. if (ParseToken(lltok::colon, "expected ':' here") ||
  6668. ParseToken(lltok::lparen, "expected '(' here") ||
  6669. ParseModuleReference(ModulePath) ||
  6670. ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags))
  6671. return true;
  6672. // Parse optional refs field
  6673. if (EatIfPresent(lltok::comma)) {
  6674. if (ParseOptionalRefs(Refs))
  6675. return true;
  6676. }
  6677. if (ParseToken(lltok::rparen, "expected ')' here"))
  6678. return true;
  6679. auto GS = llvm::make_unique<GlobalVarSummary>(
  6680. GVFlags, GlobalVarSummary::GVarFlags(), std::move(Refs));
  6681. GS->setModulePath(ModulePath);
  6682. AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  6683. ID, std::move(GS));
  6684. return false;
  6685. }
  6686. /// AliasSummary
  6687. /// ::= 'alias' ':' '(' 'module' ':' ModuleReference ',' GVFlags ','
  6688. /// 'aliasee' ':' GVReference ')'
  6689. bool LLParser::ParseAliasSummary(std::string Name, GlobalValue::GUID GUID,
  6690. unsigned ID) {
  6691. assert(Lex.getKind() == lltok::kw_alias);
  6692. LocTy Loc = Lex.getLoc();
  6693. Lex.Lex();
  6694. StringRef ModulePath;
  6695. GlobalValueSummary::GVFlags GVFlags = GlobalValueSummary::GVFlags(
  6696. /*Linkage=*/GlobalValue::ExternalLinkage, /*NotEligibleToImport=*/false,
  6697. /*Live=*/false, /*IsLocal=*/false);
  6698. if (ParseToken(lltok::colon, "expected ':' here") ||
  6699. ParseToken(lltok::lparen, "expected '(' here") ||
  6700. ParseModuleReference(ModulePath) ||
  6701. ParseToken(lltok::comma, "expected ',' here") || ParseGVFlags(GVFlags) ||
  6702. ParseToken(lltok::comma, "expected ',' here") ||
  6703. ParseToken(lltok::kw_aliasee, "expected 'aliasee' here") ||
  6704. ParseToken(lltok::colon, "expected ':' here"))
  6705. return true;
  6706. ValueInfo AliaseeVI;
  6707. unsigned GVId;
  6708. if (ParseGVReference(AliaseeVI, GVId))
  6709. return true;
  6710. if (ParseToken(lltok::rparen, "expected ')' here"))
  6711. return true;
  6712. auto AS = llvm::make_unique<AliasSummary>(GVFlags);
  6713. AS->setModulePath(ModulePath);
  6714. // Record forward reference if the aliasee is not parsed yet.
  6715. if (AliaseeVI == EmptyVI) {
  6716. auto FwdRef = ForwardRefAliasees.insert(
  6717. std::make_pair(GVId, std::vector<std::pair<AliasSummary *, LocTy>>()));
  6718. FwdRef.first->second.push_back(std::make_pair(AS.get(), Loc));
  6719. } else
  6720. AS->setAliasee(AliaseeVI.getSummaryList().front().get());
  6721. AddGlobalValueToIndex(Name, GUID, (GlobalValue::LinkageTypes)GVFlags.Linkage,
  6722. ID, std::move(AS));
  6723. return false;
  6724. }
  6725. /// Flag
  6726. /// ::= [0|1]
  6727. bool LLParser::ParseFlag(unsigned &Val) {
  6728. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  6729. return TokError("expected integer");
  6730. Val = (unsigned)Lex.getAPSIntVal().getBoolValue();
  6731. Lex.Lex();
  6732. return false;
  6733. }
  6734. /// OptionalFFlags
  6735. /// := 'funcFlags' ':' '(' ['readNone' ':' Flag]?
  6736. /// [',' 'readOnly' ':' Flag]? [',' 'noRecurse' ':' Flag]?
  6737. /// [',' 'returnDoesNotAlias' ':' Flag]? ')'
  6738. /// [',' 'noInline' ':' Flag]? ')'
  6739. bool LLParser::ParseOptionalFFlags(FunctionSummary::FFlags &FFlags) {
  6740. assert(Lex.getKind() == lltok::kw_funcFlags);
  6741. Lex.Lex();
  6742. if (ParseToken(lltok::colon, "expected ':' in funcFlags") |
  6743. ParseToken(lltok::lparen, "expected '(' in funcFlags"))
  6744. return true;
  6745. do {
  6746. unsigned Val;
  6747. switch (Lex.getKind()) {
  6748. case lltok::kw_readNone:
  6749. Lex.Lex();
  6750. if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
  6751. return true;
  6752. FFlags.ReadNone = Val;
  6753. break;
  6754. case lltok::kw_readOnly:
  6755. Lex.Lex();
  6756. if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
  6757. return true;
  6758. FFlags.ReadOnly = Val;
  6759. break;
  6760. case lltok::kw_noRecurse:
  6761. Lex.Lex();
  6762. if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
  6763. return true;
  6764. FFlags.NoRecurse = Val;
  6765. break;
  6766. case lltok::kw_returnDoesNotAlias:
  6767. Lex.Lex();
  6768. if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
  6769. return true;
  6770. FFlags.ReturnDoesNotAlias = Val;
  6771. break;
  6772. case lltok::kw_noInline:
  6773. Lex.Lex();
  6774. if (ParseToken(lltok::colon, "expected ':'") || ParseFlag(Val))
  6775. return true;
  6776. FFlags.NoInline = Val;
  6777. break;
  6778. default:
  6779. return Error(Lex.getLoc(), "expected function flag type");
  6780. }
  6781. } while (EatIfPresent(lltok::comma));
  6782. if (ParseToken(lltok::rparen, "expected ')' in funcFlags"))
  6783. return true;
  6784. return false;
  6785. }
  6786. /// OptionalCalls
  6787. /// := 'calls' ':' '(' Call [',' Call]* ')'
  6788. /// Call ::= '(' 'callee' ':' GVReference
  6789. /// [( ',' 'hotness' ':' Hotness | ',' 'relbf' ':' UInt32 )]? ')'
  6790. bool LLParser::ParseOptionalCalls(std::vector<FunctionSummary::EdgeTy> &Calls) {
  6791. assert(Lex.getKind() == lltok::kw_calls);
  6792. Lex.Lex();
  6793. if (ParseToken(lltok::colon, "expected ':' in calls") |
  6794. ParseToken(lltok::lparen, "expected '(' in calls"))
  6795. return true;
  6796. IdToIndexMapType IdToIndexMap;
  6797. // Parse each call edge
  6798. do {
  6799. ValueInfo VI;
  6800. if (ParseToken(lltok::lparen, "expected '(' in call") ||
  6801. ParseToken(lltok::kw_callee, "expected 'callee' in call") ||
  6802. ParseToken(lltok::colon, "expected ':'"))
  6803. return true;
  6804. LocTy Loc = Lex.getLoc();
  6805. unsigned GVId;
  6806. if (ParseGVReference(VI, GVId))
  6807. return true;
  6808. CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
  6809. unsigned RelBF = 0;
  6810. if (EatIfPresent(lltok::comma)) {
  6811. // Expect either hotness or relbf
  6812. if (EatIfPresent(lltok::kw_hotness)) {
  6813. if (ParseToken(lltok::colon, "expected ':'") || ParseHotness(Hotness))
  6814. return true;
  6815. } else {
  6816. if (ParseToken(lltok::kw_relbf, "expected relbf") ||
  6817. ParseToken(lltok::colon, "expected ':'") || ParseUInt32(RelBF))
  6818. return true;
  6819. }
  6820. }
  6821. // Keep track of the Call array index needing a forward reference.
  6822. // We will save the location of the ValueInfo needing an update, but
  6823. // can only do so once the std::vector is finalized.
  6824. if (VI == EmptyVI)
  6825. IdToIndexMap[GVId].push_back(std::make_pair(Calls.size(), Loc));
  6826. Calls.push_back(FunctionSummary::EdgeTy{VI, CalleeInfo(Hotness, RelBF)});
  6827. if (ParseToken(lltok::rparen, "expected ')' in call"))
  6828. return true;
  6829. } while (EatIfPresent(lltok::comma));
  6830. // Now that the Calls vector is finalized, it is safe to save the locations
  6831. // of any forward GV references that need updating later.
  6832. for (auto I : IdToIndexMap) {
  6833. for (auto P : I.second) {
  6834. assert(Calls[P.first].first == EmptyVI &&
  6835. "Forward referenced ValueInfo expected to be empty");
  6836. auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
  6837. I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
  6838. FwdRef.first->second.push_back(
  6839. std::make_pair(&Calls[P.first].first, P.second));
  6840. }
  6841. }
  6842. if (ParseToken(lltok::rparen, "expected ')' in calls"))
  6843. return true;
  6844. return false;
  6845. }
  6846. /// Hotness
  6847. /// := ('unknown'|'cold'|'none'|'hot'|'critical')
  6848. bool LLParser::ParseHotness(CalleeInfo::HotnessType &Hotness) {
  6849. switch (Lex.getKind()) {
  6850. case lltok::kw_unknown:
  6851. Hotness = CalleeInfo::HotnessType::Unknown;
  6852. break;
  6853. case lltok::kw_cold:
  6854. Hotness = CalleeInfo::HotnessType::Cold;
  6855. break;
  6856. case lltok::kw_none:
  6857. Hotness = CalleeInfo::HotnessType::None;
  6858. break;
  6859. case lltok::kw_hot:
  6860. Hotness = CalleeInfo::HotnessType::Hot;
  6861. break;
  6862. case lltok::kw_critical:
  6863. Hotness = CalleeInfo::HotnessType::Critical;
  6864. break;
  6865. default:
  6866. return Error(Lex.getLoc(), "invalid call edge hotness");
  6867. }
  6868. Lex.Lex();
  6869. return false;
  6870. }
  6871. /// OptionalRefs
  6872. /// := 'refs' ':' '(' GVReference [',' GVReference]* ')'
  6873. bool LLParser::ParseOptionalRefs(std::vector<ValueInfo> &Refs) {
  6874. assert(Lex.getKind() == lltok::kw_refs);
  6875. Lex.Lex();
  6876. if (ParseToken(lltok::colon, "expected ':' in refs") |
  6877. ParseToken(lltok::lparen, "expected '(' in refs"))
  6878. return true;
  6879. IdToIndexMapType IdToIndexMap;
  6880. // Parse each ref edge
  6881. do {
  6882. ValueInfo VI;
  6883. LocTy Loc = Lex.getLoc();
  6884. unsigned GVId;
  6885. if (ParseGVReference(VI, GVId))
  6886. return true;
  6887. // Keep track of the Refs array index needing a forward reference.
  6888. // We will save the location of the ValueInfo needing an update, but
  6889. // can only do so once the std::vector is finalized.
  6890. if (VI == EmptyVI)
  6891. IdToIndexMap[GVId].push_back(std::make_pair(Refs.size(), Loc));
  6892. Refs.push_back(VI);
  6893. } while (EatIfPresent(lltok::comma));
  6894. // Now that the Refs vector is finalized, it is safe to save the locations
  6895. // of any forward GV references that need updating later.
  6896. for (auto I : IdToIndexMap) {
  6897. for (auto P : I.second) {
  6898. assert(Refs[P.first] == EmptyVI &&
  6899. "Forward referenced ValueInfo expected to be empty");
  6900. auto FwdRef = ForwardRefValueInfos.insert(std::make_pair(
  6901. I.first, std::vector<std::pair<ValueInfo *, LocTy>>()));
  6902. FwdRef.first->second.push_back(std::make_pair(&Refs[P.first], P.second));
  6903. }
  6904. }
  6905. if (ParseToken(lltok::rparen, "expected ')' in refs"))
  6906. return true;
  6907. return false;
  6908. }
  6909. /// OptionalTypeIdInfo
  6910. /// := 'typeidinfo' ':' '(' [',' TypeTests]? [',' TypeTestAssumeVCalls]?
  6911. /// [',' TypeCheckedLoadVCalls]? [',' TypeTestAssumeConstVCalls]?
  6912. /// [',' TypeCheckedLoadConstVCalls]? ')'
  6913. bool LLParser::ParseOptionalTypeIdInfo(
  6914. FunctionSummary::TypeIdInfo &TypeIdInfo) {
  6915. assert(Lex.getKind() == lltok::kw_typeIdInfo);
  6916. Lex.Lex();
  6917. if (ParseToken(lltok::colon, "expected ':' here") ||
  6918. ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
  6919. return true;
  6920. do {
  6921. switch (Lex.getKind()) {
  6922. case lltok::kw_typeTests:
  6923. if (ParseTypeTests(TypeIdInfo.TypeTests))
  6924. return true;
  6925. break;
  6926. case lltok::kw_typeTestAssumeVCalls:
  6927. if (ParseVFuncIdList(lltok::kw_typeTestAssumeVCalls,
  6928. TypeIdInfo.TypeTestAssumeVCalls))
  6929. return true;
  6930. break;
  6931. case lltok::kw_typeCheckedLoadVCalls:
  6932. if (ParseVFuncIdList(lltok::kw_typeCheckedLoadVCalls,
  6933. TypeIdInfo.TypeCheckedLoadVCalls))
  6934. return true;
  6935. break;
  6936. case lltok::kw_typeTestAssumeConstVCalls:
  6937. if (ParseConstVCallList(lltok::kw_typeTestAssumeConstVCalls,
  6938. TypeIdInfo.TypeTestAssumeConstVCalls))
  6939. return true;
  6940. break;
  6941. case lltok::kw_typeCheckedLoadConstVCalls:
  6942. if (ParseConstVCallList(lltok::kw_typeCheckedLoadConstVCalls,
  6943. TypeIdInfo.TypeCheckedLoadConstVCalls))
  6944. return true;
  6945. break;
  6946. default:
  6947. return Error(Lex.getLoc(), "invalid typeIdInfo list type");
  6948. }
  6949. } while (EatIfPresent(lltok::comma));
  6950. if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
  6951. return true;
  6952. return false;
  6953. }
  6954. /// TypeTests
  6955. /// ::= 'typeTests' ':' '(' (SummaryID | UInt64)
  6956. /// [',' (SummaryID | UInt64)]* ')'
  6957. bool LLParser::ParseTypeTests(std::vector<GlobalValue::GUID> &TypeTests) {
  6958. assert(Lex.getKind() == lltok::kw_typeTests);
  6959. Lex.Lex();
  6960. if (ParseToken(lltok::colon, "expected ':' here") ||
  6961. ParseToken(lltok::lparen, "expected '(' in typeIdInfo"))
  6962. return true;
  6963. IdToIndexMapType IdToIndexMap;
  6964. do {
  6965. GlobalValue::GUID GUID = 0;
  6966. if (Lex.getKind() == lltok::SummaryID) {
  6967. unsigned ID = Lex.getUIntVal();
  6968. LocTy Loc = Lex.getLoc();
  6969. // Keep track of the TypeTests array index needing a forward reference.
  6970. // We will save the location of the GUID needing an update, but
  6971. // can only do so once the std::vector is finalized.
  6972. IdToIndexMap[ID].push_back(std::make_pair(TypeTests.size(), Loc));
  6973. Lex.Lex();
  6974. } else if (ParseUInt64(GUID))
  6975. return true;
  6976. TypeTests.push_back(GUID);
  6977. } while (EatIfPresent(lltok::comma));
  6978. // Now that the TypeTests vector is finalized, it is safe to save the
  6979. // locations of any forward GV references that need updating later.
  6980. for (auto I : IdToIndexMap) {
  6981. for (auto P : I.second) {
  6982. assert(TypeTests[P.first] == 0 &&
  6983. "Forward referenced type id GUID expected to be 0");
  6984. auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
  6985. I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
  6986. FwdRef.first->second.push_back(
  6987. std::make_pair(&TypeTests[P.first], P.second));
  6988. }
  6989. }
  6990. if (ParseToken(lltok::rparen, "expected ')' in typeIdInfo"))
  6991. return true;
  6992. return false;
  6993. }
  6994. /// VFuncIdList
  6995. /// ::= Kind ':' '(' VFuncId [',' VFuncId]* ')'
  6996. bool LLParser::ParseVFuncIdList(
  6997. lltok::Kind Kind, std::vector<FunctionSummary::VFuncId> &VFuncIdList) {
  6998. assert(Lex.getKind() == Kind);
  6999. Lex.Lex();
  7000. if (ParseToken(lltok::colon, "expected ':' here") ||
  7001. ParseToken(lltok::lparen, "expected '(' here"))
  7002. return true;
  7003. IdToIndexMapType IdToIndexMap;
  7004. do {
  7005. FunctionSummary::VFuncId VFuncId;
  7006. if (ParseVFuncId(VFuncId, IdToIndexMap, VFuncIdList.size()))
  7007. return true;
  7008. VFuncIdList.push_back(VFuncId);
  7009. } while (EatIfPresent(lltok::comma));
  7010. if (ParseToken(lltok::rparen, "expected ')' here"))
  7011. return true;
  7012. // Now that the VFuncIdList vector is finalized, it is safe to save the
  7013. // locations of any forward GV references that need updating later.
  7014. for (auto I : IdToIndexMap) {
  7015. for (auto P : I.second) {
  7016. assert(VFuncIdList[P.first].GUID == 0 &&
  7017. "Forward referenced type id GUID expected to be 0");
  7018. auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
  7019. I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
  7020. FwdRef.first->second.push_back(
  7021. std::make_pair(&VFuncIdList[P.first].GUID, P.second));
  7022. }
  7023. }
  7024. return false;
  7025. }
  7026. /// ConstVCallList
  7027. /// ::= Kind ':' '(' ConstVCall [',' ConstVCall]* ')'
  7028. bool LLParser::ParseConstVCallList(
  7029. lltok::Kind Kind,
  7030. std::vector<FunctionSummary::ConstVCall> &ConstVCallList) {
  7031. assert(Lex.getKind() == Kind);
  7032. Lex.Lex();
  7033. if (ParseToken(lltok::colon, "expected ':' here") ||
  7034. ParseToken(lltok::lparen, "expected '(' here"))
  7035. return true;
  7036. IdToIndexMapType IdToIndexMap;
  7037. do {
  7038. FunctionSummary::ConstVCall ConstVCall;
  7039. if (ParseConstVCall(ConstVCall, IdToIndexMap, ConstVCallList.size()))
  7040. return true;
  7041. ConstVCallList.push_back(ConstVCall);
  7042. } while (EatIfPresent(lltok::comma));
  7043. if (ParseToken(lltok::rparen, "expected ')' here"))
  7044. return true;
  7045. // Now that the ConstVCallList vector is finalized, it is safe to save the
  7046. // locations of any forward GV references that need updating later.
  7047. for (auto I : IdToIndexMap) {
  7048. for (auto P : I.second) {
  7049. assert(ConstVCallList[P.first].VFunc.GUID == 0 &&
  7050. "Forward referenced type id GUID expected to be 0");
  7051. auto FwdRef = ForwardRefTypeIds.insert(std::make_pair(
  7052. I.first, std::vector<std::pair<GlobalValue::GUID *, LocTy>>()));
  7053. FwdRef.first->second.push_back(
  7054. std::make_pair(&ConstVCallList[P.first].VFunc.GUID, P.second));
  7055. }
  7056. }
  7057. return false;
  7058. }
  7059. /// ConstVCall
  7060. /// ::= '(' VFuncId ',' Args ')'
  7061. bool LLParser::ParseConstVCall(FunctionSummary::ConstVCall &ConstVCall,
  7062. IdToIndexMapType &IdToIndexMap, unsigned Index) {
  7063. if (ParseToken(lltok::lparen, "expected '(' here") ||
  7064. ParseVFuncId(ConstVCall.VFunc, IdToIndexMap, Index))
  7065. return true;
  7066. if (EatIfPresent(lltok::comma))
  7067. if (ParseArgs(ConstVCall.Args))
  7068. return true;
  7069. if (ParseToken(lltok::rparen, "expected ')' here"))
  7070. return true;
  7071. return false;
  7072. }
  7073. /// VFuncId
  7074. /// ::= 'vFuncId' ':' '(' (SummaryID | 'guid' ':' UInt64) ','
  7075. /// 'offset' ':' UInt64 ')'
  7076. bool LLParser::ParseVFuncId(FunctionSummary::VFuncId &VFuncId,
  7077. IdToIndexMapType &IdToIndexMap, unsigned Index) {
  7078. assert(Lex.getKind() == lltok::kw_vFuncId);
  7079. Lex.Lex();
  7080. if (ParseToken(lltok::colon, "expected ':' here") ||
  7081. ParseToken(lltok::lparen, "expected '(' here"))
  7082. return true;
  7083. if (Lex.getKind() == lltok::SummaryID) {
  7084. VFuncId.GUID = 0;
  7085. unsigned ID = Lex.getUIntVal();
  7086. LocTy Loc = Lex.getLoc();
  7087. // Keep track of the array index needing a forward reference.
  7088. // We will save the location of the GUID needing an update, but
  7089. // can only do so once the caller's std::vector is finalized.
  7090. IdToIndexMap[ID].push_back(std::make_pair(Index, Loc));
  7091. Lex.Lex();
  7092. } else if (ParseToken(lltok::kw_guid, "expected 'guid' here") ||
  7093. ParseToken(lltok::colon, "expected ':' here") ||
  7094. ParseUInt64(VFuncId.GUID))
  7095. return true;
  7096. if (ParseToken(lltok::comma, "expected ',' here") ||
  7097. ParseToken(lltok::kw_offset, "expected 'offset' here") ||
  7098. ParseToken(lltok::colon, "expected ':' here") ||
  7099. ParseUInt64(VFuncId.Offset) ||
  7100. ParseToken(lltok::rparen, "expected ')' here"))
  7101. return true;
  7102. return false;
  7103. }
  7104. /// GVFlags
  7105. /// ::= 'flags' ':' '(' 'linkage' ':' OptionalLinkageAux ','
  7106. /// 'notEligibleToImport' ':' Flag ',' 'live' ':' Flag ','
  7107. /// 'dsoLocal' ':' Flag ')'
  7108. bool LLParser::ParseGVFlags(GlobalValueSummary::GVFlags &GVFlags) {
  7109. assert(Lex.getKind() == lltok::kw_flags);
  7110. Lex.Lex();
  7111. bool HasLinkage;
  7112. if (ParseToken(lltok::colon, "expected ':' here") ||
  7113. ParseToken(lltok::lparen, "expected '(' here") ||
  7114. ParseToken(lltok::kw_linkage, "expected 'linkage' here") ||
  7115. ParseToken(lltok::colon, "expected ':' here"))
  7116. return true;
  7117. GVFlags.Linkage = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
  7118. assert(HasLinkage && "Linkage not optional in summary entry");
  7119. Lex.Lex();
  7120. unsigned Flag;
  7121. if (ParseToken(lltok::comma, "expected ',' here") ||
  7122. ParseToken(lltok::kw_notEligibleToImport,
  7123. "expected 'notEligibleToImport' here") ||
  7124. ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
  7125. return true;
  7126. GVFlags.NotEligibleToImport = Flag;
  7127. if (ParseToken(lltok::comma, "expected ',' here") ||
  7128. ParseToken(lltok::kw_live, "expected 'live' here") ||
  7129. ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
  7130. return true;
  7131. GVFlags.Live = Flag;
  7132. if (ParseToken(lltok::comma, "expected ',' here") ||
  7133. ParseToken(lltok::kw_dsoLocal, "expected 'dsoLocal' here") ||
  7134. ParseToken(lltok::colon, "expected ':' here") || ParseFlag(Flag))
  7135. return true;
  7136. GVFlags.DSOLocal = Flag;
  7137. if (ParseToken(lltok::rparen, "expected ')' here"))
  7138. return true;
  7139. return false;
  7140. }
  7141. /// ModuleReference
  7142. /// ::= 'module' ':' UInt
  7143. bool LLParser::ParseModuleReference(StringRef &ModulePath) {
  7144. // Parse module id.
  7145. if (ParseToken(lltok::kw_module, "expected 'module' here") ||
  7146. ParseToken(lltok::colon, "expected ':' here") ||
  7147. ParseToken(lltok::SummaryID, "expected module ID"))
  7148. return true;
  7149. unsigned ModuleID = Lex.getUIntVal();
  7150. auto I = ModuleIdMap.find(ModuleID);
  7151. // We should have already parsed all module IDs
  7152. assert(I != ModuleIdMap.end());
  7153. ModulePath = I->second;
  7154. return false;
  7155. }
  7156. /// GVReference
  7157. /// ::= SummaryID
  7158. bool LLParser::ParseGVReference(ValueInfo &VI, unsigned &GVId) {
  7159. if (ParseToken(lltok::SummaryID, "expected GV ID"))
  7160. return true;
  7161. GVId = Lex.getUIntVal();
  7162. // Check if we already have a VI for this GV
  7163. if (GVId < NumberedValueInfos.size()) {
  7164. assert(NumberedValueInfos[GVId] != EmptyVI);
  7165. VI = NumberedValueInfos[GVId];
  7166. } else
  7167. // We will create a forward reference to the stored location.
  7168. VI = EmptyVI;
  7169. return false;
  7170. }