AsmParser.cpp 206 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447
  1. //===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This class implements a parser for assembly files similar to gas syntax.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/APFloat.h"
  13. #include "llvm/ADT/APInt.h"
  14. #include "llvm/ADT/ArrayRef.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallSet.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/StringExtras.h"
  20. #include "llvm/ADT/StringMap.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Twine.h"
  23. #include "llvm/BinaryFormat/Dwarf.h"
  24. #include "llvm/DebugInfo/CodeView/SymbolRecord.h"
  25. #include "llvm/MC/MCAsmInfo.h"
  26. #include "llvm/MC/MCCodeView.h"
  27. #include "llvm/MC/MCContext.h"
  28. #include "llvm/MC/MCDirectives.h"
  29. #include "llvm/MC/MCDwarf.h"
  30. #include "llvm/MC/MCExpr.h"
  31. #include "llvm/MC/MCInstPrinter.h"
  32. #include "llvm/MC/MCInstrDesc.h"
  33. #include "llvm/MC/MCInstrInfo.h"
  34. #include "llvm/MC/MCParser/AsmCond.h"
  35. #include "llvm/MC/MCParser/AsmLexer.h"
  36. #include "llvm/MC/MCParser/MCAsmLexer.h"
  37. #include "llvm/MC/MCParser/MCAsmParser.h"
  38. #include "llvm/MC/MCParser/MCAsmParserExtension.h"
  39. #include "llvm/MC/MCParser/MCAsmParserUtils.h"
  40. #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
  41. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  42. #include "llvm/MC/MCRegisterInfo.h"
  43. #include "llvm/MC/MCSection.h"
  44. #include "llvm/MC/MCStreamer.h"
  45. #include "llvm/MC/MCSymbol.h"
  46. #include "llvm/MC/MCTargetOptions.h"
  47. #include "llvm/MC/MCValue.h"
  48. #include "llvm/Support/Casting.h"
  49. #include "llvm/Support/CommandLine.h"
  50. #include "llvm/Support/ErrorHandling.h"
  51. #include "llvm/Support/MD5.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/MemoryBuffer.h"
  54. #include "llvm/Support/SMLoc.h"
  55. #include "llvm/Support/SourceMgr.h"
  56. #include "llvm/Support/raw_ostream.h"
  57. #include <algorithm>
  58. #include <cassert>
  59. #include <cctype>
  60. #include <climits>
  61. #include <cstddef>
  62. #include <cstdint>
  63. #include <deque>
  64. #include <memory>
  65. #include <optional>
  66. #include <sstream>
  67. #include <string>
  68. #include <tuple>
  69. #include <utility>
  70. #include <vector>
  71. using namespace llvm;
  72. MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
  73. namespace {
  74. /// Helper types for tracking macro definitions.
  75. typedef std::vector<AsmToken> MCAsmMacroArgument;
  76. typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
  77. /// Helper class for storing information about an active macro
  78. /// instantiation.
  79. struct MacroInstantiation {
  80. /// The location of the instantiation.
  81. SMLoc InstantiationLoc;
  82. /// The buffer where parsing should resume upon instantiation completion.
  83. unsigned ExitBuffer;
  84. /// The location where parsing should resume upon instantiation completion.
  85. SMLoc ExitLoc;
  86. /// The depth of TheCondStack at the start of the instantiation.
  87. size_t CondStackDepth;
  88. };
  89. struct ParseStatementInfo {
  90. /// The parsed operands from the last parsed statement.
  91. SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
  92. /// The opcode from the last parsed instruction.
  93. unsigned Opcode = ~0U;
  94. /// Was there an error parsing the inline assembly?
  95. bool ParseError = false;
  96. SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
  97. ParseStatementInfo() = delete;
  98. ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
  99. : AsmRewrites(rewrites) {}
  100. };
  101. /// The concrete assembly parser instance.
  102. class AsmParser : public MCAsmParser {
  103. private:
  104. AsmLexer Lexer;
  105. MCContext &Ctx;
  106. MCStreamer &Out;
  107. const MCAsmInfo &MAI;
  108. SourceMgr &SrcMgr;
  109. SourceMgr::DiagHandlerTy SavedDiagHandler;
  110. void *SavedDiagContext;
  111. std::unique_ptr<MCAsmParserExtension> PlatformParser;
  112. SMLoc StartTokLoc;
  113. /// This is the current buffer index we're lexing from as managed by the
  114. /// SourceMgr object.
  115. unsigned CurBuffer;
  116. AsmCond TheCondState;
  117. std::vector<AsmCond> TheCondStack;
  118. /// maps directive names to handler methods in parser
  119. /// extensions. Extensions register themselves in this map by calling
  120. /// addDirectiveHandler.
  121. StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
  122. /// Stack of active macro instantiations.
  123. std::vector<MacroInstantiation*> ActiveMacros;
  124. /// List of bodies of anonymous macros.
  125. std::deque<MCAsmMacro> MacroLikeBodies;
  126. /// Boolean tracking whether macro substitution is enabled.
  127. unsigned MacrosEnabledFlag : 1;
  128. /// Keeps track of how many .macro's have been instantiated.
  129. unsigned NumOfMacroInstantiations;
  130. /// The values from the last parsed cpp hash file line comment if any.
  131. struct CppHashInfoTy {
  132. StringRef Filename;
  133. int64_t LineNumber;
  134. SMLoc Loc;
  135. unsigned Buf;
  136. CppHashInfoTy() : LineNumber(0), Buf(0) {}
  137. };
  138. CppHashInfoTy CppHashInfo;
  139. /// The filename from the first cpp hash file line comment, if any.
  140. StringRef FirstCppHashFilename;
  141. /// List of forward directional labels for diagnosis at the end.
  142. SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
  143. SmallSet<StringRef, 2> LTODiscardSymbols;
  144. /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
  145. unsigned AssemblerDialect = ~0U;
  146. /// is Darwin compatibility enabled?
  147. bool IsDarwin = false;
  148. /// Are we parsing ms-style inline assembly?
  149. bool ParsingMSInlineAsm = false;
  150. /// Did we already inform the user about inconsistent MD5 usage?
  151. bool ReportedInconsistentMD5 = false;
  152. // Is alt macro mode enabled.
  153. bool AltMacroMode = false;
  154. protected:
  155. virtual bool parseStatement(ParseStatementInfo &Info,
  156. MCAsmParserSemaCallback *SI);
  157. /// This routine uses the target specific ParseInstruction function to
  158. /// parse an instruction into Operands, and then call the target specific
  159. /// MatchAndEmit function to match and emit the instruction.
  160. bool parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
  161. StringRef IDVal, AsmToken ID,
  162. SMLoc IDLoc);
  163. /// Should we emit DWARF describing this assembler source? (Returns false if
  164. /// the source has .file directives, which means we don't want to generate
  165. /// info describing the assembler source itself.)
  166. bool enabledGenDwarfForAssembly();
  167. public:
  168. AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
  169. const MCAsmInfo &MAI, unsigned CB);
  170. AsmParser(const AsmParser &) = delete;
  171. AsmParser &operator=(const AsmParser &) = delete;
  172. ~AsmParser() override;
  173. bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
  174. void addDirectiveHandler(StringRef Directive,
  175. ExtensionDirectiveHandler Handler) override {
  176. ExtensionDirectiveMap[Directive] = Handler;
  177. }
  178. void addAliasForDirective(StringRef Directive, StringRef Alias) override {
  179. DirectiveKindMap[Directive.lower()] = DirectiveKindMap[Alias.lower()];
  180. }
  181. /// @name MCAsmParser Interface
  182. /// {
  183. SourceMgr &getSourceManager() override { return SrcMgr; }
  184. MCAsmLexer &getLexer() override { return Lexer; }
  185. MCContext &getContext() override { return Ctx; }
  186. MCStreamer &getStreamer() override { return Out; }
  187. CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
  188. unsigned getAssemblerDialect() override {
  189. if (AssemblerDialect == ~0U)
  190. return MAI.getAssemblerDialect();
  191. else
  192. return AssemblerDialect;
  193. }
  194. void setAssemblerDialect(unsigned i) override {
  195. AssemblerDialect = i;
  196. }
  197. void Note(SMLoc L, const Twine &Msg, SMRange Range = std::nullopt) override;
  198. bool Warning(SMLoc L, const Twine &Msg,
  199. SMRange Range = std::nullopt) override;
  200. bool printError(SMLoc L, const Twine &Msg,
  201. SMRange Range = std::nullopt) override;
  202. const AsmToken &Lex() override;
  203. void setParsingMSInlineAsm(bool V) override {
  204. ParsingMSInlineAsm = V;
  205. // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
  206. // hex integer literals.
  207. Lexer.setLexMasmIntegers(V);
  208. }
  209. bool isParsingMSInlineAsm() override { return ParsingMSInlineAsm; }
  210. bool discardLTOSymbol(StringRef Name) const override {
  211. return LTODiscardSymbols.contains(Name);
  212. }
  213. bool parseMSInlineAsm(std::string &AsmString, unsigned &NumOutputs,
  214. unsigned &NumInputs,
  215. SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
  216. SmallVectorImpl<std::string> &Constraints,
  217. SmallVectorImpl<std::string> &Clobbers,
  218. const MCInstrInfo *MII, const MCInstPrinter *IP,
  219. MCAsmParserSemaCallback &SI) override;
  220. bool parseExpression(const MCExpr *&Res);
  221. bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
  222. bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
  223. AsmTypeInfo *TypeInfo) override;
  224. bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
  225. bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
  226. SMLoc &EndLoc) override;
  227. bool parseAbsoluteExpression(int64_t &Res) override;
  228. /// Parse a floating point expression using the float \p Semantics
  229. /// and set \p Res to the value.
  230. bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
  231. /// Parse an identifier or string (as a quoted identifier)
  232. /// and set \p Res to the identifier contents.
  233. bool parseIdentifier(StringRef &Res) override;
  234. void eatToEndOfStatement() override;
  235. bool checkForValidSection() override;
  236. /// }
  237. private:
  238. bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
  239. bool parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo = true);
  240. void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
  241. ArrayRef<MCAsmMacroParameter> Parameters);
  242. bool expandMacro(raw_svector_ostream &OS, StringRef Body,
  243. ArrayRef<MCAsmMacroParameter> Parameters,
  244. ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
  245. SMLoc L);
  246. /// Are macros enabled in the parser?
  247. bool areMacrosEnabled() {return MacrosEnabledFlag;}
  248. /// Control a flag in the parser that enables or disables macros.
  249. void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
  250. /// Are we inside a macro instantiation?
  251. bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
  252. /// Handle entry to macro instantiation.
  253. ///
  254. /// \param M The macro.
  255. /// \param NameLoc Instantiation location.
  256. bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
  257. /// Handle exit from macro instantiation.
  258. void handleMacroExit();
  259. /// Extract AsmTokens for a macro argument.
  260. bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
  261. /// Parse all macro arguments for a given macro.
  262. bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
  263. void printMacroInstantiations();
  264. void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
  265. SMRange Range = std::nullopt) const {
  266. ArrayRef<SMRange> Ranges(Range);
  267. SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
  268. }
  269. static void DiagHandler(const SMDiagnostic &Diag, void *Context);
  270. /// Enter the specified file. This returns true on failure.
  271. bool enterIncludeFile(const std::string &Filename);
  272. /// Process the specified file for the .incbin directive.
  273. /// This returns true on failure.
  274. bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
  275. const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
  276. /// Reset the current lexer position to that given by \p Loc. The
  277. /// current token is not set; clients should ensure Lex() is called
  278. /// subsequently.
  279. ///
  280. /// \param InBuffer If not 0, should be the known buffer id that contains the
  281. /// location.
  282. void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
  283. /// Parse up to the end of statement and a return the contents from the
  284. /// current token until the end of the statement; the current token on exit
  285. /// will be either the EndOfStatement or EOF.
  286. StringRef parseStringToEndOfStatement() override;
  287. /// Parse until the end of a statement or a comma is encountered,
  288. /// return the contents from the current token up to the end or comma.
  289. StringRef parseStringToComma();
  290. enum class AssignmentKind {
  291. Set,
  292. Equiv,
  293. Equal,
  294. LTOSetConditional,
  295. };
  296. bool parseAssignment(StringRef Name, AssignmentKind Kind);
  297. unsigned getBinOpPrecedence(AsmToken::TokenKind K,
  298. MCBinaryExpr::Opcode &Kind);
  299. bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
  300. bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
  301. bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
  302. bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
  303. bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
  304. bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
  305. // Generic (target and platform independent) directive parsing.
  306. enum DirectiveKind {
  307. DK_NO_DIRECTIVE, // Placeholder
  308. DK_SET,
  309. DK_EQU,
  310. DK_EQUIV,
  311. DK_ASCII,
  312. DK_ASCIZ,
  313. DK_STRING,
  314. DK_BYTE,
  315. DK_SHORT,
  316. DK_RELOC,
  317. DK_VALUE,
  318. DK_2BYTE,
  319. DK_LONG,
  320. DK_INT,
  321. DK_4BYTE,
  322. DK_QUAD,
  323. DK_8BYTE,
  324. DK_OCTA,
  325. DK_DC,
  326. DK_DC_A,
  327. DK_DC_B,
  328. DK_DC_D,
  329. DK_DC_L,
  330. DK_DC_S,
  331. DK_DC_W,
  332. DK_DC_X,
  333. DK_DCB,
  334. DK_DCB_B,
  335. DK_DCB_D,
  336. DK_DCB_L,
  337. DK_DCB_S,
  338. DK_DCB_W,
  339. DK_DCB_X,
  340. DK_DS,
  341. DK_DS_B,
  342. DK_DS_D,
  343. DK_DS_L,
  344. DK_DS_P,
  345. DK_DS_S,
  346. DK_DS_W,
  347. DK_DS_X,
  348. DK_SINGLE,
  349. DK_FLOAT,
  350. DK_DOUBLE,
  351. DK_ALIGN,
  352. DK_ALIGN32,
  353. DK_BALIGN,
  354. DK_BALIGNW,
  355. DK_BALIGNL,
  356. DK_P2ALIGN,
  357. DK_P2ALIGNW,
  358. DK_P2ALIGNL,
  359. DK_ORG,
  360. DK_FILL,
  361. DK_ENDR,
  362. DK_BUNDLE_ALIGN_MODE,
  363. DK_BUNDLE_LOCK,
  364. DK_BUNDLE_UNLOCK,
  365. DK_ZERO,
  366. DK_EXTERN,
  367. DK_GLOBL,
  368. DK_GLOBAL,
  369. DK_LAZY_REFERENCE,
  370. DK_NO_DEAD_STRIP,
  371. DK_SYMBOL_RESOLVER,
  372. DK_PRIVATE_EXTERN,
  373. DK_REFERENCE,
  374. DK_WEAK_DEFINITION,
  375. DK_WEAK_REFERENCE,
  376. DK_WEAK_DEF_CAN_BE_HIDDEN,
  377. DK_COLD,
  378. DK_COMM,
  379. DK_COMMON,
  380. DK_LCOMM,
  381. DK_ABORT,
  382. DK_INCLUDE,
  383. DK_INCBIN,
  384. DK_CODE16,
  385. DK_CODE16GCC,
  386. DK_REPT,
  387. DK_IRP,
  388. DK_IRPC,
  389. DK_IF,
  390. DK_IFEQ,
  391. DK_IFGE,
  392. DK_IFGT,
  393. DK_IFLE,
  394. DK_IFLT,
  395. DK_IFNE,
  396. DK_IFB,
  397. DK_IFNB,
  398. DK_IFC,
  399. DK_IFEQS,
  400. DK_IFNC,
  401. DK_IFNES,
  402. DK_IFDEF,
  403. DK_IFNDEF,
  404. DK_IFNOTDEF,
  405. DK_ELSEIF,
  406. DK_ELSE,
  407. DK_ENDIF,
  408. DK_SPACE,
  409. DK_SKIP,
  410. DK_FILE,
  411. DK_LINE,
  412. DK_LOC,
  413. DK_STABS,
  414. DK_CV_FILE,
  415. DK_CV_FUNC_ID,
  416. DK_CV_INLINE_SITE_ID,
  417. DK_CV_LOC,
  418. DK_CV_LINETABLE,
  419. DK_CV_INLINE_LINETABLE,
  420. DK_CV_DEF_RANGE,
  421. DK_CV_STRINGTABLE,
  422. DK_CV_STRING,
  423. DK_CV_FILECHECKSUMS,
  424. DK_CV_FILECHECKSUM_OFFSET,
  425. DK_CV_FPO_DATA,
  426. DK_CFI_SECTIONS,
  427. DK_CFI_STARTPROC,
  428. DK_CFI_ENDPROC,
  429. DK_CFI_DEF_CFA,
  430. DK_CFI_DEF_CFA_OFFSET,
  431. DK_CFI_ADJUST_CFA_OFFSET,
  432. DK_CFI_DEF_CFA_REGISTER,
  433. DK_CFI_LLVM_DEF_ASPACE_CFA,
  434. DK_CFI_OFFSET,
  435. DK_CFI_REL_OFFSET,
  436. DK_CFI_PERSONALITY,
  437. DK_CFI_LSDA,
  438. DK_CFI_REMEMBER_STATE,
  439. DK_CFI_RESTORE_STATE,
  440. DK_CFI_SAME_VALUE,
  441. DK_CFI_RESTORE,
  442. DK_CFI_ESCAPE,
  443. DK_CFI_RETURN_COLUMN,
  444. DK_CFI_SIGNAL_FRAME,
  445. DK_CFI_UNDEFINED,
  446. DK_CFI_REGISTER,
  447. DK_CFI_WINDOW_SAVE,
  448. DK_CFI_B_KEY_FRAME,
  449. DK_MACROS_ON,
  450. DK_MACROS_OFF,
  451. DK_ALTMACRO,
  452. DK_NOALTMACRO,
  453. DK_MACRO,
  454. DK_EXITM,
  455. DK_ENDM,
  456. DK_ENDMACRO,
  457. DK_PURGEM,
  458. DK_SLEB128,
  459. DK_ULEB128,
  460. DK_ERR,
  461. DK_ERROR,
  462. DK_WARNING,
  463. DK_PRINT,
  464. DK_ADDRSIG,
  465. DK_ADDRSIG_SYM,
  466. DK_PSEUDO_PROBE,
  467. DK_LTO_DISCARD,
  468. DK_LTO_SET_CONDITIONAL,
  469. DK_CFI_MTE_TAGGED_FRAME,
  470. DK_MEMTAG,
  471. DK_END
  472. };
  473. /// Maps directive name --> DirectiveKind enum, for
  474. /// directives parsed by this class.
  475. StringMap<DirectiveKind> DirectiveKindMap;
  476. // Codeview def_range type parsing.
  477. enum CVDefRangeType {
  478. CVDR_DEFRANGE = 0, // Placeholder
  479. CVDR_DEFRANGE_REGISTER,
  480. CVDR_DEFRANGE_FRAMEPOINTER_REL,
  481. CVDR_DEFRANGE_SUBFIELD_REGISTER,
  482. CVDR_DEFRANGE_REGISTER_REL
  483. };
  484. /// Maps Codeview def_range types --> CVDefRangeType enum, for
  485. /// Codeview def_range types parsed by this class.
  486. StringMap<CVDefRangeType> CVDefRangeTypeMap;
  487. // ".ascii", ".asciz", ".string"
  488. bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
  489. bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
  490. bool parseDirectiveValue(StringRef IDVal,
  491. unsigned Size); // ".byte", ".long", ...
  492. bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
  493. bool parseDirectiveRealValue(StringRef IDVal,
  494. const fltSemantics &); // ".single", ...
  495. bool parseDirectiveFill(); // ".fill"
  496. bool parseDirectiveZero(); // ".zero"
  497. // ".set", ".equ", ".equiv", ".lto_set_conditional"
  498. bool parseDirectiveSet(StringRef IDVal, AssignmentKind Kind);
  499. bool parseDirectiveOrg(); // ".org"
  500. // ".align{,32}", ".p2align{,w,l}"
  501. bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
  502. // ".file", ".line", ".loc", ".stabs"
  503. bool parseDirectiveFile(SMLoc DirectiveLoc);
  504. bool parseDirectiveLine();
  505. bool parseDirectiveLoc();
  506. bool parseDirectiveStabs();
  507. // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
  508. // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
  509. bool parseDirectiveCVFile();
  510. bool parseDirectiveCVFuncId();
  511. bool parseDirectiveCVInlineSiteId();
  512. bool parseDirectiveCVLoc();
  513. bool parseDirectiveCVLinetable();
  514. bool parseDirectiveCVInlineLinetable();
  515. bool parseDirectiveCVDefRange();
  516. bool parseDirectiveCVString();
  517. bool parseDirectiveCVStringTable();
  518. bool parseDirectiveCVFileChecksums();
  519. bool parseDirectiveCVFileChecksumOffset();
  520. bool parseDirectiveCVFPOData();
  521. // .cfi directives
  522. bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
  523. bool parseDirectiveCFIWindowSave();
  524. bool parseDirectiveCFISections();
  525. bool parseDirectiveCFIStartProc();
  526. bool parseDirectiveCFIEndProc();
  527. bool parseDirectiveCFIDefCfaOffset();
  528. bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
  529. bool parseDirectiveCFIAdjustCfaOffset();
  530. bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
  531. bool parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc);
  532. bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
  533. bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
  534. bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
  535. bool parseDirectiveCFIRememberState();
  536. bool parseDirectiveCFIRestoreState();
  537. bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
  538. bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
  539. bool parseDirectiveCFIEscape();
  540. bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
  541. bool parseDirectiveCFISignalFrame();
  542. bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
  543. // macro directives
  544. bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
  545. bool parseDirectiveExitMacro(StringRef Directive);
  546. bool parseDirectiveEndMacro(StringRef Directive);
  547. bool parseDirectiveMacro(SMLoc DirectiveLoc);
  548. bool parseDirectiveMacrosOnOff(StringRef Directive);
  549. // alternate macro mode directives
  550. bool parseDirectiveAltmacro(StringRef Directive);
  551. // ".bundle_align_mode"
  552. bool parseDirectiveBundleAlignMode();
  553. // ".bundle_lock"
  554. bool parseDirectiveBundleLock();
  555. // ".bundle_unlock"
  556. bool parseDirectiveBundleUnlock();
  557. // ".space", ".skip"
  558. bool parseDirectiveSpace(StringRef IDVal);
  559. // ".dcb"
  560. bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
  561. bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
  562. // ".ds"
  563. bool parseDirectiveDS(StringRef IDVal, unsigned Size);
  564. // .sleb128 (Signed=true) and .uleb128 (Signed=false)
  565. bool parseDirectiveLEB128(bool Signed);
  566. /// Parse a directive like ".globl" which
  567. /// accepts a single symbol (which should be a label or an external).
  568. bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
  569. bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
  570. bool parseDirectiveAbort(); // ".abort"
  571. bool parseDirectiveInclude(); // ".include"
  572. bool parseDirectiveIncbin(); // ".incbin"
  573. // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
  574. bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
  575. // ".ifb" or ".ifnb", depending on ExpectBlank.
  576. bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
  577. // ".ifc" or ".ifnc", depending on ExpectEqual.
  578. bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
  579. // ".ifeqs" or ".ifnes", depending on ExpectEqual.
  580. bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
  581. // ".ifdef" or ".ifndef", depending on expect_defined
  582. bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
  583. bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
  584. bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
  585. bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
  586. bool parseEscapedString(std::string &Data) override;
  587. bool parseAngleBracketString(std::string &Data) override;
  588. const MCExpr *applyModifierToExpr(const MCExpr *E,
  589. MCSymbolRefExpr::VariantKind Variant);
  590. // Macro-like directives
  591. MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
  592. void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
  593. raw_svector_ostream &OS);
  594. bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
  595. bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
  596. bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
  597. bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
  598. // "_emit" or "__emit"
  599. bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
  600. size_t Len);
  601. // "align"
  602. bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
  603. // "end"
  604. bool parseDirectiveEnd(SMLoc DirectiveLoc);
  605. // ".err" or ".error"
  606. bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
  607. // ".warning"
  608. bool parseDirectiveWarning(SMLoc DirectiveLoc);
  609. // .print <double-quotes-string>
  610. bool parseDirectivePrint(SMLoc DirectiveLoc);
  611. // .pseudoprobe
  612. bool parseDirectivePseudoProbe();
  613. // ".lto_discard"
  614. bool parseDirectiveLTODiscard();
  615. // Directives to support address-significance tables.
  616. bool parseDirectiveAddrsig();
  617. bool parseDirectiveAddrsigSym();
  618. void initializeDirectiveKindMap();
  619. void initializeCVDefRangeTypeMap();
  620. };
  621. class HLASMAsmParser final : public AsmParser {
  622. private:
  623. MCAsmLexer &Lexer;
  624. MCStreamer &Out;
  625. void lexLeadingSpaces() {
  626. while (Lexer.is(AsmToken::Space))
  627. Lexer.Lex();
  628. }
  629. bool parseAsHLASMLabel(ParseStatementInfo &Info, MCAsmParserSemaCallback *SI);
  630. bool parseAsMachineInstruction(ParseStatementInfo &Info,
  631. MCAsmParserSemaCallback *SI);
  632. public:
  633. HLASMAsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
  634. const MCAsmInfo &MAI, unsigned CB = 0)
  635. : AsmParser(SM, Ctx, Out, MAI, CB), Lexer(getLexer()), Out(Out) {
  636. Lexer.setSkipSpace(false);
  637. Lexer.setAllowHashInIdentifier(true);
  638. Lexer.setLexHLASMIntegers(true);
  639. Lexer.setLexHLASMStrings(true);
  640. }
  641. ~HLASMAsmParser() { Lexer.setSkipSpace(true); }
  642. bool parseStatement(ParseStatementInfo &Info,
  643. MCAsmParserSemaCallback *SI) override;
  644. };
  645. } // end anonymous namespace
  646. namespace llvm {
  647. extern cl::opt<unsigned> AsmMacroMaxNestingDepth;
  648. extern MCAsmParserExtension *createDarwinAsmParser();
  649. extern MCAsmParserExtension *createELFAsmParser();
  650. extern MCAsmParserExtension *createCOFFAsmParser();
  651. extern MCAsmParserExtension *createGOFFAsmParser();
  652. extern MCAsmParserExtension *createXCOFFAsmParser();
  653. extern MCAsmParserExtension *createWasmAsmParser();
  654. } // end namespace llvm
  655. enum { DEFAULT_ADDRSPACE = 0 };
  656. AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
  657. const MCAsmInfo &MAI, unsigned CB = 0)
  658. : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
  659. CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
  660. HadError = false;
  661. // Save the old handler.
  662. SavedDiagHandler = SrcMgr.getDiagHandler();
  663. SavedDiagContext = SrcMgr.getDiagContext();
  664. // Set our own handler which calls the saved handler.
  665. SrcMgr.setDiagHandler(DiagHandler, this);
  666. Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
  667. // Make MCStreamer aware of the StartTokLoc for locations in diagnostics.
  668. Out.setStartTokLocPtr(&StartTokLoc);
  669. // Initialize the platform / file format parser.
  670. switch (Ctx.getObjectFileType()) {
  671. case MCContext::IsCOFF:
  672. PlatformParser.reset(createCOFFAsmParser());
  673. break;
  674. case MCContext::IsMachO:
  675. PlatformParser.reset(createDarwinAsmParser());
  676. IsDarwin = true;
  677. break;
  678. case MCContext::IsELF:
  679. PlatformParser.reset(createELFAsmParser());
  680. break;
  681. case MCContext::IsGOFF:
  682. PlatformParser.reset(createGOFFAsmParser());
  683. break;
  684. case MCContext::IsSPIRV:
  685. report_fatal_error(
  686. "Need to implement createSPIRVAsmParser for SPIRV format.");
  687. break;
  688. case MCContext::IsWasm:
  689. PlatformParser.reset(createWasmAsmParser());
  690. break;
  691. case MCContext::IsXCOFF:
  692. PlatformParser.reset(createXCOFFAsmParser());
  693. break;
  694. case MCContext::IsDXContainer:
  695. llvm_unreachable("DXContainer is not supported yet");
  696. break;
  697. }
  698. PlatformParser->Initialize(*this);
  699. initializeDirectiveKindMap();
  700. initializeCVDefRangeTypeMap();
  701. NumOfMacroInstantiations = 0;
  702. }
  703. AsmParser::~AsmParser() {
  704. assert((HadError || ActiveMacros.empty()) &&
  705. "Unexpected active macro instantiation!");
  706. // Remove MCStreamer's reference to the parser SMLoc.
  707. Out.setStartTokLocPtr(nullptr);
  708. // Restore the saved diagnostics handler and context for use during
  709. // finalization.
  710. SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
  711. }
  712. void AsmParser::printMacroInstantiations() {
  713. // Print the active macro instantiation stack.
  714. for (std::vector<MacroInstantiation *>::const_reverse_iterator
  715. it = ActiveMacros.rbegin(),
  716. ie = ActiveMacros.rend();
  717. it != ie; ++it)
  718. printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
  719. "while in macro instantiation");
  720. }
  721. void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
  722. printPendingErrors();
  723. printMessage(L, SourceMgr::DK_Note, Msg, Range);
  724. printMacroInstantiations();
  725. }
  726. bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
  727. if(getTargetParser().getTargetOptions().MCNoWarn)
  728. return false;
  729. if (getTargetParser().getTargetOptions().MCFatalWarnings)
  730. return Error(L, Msg, Range);
  731. printMessage(L, SourceMgr::DK_Warning, Msg, Range);
  732. printMacroInstantiations();
  733. return false;
  734. }
  735. bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
  736. HadError = true;
  737. printMessage(L, SourceMgr::DK_Error, Msg, Range);
  738. printMacroInstantiations();
  739. return true;
  740. }
  741. bool AsmParser::enterIncludeFile(const std::string &Filename) {
  742. std::string IncludedFile;
  743. unsigned NewBuf =
  744. SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
  745. if (!NewBuf)
  746. return true;
  747. CurBuffer = NewBuf;
  748. Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
  749. return false;
  750. }
  751. /// Process the specified .incbin file by searching for it in the include paths
  752. /// then just emitting the byte contents of the file to the streamer. This
  753. /// returns true on failure.
  754. bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
  755. const MCExpr *Count, SMLoc Loc) {
  756. std::string IncludedFile;
  757. unsigned NewBuf =
  758. SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
  759. if (!NewBuf)
  760. return true;
  761. // Pick up the bytes from the file and emit them.
  762. StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
  763. Bytes = Bytes.drop_front(Skip);
  764. if (Count) {
  765. int64_t Res;
  766. if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
  767. return Error(Loc, "expected absolute expression");
  768. if (Res < 0)
  769. return Warning(Loc, "negative count has no effect");
  770. Bytes = Bytes.take_front(Res);
  771. }
  772. getStreamer().emitBytes(Bytes);
  773. return false;
  774. }
  775. void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
  776. CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
  777. Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
  778. Loc.getPointer());
  779. }
  780. const AsmToken &AsmParser::Lex() {
  781. if (Lexer.getTok().is(AsmToken::Error))
  782. Error(Lexer.getErrLoc(), Lexer.getErr());
  783. // if it's a end of statement with a comment in it
  784. if (getTok().is(AsmToken::EndOfStatement)) {
  785. // if this is a line comment output it.
  786. if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
  787. getTok().getString().front() != '\r' && MAI.preserveAsmComments())
  788. Out.addExplicitComment(Twine(getTok().getString()));
  789. }
  790. const AsmToken *tok = &Lexer.Lex();
  791. // Parse comments here to be deferred until end of next statement.
  792. while (tok->is(AsmToken::Comment)) {
  793. if (MAI.preserveAsmComments())
  794. Out.addExplicitComment(Twine(tok->getString()));
  795. tok = &Lexer.Lex();
  796. }
  797. if (tok->is(AsmToken::Eof)) {
  798. // If this is the end of an included file, pop the parent file off the
  799. // include stack.
  800. SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
  801. if (ParentIncludeLoc != SMLoc()) {
  802. jumpToLoc(ParentIncludeLoc);
  803. return Lex();
  804. }
  805. }
  806. return *tok;
  807. }
  808. bool AsmParser::enabledGenDwarfForAssembly() {
  809. // Check whether the user specified -g.
  810. if (!getContext().getGenDwarfForAssembly())
  811. return false;
  812. // If we haven't encountered any .file directives (which would imply that
  813. // the assembler source was produced with debug info already) then emit one
  814. // describing the assembler source file itself.
  815. if (getContext().getGenDwarfFileNumber() == 0) {
  816. // Use the first #line directive for this, if any. It's preprocessed, so
  817. // there is no checksum, and of course no source directive.
  818. if (!FirstCppHashFilename.empty())
  819. getContext().setMCLineTableRootFile(
  820. /*CUID=*/0, getContext().getCompilationDir(), FirstCppHashFilename,
  821. /*Cksum=*/std::nullopt, /*Source=*/std::nullopt);
  822. const MCDwarfFile &RootFile =
  823. getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
  824. getContext().setGenDwarfFileNumber(getStreamer().emitDwarfFileDirective(
  825. /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
  826. RootFile.Checksum, RootFile.Source));
  827. }
  828. return true;
  829. }
  830. bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
  831. LTODiscardSymbols.clear();
  832. // Create the initial section, if requested.
  833. if (!NoInitialTextSection)
  834. Out.initSections(false, getTargetParser().getSTI());
  835. // Prime the lexer.
  836. Lex();
  837. HadError = false;
  838. AsmCond StartingCondState = TheCondState;
  839. SmallVector<AsmRewrite, 4> AsmStrRewrites;
  840. // If we are generating dwarf for assembly source files save the initial text
  841. // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
  842. // emitting any actual debug info yet and haven't had a chance to parse any
  843. // embedded .file directives.)
  844. if (getContext().getGenDwarfForAssembly()) {
  845. MCSection *Sec = getStreamer().getCurrentSectionOnly();
  846. if (!Sec->getBeginSymbol()) {
  847. MCSymbol *SectionStartSym = getContext().createTempSymbol();
  848. getStreamer().emitLabel(SectionStartSym);
  849. Sec->setBeginSymbol(SectionStartSym);
  850. }
  851. bool InsertResult = getContext().addGenDwarfSection(Sec);
  852. assert(InsertResult && ".text section should not have debug info yet");
  853. (void)InsertResult;
  854. }
  855. getTargetParser().onBeginOfFile();
  856. // While we have input, parse each statement.
  857. while (Lexer.isNot(AsmToken::Eof)) {
  858. ParseStatementInfo Info(&AsmStrRewrites);
  859. bool Parsed = parseStatement(Info, nullptr);
  860. // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
  861. // for printing ErrMsg via Lex() only if no (presumably better) parser error
  862. // exists.
  863. if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
  864. Lex();
  865. }
  866. // parseStatement returned true so may need to emit an error.
  867. printPendingErrors();
  868. // Skipping to the next line if needed.
  869. if (Parsed && !getLexer().isAtStartOfStatement())
  870. eatToEndOfStatement();
  871. }
  872. getTargetParser().onEndOfFile();
  873. printPendingErrors();
  874. // All errors should have been emitted.
  875. assert(!hasPendingError() && "unexpected error from parseStatement");
  876. getTargetParser().flushPendingInstructions(getStreamer());
  877. if (TheCondState.TheCond != StartingCondState.TheCond ||
  878. TheCondState.Ignore != StartingCondState.Ignore)
  879. printError(getTok().getLoc(), "unmatched .ifs or .elses");
  880. // Check to see there are no empty DwarfFile slots.
  881. const auto &LineTables = getContext().getMCDwarfLineTables();
  882. if (!LineTables.empty()) {
  883. unsigned Index = 0;
  884. for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
  885. if (File.Name.empty() && Index != 0)
  886. printError(getTok().getLoc(), "unassigned file number: " +
  887. Twine(Index) +
  888. " for .file directives");
  889. ++Index;
  890. }
  891. }
  892. // Check to see that all assembler local symbols were actually defined.
  893. // Targets that don't do subsections via symbols may not want this, though,
  894. // so conservatively exclude them. Only do this if we're finalizing, though,
  895. // as otherwise we won't necessarilly have seen everything yet.
  896. if (!NoFinalize) {
  897. if (MAI.hasSubsectionsViaSymbols()) {
  898. for (const auto &TableEntry : getContext().getSymbols()) {
  899. MCSymbol *Sym = TableEntry.getValue();
  900. // Variable symbols may not be marked as defined, so check those
  901. // explicitly. If we know it's a variable, we have a definition for
  902. // the purposes of this check.
  903. if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
  904. // FIXME: We would really like to refer back to where the symbol was
  905. // first referenced for a source location. We need to add something
  906. // to track that. Currently, we just point to the end of the file.
  907. printError(getTok().getLoc(), "assembler local symbol '" +
  908. Sym->getName() + "' not defined");
  909. }
  910. }
  911. // Temporary symbols like the ones for directional jumps don't go in the
  912. // symbol table. They also need to be diagnosed in all (final) cases.
  913. for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
  914. if (std::get<2>(LocSym)->isUndefined()) {
  915. // Reset the state of any "# line file" directives we've seen to the
  916. // context as it was at the diagnostic site.
  917. CppHashInfo = std::get<1>(LocSym);
  918. printError(std::get<0>(LocSym), "directional label undefined");
  919. }
  920. }
  921. }
  922. // Finalize the output stream if there are no errors and if the client wants
  923. // us to.
  924. if (!HadError && !NoFinalize) {
  925. if (auto *TS = Out.getTargetStreamer())
  926. TS->emitConstantPools();
  927. Out.finish(Lexer.getLoc());
  928. }
  929. return HadError || getContext().hadError();
  930. }
  931. bool AsmParser::checkForValidSection() {
  932. if (!ParsingMSInlineAsm && !getStreamer().getCurrentSectionOnly()) {
  933. Out.initSections(false, getTargetParser().getSTI());
  934. return Error(getTok().getLoc(),
  935. "expected section directive before assembly directive");
  936. }
  937. return false;
  938. }
  939. /// Throw away the rest of the line for testing purposes.
  940. void AsmParser::eatToEndOfStatement() {
  941. while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
  942. Lexer.Lex();
  943. // Eat EOL.
  944. if (Lexer.is(AsmToken::EndOfStatement))
  945. Lexer.Lex();
  946. }
  947. StringRef AsmParser::parseStringToEndOfStatement() {
  948. const char *Start = getTok().getLoc().getPointer();
  949. while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
  950. Lexer.Lex();
  951. const char *End = getTok().getLoc().getPointer();
  952. return StringRef(Start, End - Start);
  953. }
  954. StringRef AsmParser::parseStringToComma() {
  955. const char *Start = getTok().getLoc().getPointer();
  956. while (Lexer.isNot(AsmToken::EndOfStatement) &&
  957. Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
  958. Lexer.Lex();
  959. const char *End = getTok().getLoc().getPointer();
  960. return StringRef(Start, End - Start);
  961. }
  962. /// Parse a paren expression and return it.
  963. /// NOTE: This assumes the leading '(' has already been consumed.
  964. ///
  965. /// parenexpr ::= expr)
  966. ///
  967. bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
  968. if (parseExpression(Res))
  969. return true;
  970. EndLoc = Lexer.getTok().getEndLoc();
  971. return parseRParen();
  972. }
  973. /// Parse a bracket expression and return it.
  974. /// NOTE: This assumes the leading '[' has already been consumed.
  975. ///
  976. /// bracketexpr ::= expr]
  977. ///
  978. bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
  979. if (parseExpression(Res))
  980. return true;
  981. EndLoc = getTok().getEndLoc();
  982. if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
  983. return true;
  984. return false;
  985. }
  986. /// Parse a primary expression and return it.
  987. /// primaryexpr ::= (parenexpr
  988. /// primaryexpr ::= symbol
  989. /// primaryexpr ::= number
  990. /// primaryexpr ::= '.'
  991. /// primaryexpr ::= ~,+,- primaryexpr
  992. bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc,
  993. AsmTypeInfo *TypeInfo) {
  994. SMLoc FirstTokenLoc = getLexer().getLoc();
  995. AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
  996. switch (FirstTokenKind) {
  997. default:
  998. return TokError("unknown token in expression");
  999. // If we have an error assume that we've already handled it.
  1000. case AsmToken::Error:
  1001. return true;
  1002. case AsmToken::Exclaim:
  1003. Lex(); // Eat the operator.
  1004. if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
  1005. return true;
  1006. Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
  1007. return false;
  1008. case AsmToken::Dollar:
  1009. case AsmToken::Star:
  1010. case AsmToken::At:
  1011. case AsmToken::String:
  1012. case AsmToken::Identifier: {
  1013. StringRef Identifier;
  1014. if (parseIdentifier(Identifier)) {
  1015. // We may have failed but '$'|'*' may be a valid token in context of
  1016. // the current PC.
  1017. if (getTok().is(AsmToken::Dollar) || getTok().is(AsmToken::Star)) {
  1018. bool ShouldGenerateTempSymbol = false;
  1019. if ((getTok().is(AsmToken::Dollar) && MAI.getDollarIsPC()) ||
  1020. (getTok().is(AsmToken::Star) && MAI.getStarIsPC()))
  1021. ShouldGenerateTempSymbol = true;
  1022. if (!ShouldGenerateTempSymbol)
  1023. return Error(FirstTokenLoc, "invalid token in expression");
  1024. // Eat the '$'|'*' token.
  1025. Lex();
  1026. // This is either a '$'|'*' reference, which references the current PC.
  1027. // Emit a temporary label to the streamer and refer to it.
  1028. MCSymbol *Sym = Ctx.createTempSymbol();
  1029. Out.emitLabel(Sym);
  1030. Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
  1031. getContext());
  1032. EndLoc = FirstTokenLoc;
  1033. return false;
  1034. }
  1035. }
  1036. // Parse symbol variant
  1037. std::pair<StringRef, StringRef> Split;
  1038. if (!MAI.useParensForSymbolVariant()) {
  1039. if (FirstTokenKind == AsmToken::String) {
  1040. if (Lexer.is(AsmToken::At)) {
  1041. Lex(); // eat @
  1042. SMLoc AtLoc = getLexer().getLoc();
  1043. StringRef VName;
  1044. if (parseIdentifier(VName))
  1045. return Error(AtLoc, "expected symbol variant after '@'");
  1046. Split = std::make_pair(Identifier, VName);
  1047. }
  1048. } else {
  1049. Split = Identifier.split('@');
  1050. }
  1051. } else if (Lexer.is(AsmToken::LParen)) {
  1052. Lex(); // eat '('.
  1053. StringRef VName;
  1054. parseIdentifier(VName);
  1055. if (parseRParen())
  1056. return true;
  1057. Split = std::make_pair(Identifier, VName);
  1058. }
  1059. EndLoc = SMLoc::getFromPointer(Identifier.end());
  1060. // This is a symbol reference.
  1061. StringRef SymbolName = Identifier;
  1062. if (SymbolName.empty())
  1063. return Error(getLexer().getLoc(), "expected a symbol reference");
  1064. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  1065. // Lookup the symbol variant if used.
  1066. if (!Split.second.empty()) {
  1067. Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
  1068. if (Variant != MCSymbolRefExpr::VK_Invalid) {
  1069. SymbolName = Split.first;
  1070. } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
  1071. Variant = MCSymbolRefExpr::VK_None;
  1072. } else {
  1073. return Error(SMLoc::getFromPointer(Split.second.begin()),
  1074. "invalid variant '" + Split.second + "'");
  1075. }
  1076. }
  1077. MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
  1078. if (!Sym)
  1079. Sym = getContext().getOrCreateSymbol(
  1080. MAI.shouldEmitLabelsInUpperCase() ? SymbolName.upper() : SymbolName);
  1081. // If this is an absolute variable reference, substitute it now to preserve
  1082. // semantics in the face of reassignment.
  1083. if (Sym->isVariable()) {
  1084. auto V = Sym->getVariableValue(/*SetUsed*/ false);
  1085. bool DoInline = isa<MCConstantExpr>(V) && !Variant;
  1086. if (auto TV = dyn_cast<MCTargetExpr>(V))
  1087. DoInline = TV->inlineAssignedExpr();
  1088. if (DoInline) {
  1089. if (Variant)
  1090. return Error(EndLoc, "unexpected modifier on variable reference");
  1091. Res = Sym->getVariableValue(/*SetUsed*/ false);
  1092. return false;
  1093. }
  1094. }
  1095. // Otherwise create a symbol ref.
  1096. Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
  1097. return false;
  1098. }
  1099. case AsmToken::BigNum:
  1100. return TokError("literal value out of range for directive");
  1101. case AsmToken::Integer: {
  1102. SMLoc Loc = getTok().getLoc();
  1103. int64_t IntVal = getTok().getIntVal();
  1104. Res = MCConstantExpr::create(IntVal, getContext());
  1105. EndLoc = Lexer.getTok().getEndLoc();
  1106. Lex(); // Eat token.
  1107. // Look for 'b' or 'f' following an Integer as a directional label
  1108. if (Lexer.getKind() == AsmToken::Identifier) {
  1109. StringRef IDVal = getTok().getString();
  1110. // Lookup the symbol variant if used.
  1111. std::pair<StringRef, StringRef> Split = IDVal.split('@');
  1112. MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
  1113. if (Split.first.size() != IDVal.size()) {
  1114. Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
  1115. if (Variant == MCSymbolRefExpr::VK_Invalid)
  1116. return TokError("invalid variant '" + Split.second + "'");
  1117. IDVal = Split.first;
  1118. }
  1119. if (IDVal == "f" || IDVal == "b") {
  1120. MCSymbol *Sym =
  1121. Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
  1122. Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
  1123. if (IDVal == "b" && Sym->isUndefined())
  1124. return Error(Loc, "directional label undefined");
  1125. DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
  1126. EndLoc = Lexer.getTok().getEndLoc();
  1127. Lex(); // Eat identifier.
  1128. }
  1129. }
  1130. return false;
  1131. }
  1132. case AsmToken::Real: {
  1133. APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
  1134. uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
  1135. Res = MCConstantExpr::create(IntVal, getContext());
  1136. EndLoc = Lexer.getTok().getEndLoc();
  1137. Lex(); // Eat token.
  1138. return false;
  1139. }
  1140. case AsmToken::Dot: {
  1141. if (!MAI.getDotIsPC())
  1142. return TokError("cannot use . as current PC");
  1143. // This is a '.' reference, which references the current PC. Emit a
  1144. // temporary label to the streamer and refer to it.
  1145. MCSymbol *Sym = Ctx.createTempSymbol();
  1146. Out.emitLabel(Sym);
  1147. Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
  1148. EndLoc = Lexer.getTok().getEndLoc();
  1149. Lex(); // Eat identifier.
  1150. return false;
  1151. }
  1152. case AsmToken::LParen:
  1153. Lex(); // Eat the '('.
  1154. return parseParenExpr(Res, EndLoc);
  1155. case AsmToken::LBrac:
  1156. if (!PlatformParser->HasBracketExpressions())
  1157. return TokError("brackets expression not supported on this target");
  1158. Lex(); // Eat the '['.
  1159. return parseBracketExpr(Res, EndLoc);
  1160. case AsmToken::Minus:
  1161. Lex(); // Eat the operator.
  1162. if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
  1163. return true;
  1164. Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
  1165. return false;
  1166. case AsmToken::Plus:
  1167. Lex(); // Eat the operator.
  1168. if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
  1169. return true;
  1170. Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
  1171. return false;
  1172. case AsmToken::Tilde:
  1173. Lex(); // Eat the operator.
  1174. if (parsePrimaryExpr(Res, EndLoc, TypeInfo))
  1175. return true;
  1176. Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
  1177. return false;
  1178. // MIPS unary expression operators. The lexer won't generate these tokens if
  1179. // MCAsmInfo::HasMipsExpressions is false for the target.
  1180. case AsmToken::PercentCall16:
  1181. case AsmToken::PercentCall_Hi:
  1182. case AsmToken::PercentCall_Lo:
  1183. case AsmToken::PercentDtprel_Hi:
  1184. case AsmToken::PercentDtprel_Lo:
  1185. case AsmToken::PercentGot:
  1186. case AsmToken::PercentGot_Disp:
  1187. case AsmToken::PercentGot_Hi:
  1188. case AsmToken::PercentGot_Lo:
  1189. case AsmToken::PercentGot_Ofst:
  1190. case AsmToken::PercentGot_Page:
  1191. case AsmToken::PercentGottprel:
  1192. case AsmToken::PercentGp_Rel:
  1193. case AsmToken::PercentHi:
  1194. case AsmToken::PercentHigher:
  1195. case AsmToken::PercentHighest:
  1196. case AsmToken::PercentLo:
  1197. case AsmToken::PercentNeg:
  1198. case AsmToken::PercentPcrel_Hi:
  1199. case AsmToken::PercentPcrel_Lo:
  1200. case AsmToken::PercentTlsgd:
  1201. case AsmToken::PercentTlsldm:
  1202. case AsmToken::PercentTprel_Hi:
  1203. case AsmToken::PercentTprel_Lo:
  1204. Lex(); // Eat the operator.
  1205. if (Lexer.isNot(AsmToken::LParen))
  1206. return TokError("expected '(' after operator");
  1207. Lex(); // Eat the operator.
  1208. if (parseExpression(Res, EndLoc))
  1209. return true;
  1210. if (parseRParen())
  1211. return true;
  1212. Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
  1213. return !Res;
  1214. }
  1215. }
  1216. bool AsmParser::parseExpression(const MCExpr *&Res) {
  1217. SMLoc EndLoc;
  1218. return parseExpression(Res, EndLoc);
  1219. }
  1220. const MCExpr *
  1221. AsmParser::applyModifierToExpr(const MCExpr *E,
  1222. MCSymbolRefExpr::VariantKind Variant) {
  1223. // Ask the target implementation about this expression first.
  1224. const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
  1225. if (NewE)
  1226. return NewE;
  1227. // Recurse over the given expression, rebuilding it to apply the given variant
  1228. // if there is exactly one symbol.
  1229. switch (E->getKind()) {
  1230. case MCExpr::Target:
  1231. case MCExpr::Constant:
  1232. return nullptr;
  1233. case MCExpr::SymbolRef: {
  1234. const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
  1235. if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
  1236. TokError("invalid variant on expression '" + getTok().getIdentifier() +
  1237. "' (already modified)");
  1238. return E;
  1239. }
  1240. return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
  1241. }
  1242. case MCExpr::Unary: {
  1243. const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
  1244. const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
  1245. if (!Sub)
  1246. return nullptr;
  1247. return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
  1248. }
  1249. case MCExpr::Binary: {
  1250. const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
  1251. const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
  1252. const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
  1253. if (!LHS && !RHS)
  1254. return nullptr;
  1255. if (!LHS)
  1256. LHS = BE->getLHS();
  1257. if (!RHS)
  1258. RHS = BE->getRHS();
  1259. return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
  1260. }
  1261. }
  1262. llvm_unreachable("Invalid expression kind!");
  1263. }
  1264. /// This function checks if the next token is <string> type or arithmetic.
  1265. /// string that begin with character '<' must end with character '>'.
  1266. /// otherwise it is arithmetics.
  1267. /// If the function returns a 'true' value,
  1268. /// the End argument will be filled with the last location pointed to the '>'
  1269. /// character.
  1270. /// There is a gap between the AltMacro's documentation and the single quote
  1271. /// implementation. GCC does not fully support this feature and so we will not
  1272. /// support it.
  1273. /// TODO: Adding single quote as a string.
  1274. static bool isAngleBracketString(SMLoc &StrLoc, SMLoc &EndLoc) {
  1275. assert((StrLoc.getPointer() != nullptr) &&
  1276. "Argument to the function cannot be a NULL value");
  1277. const char *CharPtr = StrLoc.getPointer();
  1278. while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
  1279. (*CharPtr != '\0')) {
  1280. if (*CharPtr == '!')
  1281. CharPtr++;
  1282. CharPtr++;
  1283. }
  1284. if (*CharPtr == '>') {
  1285. EndLoc = StrLoc.getFromPointer(CharPtr + 1);
  1286. return true;
  1287. }
  1288. return false;
  1289. }
  1290. /// creating a string without the escape characters '!'.
  1291. static std::string angleBracketString(StringRef AltMacroStr) {
  1292. std::string Res;
  1293. for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
  1294. if (AltMacroStr[Pos] == '!')
  1295. Pos++;
  1296. Res += AltMacroStr[Pos];
  1297. }
  1298. return Res;
  1299. }
  1300. /// Parse an expression and return it.
  1301. ///
  1302. /// expr ::= expr &&,|| expr -> lowest.
  1303. /// expr ::= expr |,^,&,! expr
  1304. /// expr ::= expr ==,!=,<>,<,<=,>,>= expr
  1305. /// expr ::= expr <<,>> expr
  1306. /// expr ::= expr +,- expr
  1307. /// expr ::= expr *,/,% expr -> highest.
  1308. /// expr ::= primaryexpr
  1309. ///
  1310. bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
  1311. // Parse the expression.
  1312. Res = nullptr;
  1313. if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
  1314. parseBinOpRHS(1, Res, EndLoc))
  1315. return true;
  1316. // As a special case, we support 'a op b @ modifier' by rewriting the
  1317. // expression to include the modifier. This is inefficient, but in general we
  1318. // expect users to use 'a@modifier op b'.
  1319. if (Lexer.getKind() == AsmToken::At) {
  1320. Lex();
  1321. if (Lexer.isNot(AsmToken::Identifier))
  1322. return TokError("unexpected symbol modifier following '@'");
  1323. MCSymbolRefExpr::VariantKind Variant =
  1324. MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
  1325. if (Variant == MCSymbolRefExpr::VK_Invalid)
  1326. return TokError("invalid variant '" + getTok().getIdentifier() + "'");
  1327. const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
  1328. if (!ModifiedRes) {
  1329. return TokError("invalid modifier '" + getTok().getIdentifier() +
  1330. "' (no symbols present)");
  1331. }
  1332. Res = ModifiedRes;
  1333. Lex();
  1334. }
  1335. // Try to constant fold it up front, if possible. Do not exploit
  1336. // assembler here.
  1337. int64_t Value;
  1338. if (Res->evaluateAsAbsolute(Value))
  1339. Res = MCConstantExpr::create(Value, getContext());
  1340. return false;
  1341. }
  1342. bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
  1343. Res = nullptr;
  1344. return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
  1345. }
  1346. bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
  1347. SMLoc &EndLoc) {
  1348. if (parseParenExpr(Res, EndLoc))
  1349. return true;
  1350. for (; ParenDepth > 0; --ParenDepth) {
  1351. if (parseBinOpRHS(1, Res, EndLoc))
  1352. return true;
  1353. // We don't Lex() the last RParen.
  1354. // This is the same behavior as parseParenExpression().
  1355. if (ParenDepth - 1 > 0) {
  1356. EndLoc = getTok().getEndLoc();
  1357. if (parseRParen())
  1358. return true;
  1359. }
  1360. }
  1361. return false;
  1362. }
  1363. bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
  1364. const MCExpr *Expr;
  1365. SMLoc StartLoc = Lexer.getLoc();
  1366. if (parseExpression(Expr))
  1367. return true;
  1368. if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
  1369. return Error(StartLoc, "expected absolute expression");
  1370. return false;
  1371. }
  1372. static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
  1373. MCBinaryExpr::Opcode &Kind,
  1374. bool ShouldUseLogicalShr) {
  1375. switch (K) {
  1376. default:
  1377. return 0; // not a binop.
  1378. // Lowest Precedence: &&, ||
  1379. case AsmToken::AmpAmp:
  1380. Kind = MCBinaryExpr::LAnd;
  1381. return 1;
  1382. case AsmToken::PipePipe:
  1383. Kind = MCBinaryExpr::LOr;
  1384. return 1;
  1385. // Low Precedence: |, &, ^
  1386. case AsmToken::Pipe:
  1387. Kind = MCBinaryExpr::Or;
  1388. return 2;
  1389. case AsmToken::Caret:
  1390. Kind = MCBinaryExpr::Xor;
  1391. return 2;
  1392. case AsmToken::Amp:
  1393. Kind = MCBinaryExpr::And;
  1394. return 2;
  1395. // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
  1396. case AsmToken::EqualEqual:
  1397. Kind = MCBinaryExpr::EQ;
  1398. return 3;
  1399. case AsmToken::ExclaimEqual:
  1400. case AsmToken::LessGreater:
  1401. Kind = MCBinaryExpr::NE;
  1402. return 3;
  1403. case AsmToken::Less:
  1404. Kind = MCBinaryExpr::LT;
  1405. return 3;
  1406. case AsmToken::LessEqual:
  1407. Kind = MCBinaryExpr::LTE;
  1408. return 3;
  1409. case AsmToken::Greater:
  1410. Kind = MCBinaryExpr::GT;
  1411. return 3;
  1412. case AsmToken::GreaterEqual:
  1413. Kind = MCBinaryExpr::GTE;
  1414. return 3;
  1415. // Intermediate Precedence: <<, >>
  1416. case AsmToken::LessLess:
  1417. Kind = MCBinaryExpr::Shl;
  1418. return 4;
  1419. case AsmToken::GreaterGreater:
  1420. Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
  1421. return 4;
  1422. // High Intermediate Precedence: +, -
  1423. case AsmToken::Plus:
  1424. Kind = MCBinaryExpr::Add;
  1425. return 5;
  1426. case AsmToken::Minus:
  1427. Kind = MCBinaryExpr::Sub;
  1428. return 5;
  1429. // Highest Precedence: *, /, %
  1430. case AsmToken::Star:
  1431. Kind = MCBinaryExpr::Mul;
  1432. return 6;
  1433. case AsmToken::Slash:
  1434. Kind = MCBinaryExpr::Div;
  1435. return 6;
  1436. case AsmToken::Percent:
  1437. Kind = MCBinaryExpr::Mod;
  1438. return 6;
  1439. }
  1440. }
  1441. static unsigned getGNUBinOpPrecedence(const MCAsmInfo &MAI,
  1442. AsmToken::TokenKind K,
  1443. MCBinaryExpr::Opcode &Kind,
  1444. bool ShouldUseLogicalShr) {
  1445. switch (K) {
  1446. default:
  1447. return 0; // not a binop.
  1448. // Lowest Precedence: &&, ||
  1449. case AsmToken::AmpAmp:
  1450. Kind = MCBinaryExpr::LAnd;
  1451. return 2;
  1452. case AsmToken::PipePipe:
  1453. Kind = MCBinaryExpr::LOr;
  1454. return 1;
  1455. // Low Precedence: ==, !=, <>, <, <=, >, >=
  1456. case AsmToken::EqualEqual:
  1457. Kind = MCBinaryExpr::EQ;
  1458. return 3;
  1459. case AsmToken::ExclaimEqual:
  1460. case AsmToken::LessGreater:
  1461. Kind = MCBinaryExpr::NE;
  1462. return 3;
  1463. case AsmToken::Less:
  1464. Kind = MCBinaryExpr::LT;
  1465. return 3;
  1466. case AsmToken::LessEqual:
  1467. Kind = MCBinaryExpr::LTE;
  1468. return 3;
  1469. case AsmToken::Greater:
  1470. Kind = MCBinaryExpr::GT;
  1471. return 3;
  1472. case AsmToken::GreaterEqual:
  1473. Kind = MCBinaryExpr::GTE;
  1474. return 3;
  1475. // Low Intermediate Precedence: +, -
  1476. case AsmToken::Plus:
  1477. Kind = MCBinaryExpr::Add;
  1478. return 4;
  1479. case AsmToken::Minus:
  1480. Kind = MCBinaryExpr::Sub;
  1481. return 4;
  1482. // High Intermediate Precedence: |, !, &, ^
  1483. //
  1484. case AsmToken::Pipe:
  1485. Kind = MCBinaryExpr::Or;
  1486. return 5;
  1487. case AsmToken::Exclaim:
  1488. // Hack to support ARM compatible aliases (implied 'sp' operand in 'srs*'
  1489. // instructions like 'srsda #31!') and not parse ! as an infix operator.
  1490. if (MAI.getCommentString() == "@")
  1491. return 0;
  1492. Kind = MCBinaryExpr::OrNot;
  1493. return 5;
  1494. case AsmToken::Caret:
  1495. Kind = MCBinaryExpr::Xor;
  1496. return 5;
  1497. case AsmToken::Amp:
  1498. Kind = MCBinaryExpr::And;
  1499. return 5;
  1500. // Highest Precedence: *, /, %, <<, >>
  1501. case AsmToken::Star:
  1502. Kind = MCBinaryExpr::Mul;
  1503. return 6;
  1504. case AsmToken::Slash:
  1505. Kind = MCBinaryExpr::Div;
  1506. return 6;
  1507. case AsmToken::Percent:
  1508. Kind = MCBinaryExpr::Mod;
  1509. return 6;
  1510. case AsmToken::LessLess:
  1511. Kind = MCBinaryExpr::Shl;
  1512. return 6;
  1513. case AsmToken::GreaterGreater:
  1514. Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
  1515. return 6;
  1516. }
  1517. }
  1518. unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
  1519. MCBinaryExpr::Opcode &Kind) {
  1520. bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
  1521. return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
  1522. : getGNUBinOpPrecedence(MAI, K, Kind, ShouldUseLogicalShr);
  1523. }
  1524. /// Parse all binary operators with precedence >= 'Precedence'.
  1525. /// Res contains the LHS of the expression on input.
  1526. bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
  1527. SMLoc &EndLoc) {
  1528. SMLoc StartLoc = Lexer.getLoc();
  1529. while (true) {
  1530. MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
  1531. unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
  1532. // If the next token is lower precedence than we are allowed to eat, return
  1533. // successfully with what we ate already.
  1534. if (TokPrec < Precedence)
  1535. return false;
  1536. Lex();
  1537. // Eat the next primary expression.
  1538. const MCExpr *RHS;
  1539. if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
  1540. return true;
  1541. // If BinOp binds less tightly with RHS than the operator after RHS, let
  1542. // the pending operator take RHS as its LHS.
  1543. MCBinaryExpr::Opcode Dummy;
  1544. unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
  1545. if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
  1546. return true;
  1547. // Merge LHS and RHS according to operator.
  1548. Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
  1549. }
  1550. }
  1551. /// ParseStatement:
  1552. /// ::= EndOfStatement
  1553. /// ::= Label* Directive ...Operands... EndOfStatement
  1554. /// ::= Label* Identifier OperandList* EndOfStatement
  1555. bool AsmParser::parseStatement(ParseStatementInfo &Info,
  1556. MCAsmParserSemaCallback *SI) {
  1557. assert(!hasPendingError() && "parseStatement started with pending error");
  1558. // Eat initial spaces and comments
  1559. while (Lexer.is(AsmToken::Space))
  1560. Lex();
  1561. if (Lexer.is(AsmToken::EndOfStatement)) {
  1562. // if this is a line comment we can drop it safely
  1563. if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
  1564. getTok().getString().front() == '\n')
  1565. Out.addBlankLine();
  1566. Lex();
  1567. return false;
  1568. }
  1569. // Statements always start with an identifier.
  1570. AsmToken ID = getTok();
  1571. SMLoc IDLoc = ID.getLoc();
  1572. StringRef IDVal;
  1573. int64_t LocalLabelVal = -1;
  1574. StartTokLoc = ID.getLoc();
  1575. if (Lexer.is(AsmToken::HashDirective))
  1576. return parseCppHashLineFilenameComment(IDLoc,
  1577. !isInsideMacroInstantiation());
  1578. // Allow an integer followed by a ':' as a directional local label.
  1579. if (Lexer.is(AsmToken::Integer)) {
  1580. LocalLabelVal = getTok().getIntVal();
  1581. if (LocalLabelVal < 0) {
  1582. if (!TheCondState.Ignore) {
  1583. Lex(); // always eat a token
  1584. return Error(IDLoc, "unexpected token at start of statement");
  1585. }
  1586. IDVal = "";
  1587. } else {
  1588. IDVal = getTok().getString();
  1589. Lex(); // Consume the integer token to be used as an identifier token.
  1590. if (Lexer.getKind() != AsmToken::Colon) {
  1591. if (!TheCondState.Ignore) {
  1592. Lex(); // always eat a token
  1593. return Error(IDLoc, "unexpected token at start of statement");
  1594. }
  1595. }
  1596. }
  1597. } else if (Lexer.is(AsmToken::Dot)) {
  1598. // Treat '.' as a valid identifier in this context.
  1599. Lex();
  1600. IDVal = ".";
  1601. } else if (Lexer.is(AsmToken::LCurly)) {
  1602. // Treat '{' as a valid identifier in this context.
  1603. Lex();
  1604. IDVal = "{";
  1605. } else if (Lexer.is(AsmToken::RCurly)) {
  1606. // Treat '}' as a valid identifier in this context.
  1607. Lex();
  1608. IDVal = "}";
  1609. } else if (Lexer.is(AsmToken::Star) &&
  1610. getTargetParser().starIsStartOfStatement()) {
  1611. // Accept '*' as a valid start of statement.
  1612. Lex();
  1613. IDVal = "*";
  1614. } else if (parseIdentifier(IDVal)) {
  1615. if (!TheCondState.Ignore) {
  1616. Lex(); // always eat a token
  1617. return Error(IDLoc, "unexpected token at start of statement");
  1618. }
  1619. IDVal = "";
  1620. }
  1621. // Handle conditional assembly here before checking for skipping. We
  1622. // have to do this so that .endif isn't skipped in a ".if 0" block for
  1623. // example.
  1624. StringMap<DirectiveKind>::const_iterator DirKindIt =
  1625. DirectiveKindMap.find(IDVal.lower());
  1626. DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
  1627. ? DK_NO_DIRECTIVE
  1628. : DirKindIt->getValue();
  1629. switch (DirKind) {
  1630. default:
  1631. break;
  1632. case DK_IF:
  1633. case DK_IFEQ:
  1634. case DK_IFGE:
  1635. case DK_IFGT:
  1636. case DK_IFLE:
  1637. case DK_IFLT:
  1638. case DK_IFNE:
  1639. return parseDirectiveIf(IDLoc, DirKind);
  1640. case DK_IFB:
  1641. return parseDirectiveIfb(IDLoc, true);
  1642. case DK_IFNB:
  1643. return parseDirectiveIfb(IDLoc, false);
  1644. case DK_IFC:
  1645. return parseDirectiveIfc(IDLoc, true);
  1646. case DK_IFEQS:
  1647. return parseDirectiveIfeqs(IDLoc, true);
  1648. case DK_IFNC:
  1649. return parseDirectiveIfc(IDLoc, false);
  1650. case DK_IFNES:
  1651. return parseDirectiveIfeqs(IDLoc, false);
  1652. case DK_IFDEF:
  1653. return parseDirectiveIfdef(IDLoc, true);
  1654. case DK_IFNDEF:
  1655. case DK_IFNOTDEF:
  1656. return parseDirectiveIfdef(IDLoc, false);
  1657. case DK_ELSEIF:
  1658. return parseDirectiveElseIf(IDLoc);
  1659. case DK_ELSE:
  1660. return parseDirectiveElse(IDLoc);
  1661. case DK_ENDIF:
  1662. return parseDirectiveEndIf(IDLoc);
  1663. }
  1664. // Ignore the statement if in the middle of inactive conditional
  1665. // (e.g. ".if 0").
  1666. if (TheCondState.Ignore) {
  1667. eatToEndOfStatement();
  1668. return false;
  1669. }
  1670. // FIXME: Recurse on local labels?
  1671. // Check for a label.
  1672. // ::= identifier ':'
  1673. // ::= number ':'
  1674. if (Lexer.is(AsmToken::Colon) && getTargetParser().isLabel(ID)) {
  1675. if (checkForValidSection())
  1676. return true;
  1677. Lex(); // Consume the ':'.
  1678. // Diagnose attempt to use '.' as a label.
  1679. if (IDVal == ".")
  1680. return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
  1681. // Diagnose attempt to use a variable as a label.
  1682. //
  1683. // FIXME: Diagnostics. Note the location of the definition as a label.
  1684. // FIXME: This doesn't diagnose assignment to a symbol which has been
  1685. // implicitly marked as external.
  1686. MCSymbol *Sym;
  1687. if (LocalLabelVal == -1) {
  1688. if (ParsingMSInlineAsm && SI) {
  1689. StringRef RewrittenLabel =
  1690. SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
  1691. assert(!RewrittenLabel.empty() &&
  1692. "We should have an internal name here.");
  1693. Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
  1694. RewrittenLabel);
  1695. IDVal = RewrittenLabel;
  1696. }
  1697. Sym = getContext().getOrCreateSymbol(IDVal);
  1698. } else
  1699. Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
  1700. // End of Labels should be treated as end of line for lexing
  1701. // purposes but that information is not available to the Lexer who
  1702. // does not understand Labels. This may cause us to see a Hash
  1703. // here instead of a preprocessor line comment.
  1704. if (getTok().is(AsmToken::Hash)) {
  1705. StringRef CommentStr = parseStringToEndOfStatement();
  1706. Lexer.Lex();
  1707. Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
  1708. }
  1709. // Consume any end of statement token, if present, to avoid spurious
  1710. // addBlankLine calls().
  1711. if (getTok().is(AsmToken::EndOfStatement)) {
  1712. Lex();
  1713. }
  1714. if (discardLTOSymbol(IDVal))
  1715. return false;
  1716. getTargetParser().doBeforeLabelEmit(Sym, IDLoc);
  1717. // Emit the label.
  1718. if (!getTargetParser().isParsingMSInlineAsm())
  1719. Out.emitLabel(Sym, IDLoc);
  1720. // If we are generating dwarf for assembly source files then gather the
  1721. // info to make a dwarf label entry for this label if needed.
  1722. if (enabledGenDwarfForAssembly())
  1723. MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
  1724. IDLoc);
  1725. getTargetParser().onLabelParsed(Sym);
  1726. return false;
  1727. }
  1728. // Check for an assignment statement.
  1729. // ::= identifier '='
  1730. if (Lexer.is(AsmToken::Equal) && getTargetParser().equalIsAsmAssignment()) {
  1731. Lex();
  1732. return parseAssignment(IDVal, AssignmentKind::Equal);
  1733. }
  1734. // If macros are enabled, check to see if this is a macro instantiation.
  1735. if (areMacrosEnabled())
  1736. if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
  1737. return handleMacroEntry(M, IDLoc);
  1738. }
  1739. // Otherwise, we have a normal instruction or directive.
  1740. // Directives start with "."
  1741. if (IDVal.startswith(".") && IDVal != ".") {
  1742. // There are several entities interested in parsing directives:
  1743. //
  1744. // 1. The target-specific assembly parser. Some directives are target
  1745. // specific or may potentially behave differently on certain targets.
  1746. // 2. Asm parser extensions. For example, platform-specific parsers
  1747. // (like the ELF parser) register themselves as extensions.
  1748. // 3. The generic directive parser implemented by this class. These are
  1749. // all the directives that behave in a target and platform independent
  1750. // manner, or at least have a default behavior that's shared between
  1751. // all targets and platforms.
  1752. getTargetParser().flushPendingInstructions(getStreamer());
  1753. SMLoc StartTokLoc = getTok().getLoc();
  1754. bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
  1755. if (hasPendingError())
  1756. return true;
  1757. // Currently the return value should be true if we are
  1758. // uninterested but as this is at odds with the standard parsing
  1759. // convention (return true = error) we have instances of a parsed
  1760. // directive that fails returning true as an error. Catch these
  1761. // cases as best as possible errors here.
  1762. if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
  1763. return true;
  1764. // Return if we did some parsing or believe we succeeded.
  1765. if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
  1766. return false;
  1767. // Next, check the extension directive map to see if any extension has
  1768. // registered itself to parse this directive.
  1769. std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
  1770. ExtensionDirectiveMap.lookup(IDVal);
  1771. if (Handler.first)
  1772. return (*Handler.second)(Handler.first, IDVal, IDLoc);
  1773. // Finally, if no one else is interested in this directive, it must be
  1774. // generic and familiar to this class.
  1775. switch (DirKind) {
  1776. default:
  1777. break;
  1778. case DK_SET:
  1779. case DK_EQU:
  1780. return parseDirectiveSet(IDVal, AssignmentKind::Set);
  1781. case DK_EQUIV:
  1782. return parseDirectiveSet(IDVal, AssignmentKind::Equiv);
  1783. case DK_LTO_SET_CONDITIONAL:
  1784. return parseDirectiveSet(IDVal, AssignmentKind::LTOSetConditional);
  1785. case DK_ASCII:
  1786. return parseDirectiveAscii(IDVal, false);
  1787. case DK_ASCIZ:
  1788. case DK_STRING:
  1789. return parseDirectiveAscii(IDVal, true);
  1790. case DK_BYTE:
  1791. case DK_DC_B:
  1792. return parseDirectiveValue(IDVal, 1);
  1793. case DK_DC:
  1794. case DK_DC_W:
  1795. case DK_SHORT:
  1796. case DK_VALUE:
  1797. case DK_2BYTE:
  1798. return parseDirectiveValue(IDVal, 2);
  1799. case DK_LONG:
  1800. case DK_INT:
  1801. case DK_4BYTE:
  1802. case DK_DC_L:
  1803. return parseDirectiveValue(IDVal, 4);
  1804. case DK_QUAD:
  1805. case DK_8BYTE:
  1806. return parseDirectiveValue(IDVal, 8);
  1807. case DK_DC_A:
  1808. return parseDirectiveValue(
  1809. IDVal, getContext().getAsmInfo()->getCodePointerSize());
  1810. case DK_OCTA:
  1811. return parseDirectiveOctaValue(IDVal);
  1812. case DK_SINGLE:
  1813. case DK_FLOAT:
  1814. case DK_DC_S:
  1815. return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
  1816. case DK_DOUBLE:
  1817. case DK_DC_D:
  1818. return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
  1819. case DK_ALIGN: {
  1820. bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
  1821. return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
  1822. }
  1823. case DK_ALIGN32: {
  1824. bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
  1825. return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
  1826. }
  1827. case DK_BALIGN:
  1828. return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
  1829. case DK_BALIGNW:
  1830. return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
  1831. case DK_BALIGNL:
  1832. return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
  1833. case DK_P2ALIGN:
  1834. return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
  1835. case DK_P2ALIGNW:
  1836. return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
  1837. case DK_P2ALIGNL:
  1838. return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
  1839. case DK_ORG:
  1840. return parseDirectiveOrg();
  1841. case DK_FILL:
  1842. return parseDirectiveFill();
  1843. case DK_ZERO:
  1844. return parseDirectiveZero();
  1845. case DK_EXTERN:
  1846. eatToEndOfStatement(); // .extern is the default, ignore it.
  1847. return false;
  1848. case DK_GLOBL:
  1849. case DK_GLOBAL:
  1850. return parseDirectiveSymbolAttribute(MCSA_Global);
  1851. case DK_LAZY_REFERENCE:
  1852. return parseDirectiveSymbolAttribute(MCSA_LazyReference);
  1853. case DK_NO_DEAD_STRIP:
  1854. return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
  1855. case DK_SYMBOL_RESOLVER:
  1856. return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
  1857. case DK_PRIVATE_EXTERN:
  1858. return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
  1859. case DK_REFERENCE:
  1860. return parseDirectiveSymbolAttribute(MCSA_Reference);
  1861. case DK_WEAK_DEFINITION:
  1862. return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
  1863. case DK_WEAK_REFERENCE:
  1864. return parseDirectiveSymbolAttribute(MCSA_WeakReference);
  1865. case DK_WEAK_DEF_CAN_BE_HIDDEN:
  1866. return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
  1867. case DK_COLD:
  1868. return parseDirectiveSymbolAttribute(MCSA_Cold);
  1869. case DK_COMM:
  1870. case DK_COMMON:
  1871. return parseDirectiveComm(/*IsLocal=*/false);
  1872. case DK_LCOMM:
  1873. return parseDirectiveComm(/*IsLocal=*/true);
  1874. case DK_ABORT:
  1875. return parseDirectiveAbort();
  1876. case DK_INCLUDE:
  1877. return parseDirectiveInclude();
  1878. case DK_INCBIN:
  1879. return parseDirectiveIncbin();
  1880. case DK_CODE16:
  1881. case DK_CODE16GCC:
  1882. return TokError(Twine(IDVal) +
  1883. " not currently supported for this target");
  1884. case DK_REPT:
  1885. return parseDirectiveRept(IDLoc, IDVal);
  1886. case DK_IRP:
  1887. return parseDirectiveIrp(IDLoc);
  1888. case DK_IRPC:
  1889. return parseDirectiveIrpc(IDLoc);
  1890. case DK_ENDR:
  1891. return parseDirectiveEndr(IDLoc);
  1892. case DK_BUNDLE_ALIGN_MODE:
  1893. return parseDirectiveBundleAlignMode();
  1894. case DK_BUNDLE_LOCK:
  1895. return parseDirectiveBundleLock();
  1896. case DK_BUNDLE_UNLOCK:
  1897. return parseDirectiveBundleUnlock();
  1898. case DK_SLEB128:
  1899. return parseDirectiveLEB128(true);
  1900. case DK_ULEB128:
  1901. return parseDirectiveLEB128(false);
  1902. case DK_SPACE:
  1903. case DK_SKIP:
  1904. return parseDirectiveSpace(IDVal);
  1905. case DK_FILE:
  1906. return parseDirectiveFile(IDLoc);
  1907. case DK_LINE:
  1908. return parseDirectiveLine();
  1909. case DK_LOC:
  1910. return parseDirectiveLoc();
  1911. case DK_STABS:
  1912. return parseDirectiveStabs();
  1913. case DK_CV_FILE:
  1914. return parseDirectiveCVFile();
  1915. case DK_CV_FUNC_ID:
  1916. return parseDirectiveCVFuncId();
  1917. case DK_CV_INLINE_SITE_ID:
  1918. return parseDirectiveCVInlineSiteId();
  1919. case DK_CV_LOC:
  1920. return parseDirectiveCVLoc();
  1921. case DK_CV_LINETABLE:
  1922. return parseDirectiveCVLinetable();
  1923. case DK_CV_INLINE_LINETABLE:
  1924. return parseDirectiveCVInlineLinetable();
  1925. case DK_CV_DEF_RANGE:
  1926. return parseDirectiveCVDefRange();
  1927. case DK_CV_STRING:
  1928. return parseDirectiveCVString();
  1929. case DK_CV_STRINGTABLE:
  1930. return parseDirectiveCVStringTable();
  1931. case DK_CV_FILECHECKSUMS:
  1932. return parseDirectiveCVFileChecksums();
  1933. case DK_CV_FILECHECKSUM_OFFSET:
  1934. return parseDirectiveCVFileChecksumOffset();
  1935. case DK_CV_FPO_DATA:
  1936. return parseDirectiveCVFPOData();
  1937. case DK_CFI_SECTIONS:
  1938. return parseDirectiveCFISections();
  1939. case DK_CFI_STARTPROC:
  1940. return parseDirectiveCFIStartProc();
  1941. case DK_CFI_ENDPROC:
  1942. return parseDirectiveCFIEndProc();
  1943. case DK_CFI_DEF_CFA:
  1944. return parseDirectiveCFIDefCfa(IDLoc);
  1945. case DK_CFI_DEF_CFA_OFFSET:
  1946. return parseDirectiveCFIDefCfaOffset();
  1947. case DK_CFI_ADJUST_CFA_OFFSET:
  1948. return parseDirectiveCFIAdjustCfaOffset();
  1949. case DK_CFI_DEF_CFA_REGISTER:
  1950. return parseDirectiveCFIDefCfaRegister(IDLoc);
  1951. case DK_CFI_LLVM_DEF_ASPACE_CFA:
  1952. return parseDirectiveCFILLVMDefAspaceCfa(IDLoc);
  1953. case DK_CFI_OFFSET:
  1954. return parseDirectiveCFIOffset(IDLoc);
  1955. case DK_CFI_REL_OFFSET:
  1956. return parseDirectiveCFIRelOffset(IDLoc);
  1957. case DK_CFI_PERSONALITY:
  1958. return parseDirectiveCFIPersonalityOrLsda(true);
  1959. case DK_CFI_LSDA:
  1960. return parseDirectiveCFIPersonalityOrLsda(false);
  1961. case DK_CFI_REMEMBER_STATE:
  1962. return parseDirectiveCFIRememberState();
  1963. case DK_CFI_RESTORE_STATE:
  1964. return parseDirectiveCFIRestoreState();
  1965. case DK_CFI_SAME_VALUE:
  1966. return parseDirectiveCFISameValue(IDLoc);
  1967. case DK_CFI_RESTORE:
  1968. return parseDirectiveCFIRestore(IDLoc);
  1969. case DK_CFI_ESCAPE:
  1970. return parseDirectiveCFIEscape();
  1971. case DK_CFI_RETURN_COLUMN:
  1972. return parseDirectiveCFIReturnColumn(IDLoc);
  1973. case DK_CFI_SIGNAL_FRAME:
  1974. return parseDirectiveCFISignalFrame();
  1975. case DK_CFI_UNDEFINED:
  1976. return parseDirectiveCFIUndefined(IDLoc);
  1977. case DK_CFI_REGISTER:
  1978. return parseDirectiveCFIRegister(IDLoc);
  1979. case DK_CFI_WINDOW_SAVE:
  1980. return parseDirectiveCFIWindowSave();
  1981. case DK_MACROS_ON:
  1982. case DK_MACROS_OFF:
  1983. return parseDirectiveMacrosOnOff(IDVal);
  1984. case DK_MACRO:
  1985. return parseDirectiveMacro(IDLoc);
  1986. case DK_ALTMACRO:
  1987. case DK_NOALTMACRO:
  1988. return parseDirectiveAltmacro(IDVal);
  1989. case DK_EXITM:
  1990. return parseDirectiveExitMacro(IDVal);
  1991. case DK_ENDM:
  1992. case DK_ENDMACRO:
  1993. return parseDirectiveEndMacro(IDVal);
  1994. case DK_PURGEM:
  1995. return parseDirectivePurgeMacro(IDLoc);
  1996. case DK_END:
  1997. return parseDirectiveEnd(IDLoc);
  1998. case DK_ERR:
  1999. return parseDirectiveError(IDLoc, false);
  2000. case DK_ERROR:
  2001. return parseDirectiveError(IDLoc, true);
  2002. case DK_WARNING:
  2003. return parseDirectiveWarning(IDLoc);
  2004. case DK_RELOC:
  2005. return parseDirectiveReloc(IDLoc);
  2006. case DK_DCB:
  2007. case DK_DCB_W:
  2008. return parseDirectiveDCB(IDVal, 2);
  2009. case DK_DCB_B:
  2010. return parseDirectiveDCB(IDVal, 1);
  2011. case DK_DCB_D:
  2012. return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
  2013. case DK_DCB_L:
  2014. return parseDirectiveDCB(IDVal, 4);
  2015. case DK_DCB_S:
  2016. return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
  2017. case DK_DC_X:
  2018. case DK_DCB_X:
  2019. return TokError(Twine(IDVal) +
  2020. " not currently supported for this target");
  2021. case DK_DS:
  2022. case DK_DS_W:
  2023. return parseDirectiveDS(IDVal, 2);
  2024. case DK_DS_B:
  2025. return parseDirectiveDS(IDVal, 1);
  2026. case DK_DS_D:
  2027. return parseDirectiveDS(IDVal, 8);
  2028. case DK_DS_L:
  2029. case DK_DS_S:
  2030. return parseDirectiveDS(IDVal, 4);
  2031. case DK_DS_P:
  2032. case DK_DS_X:
  2033. return parseDirectiveDS(IDVal, 12);
  2034. case DK_PRINT:
  2035. return parseDirectivePrint(IDLoc);
  2036. case DK_ADDRSIG:
  2037. return parseDirectiveAddrsig();
  2038. case DK_ADDRSIG_SYM:
  2039. return parseDirectiveAddrsigSym();
  2040. case DK_PSEUDO_PROBE:
  2041. return parseDirectivePseudoProbe();
  2042. case DK_LTO_DISCARD:
  2043. return parseDirectiveLTODiscard();
  2044. case DK_MEMTAG:
  2045. return parseDirectiveSymbolAttribute(MCSA_Memtag);
  2046. }
  2047. return Error(IDLoc, "unknown directive");
  2048. }
  2049. // __asm _emit or __asm __emit
  2050. if (ParsingMSInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
  2051. IDVal == "_EMIT" || IDVal == "__EMIT"))
  2052. return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
  2053. // __asm align
  2054. if (ParsingMSInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
  2055. return parseDirectiveMSAlign(IDLoc, Info);
  2056. if (ParsingMSInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
  2057. Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
  2058. if (checkForValidSection())
  2059. return true;
  2060. return parseAndMatchAndEmitTargetInstruction(Info, IDVal, ID, IDLoc);
  2061. }
  2062. bool AsmParser::parseAndMatchAndEmitTargetInstruction(ParseStatementInfo &Info,
  2063. StringRef IDVal,
  2064. AsmToken ID,
  2065. SMLoc IDLoc) {
  2066. // Canonicalize the opcode to lower case.
  2067. std::string OpcodeStr = IDVal.lower();
  2068. ParseInstructionInfo IInfo(Info.AsmRewrites);
  2069. bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
  2070. Info.ParsedOperands);
  2071. Info.ParseError = ParseHadError;
  2072. // Dump the parsed representation, if requested.
  2073. if (getShowParsedOperands()) {
  2074. SmallString<256> Str;
  2075. raw_svector_ostream OS(Str);
  2076. OS << "parsed instruction: [";
  2077. for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
  2078. if (i != 0)
  2079. OS << ", ";
  2080. Info.ParsedOperands[i]->print(OS);
  2081. }
  2082. OS << "]";
  2083. printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
  2084. }
  2085. // Fail even if ParseInstruction erroneously returns false.
  2086. if (hasPendingError() || ParseHadError)
  2087. return true;
  2088. // If we are generating dwarf for the current section then generate a .loc
  2089. // directive for the instruction.
  2090. if (!ParseHadError && enabledGenDwarfForAssembly() &&
  2091. getContext().getGenDwarfSectionSyms().count(
  2092. getStreamer().getCurrentSectionOnly())) {
  2093. unsigned Line;
  2094. if (ActiveMacros.empty())
  2095. Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
  2096. else
  2097. Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
  2098. ActiveMacros.front()->ExitBuffer);
  2099. // If we previously parsed a cpp hash file line comment then make sure the
  2100. // current Dwarf File is for the CppHashFilename if not then emit the
  2101. // Dwarf File table for it and adjust the line number for the .loc.
  2102. if (!CppHashInfo.Filename.empty()) {
  2103. unsigned FileNumber = getStreamer().emitDwarfFileDirective(
  2104. 0, StringRef(), CppHashInfo.Filename);
  2105. getContext().setGenDwarfFileNumber(FileNumber);
  2106. unsigned CppHashLocLineNo =
  2107. SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
  2108. Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
  2109. }
  2110. getStreamer().emitDwarfLocDirective(
  2111. getContext().getGenDwarfFileNumber(), Line, 0,
  2112. DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
  2113. StringRef());
  2114. }
  2115. // If parsing succeeded, match the instruction.
  2116. if (!ParseHadError) {
  2117. uint64_t ErrorInfo;
  2118. if (getTargetParser().MatchAndEmitInstruction(
  2119. IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
  2120. getTargetParser().isParsingMSInlineAsm()))
  2121. return true;
  2122. }
  2123. return false;
  2124. }
  2125. // Parse and erase curly braces marking block start/end
  2126. bool
  2127. AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
  2128. // Identify curly brace marking block start/end
  2129. if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
  2130. return false;
  2131. SMLoc StartLoc = Lexer.getLoc();
  2132. Lex(); // Eat the brace
  2133. if (Lexer.is(AsmToken::EndOfStatement))
  2134. Lex(); // Eat EndOfStatement following the brace
  2135. // Erase the block start/end brace from the output asm string
  2136. AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
  2137. StartLoc.getPointer());
  2138. return true;
  2139. }
  2140. /// parseCppHashLineFilenameComment as this:
  2141. /// ::= # number "filename"
  2142. bool AsmParser::parseCppHashLineFilenameComment(SMLoc L, bool SaveLocInfo) {
  2143. Lex(); // Eat the hash token.
  2144. // Lexer only ever emits HashDirective if it fully formed if it's
  2145. // done the checking already so this is an internal error.
  2146. assert(getTok().is(AsmToken::Integer) &&
  2147. "Lexing Cpp line comment: Expected Integer");
  2148. int64_t LineNumber = getTok().getIntVal();
  2149. Lex();
  2150. assert(getTok().is(AsmToken::String) &&
  2151. "Lexing Cpp line comment: Expected String");
  2152. StringRef Filename = getTok().getString();
  2153. Lex();
  2154. if (!SaveLocInfo)
  2155. return false;
  2156. // Get rid of the enclosing quotes.
  2157. Filename = Filename.substr(1, Filename.size() - 2);
  2158. // Save the SMLoc, Filename and LineNumber for later use by diagnostics
  2159. // and possibly DWARF file info.
  2160. CppHashInfo.Loc = L;
  2161. CppHashInfo.Filename = Filename;
  2162. CppHashInfo.LineNumber = LineNumber;
  2163. CppHashInfo.Buf = CurBuffer;
  2164. if (FirstCppHashFilename.empty())
  2165. FirstCppHashFilename = Filename;
  2166. return false;
  2167. }
  2168. /// will use the last parsed cpp hash line filename comment
  2169. /// for the Filename and LineNo if any in the diagnostic.
  2170. void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
  2171. auto *Parser = static_cast<AsmParser *>(Context);
  2172. raw_ostream &OS = errs();
  2173. const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
  2174. SMLoc DiagLoc = Diag.getLoc();
  2175. unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
  2176. unsigned CppHashBuf =
  2177. Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
  2178. // Like SourceMgr::printMessage() we need to print the include stack if any
  2179. // before printing the message.
  2180. unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
  2181. if (!Parser->SavedDiagHandler && DiagCurBuffer &&
  2182. DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
  2183. SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
  2184. DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
  2185. }
  2186. // If we have not parsed a cpp hash line filename comment or the source
  2187. // manager changed or buffer changed (like in a nested include) then just
  2188. // print the normal diagnostic using its Filename and LineNo.
  2189. if (!Parser->CppHashInfo.LineNumber || DiagBuf != CppHashBuf) {
  2190. if (Parser->SavedDiagHandler)
  2191. Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
  2192. else
  2193. Parser->getContext().diagnose(Diag);
  2194. return;
  2195. }
  2196. // Use the CppHashFilename and calculate a line number based on the
  2197. // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
  2198. // for the diagnostic.
  2199. const std::string &Filename = std::string(Parser->CppHashInfo.Filename);
  2200. int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
  2201. int CppHashLocLineNo =
  2202. Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
  2203. int LineNo =
  2204. Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
  2205. SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
  2206. Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
  2207. Diag.getLineContents(), Diag.getRanges());
  2208. if (Parser->SavedDiagHandler)
  2209. Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
  2210. else
  2211. Parser->getContext().diagnose(NewDiag);
  2212. }
  2213. // FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
  2214. // difference being that that function accepts '@' as part of identifiers and
  2215. // we can't do that. AsmLexer.cpp should probably be changed to handle
  2216. // '@' as a special case when needed.
  2217. static bool isIdentifierChar(char c) {
  2218. return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
  2219. c == '.';
  2220. }
  2221. bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
  2222. ArrayRef<MCAsmMacroParameter> Parameters,
  2223. ArrayRef<MCAsmMacroArgument> A,
  2224. bool EnableAtPseudoVariable, SMLoc L) {
  2225. unsigned NParameters = Parameters.size();
  2226. bool HasVararg = NParameters ? Parameters.back().Vararg : false;
  2227. if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
  2228. return Error(L, "Wrong number of arguments");
  2229. // A macro without parameters is handled differently on Darwin:
  2230. // gas accepts no arguments and does no substitutions
  2231. while (!Body.empty()) {
  2232. // Scan for the next substitution.
  2233. std::size_t End = Body.size(), Pos = 0;
  2234. for (; Pos != End; ++Pos) {
  2235. // Check for a substitution or escape.
  2236. if (IsDarwin && !NParameters) {
  2237. // This macro has no parameters, look for $0, $1, etc.
  2238. if (Body[Pos] != '$' || Pos + 1 == End)
  2239. continue;
  2240. char Next = Body[Pos + 1];
  2241. if (Next == '$' || Next == 'n' ||
  2242. isdigit(static_cast<unsigned char>(Next)))
  2243. break;
  2244. } else {
  2245. // This macro has parameters, look for \foo, \bar, etc.
  2246. if (Body[Pos] == '\\' && Pos + 1 != End)
  2247. break;
  2248. }
  2249. }
  2250. // Add the prefix.
  2251. OS << Body.slice(0, Pos);
  2252. // Check if we reached the end.
  2253. if (Pos == End)
  2254. break;
  2255. if (IsDarwin && !NParameters) {
  2256. switch (Body[Pos + 1]) {
  2257. // $$ => $
  2258. case '$':
  2259. OS << '$';
  2260. break;
  2261. // $n => number of arguments
  2262. case 'n':
  2263. OS << A.size();
  2264. break;
  2265. // $[0-9] => argument
  2266. default: {
  2267. // Missing arguments are ignored.
  2268. unsigned Index = Body[Pos + 1] - '0';
  2269. if (Index >= A.size())
  2270. break;
  2271. // Otherwise substitute with the token values, with spaces eliminated.
  2272. for (const AsmToken &Token : A[Index])
  2273. OS << Token.getString();
  2274. break;
  2275. }
  2276. }
  2277. Pos += 2;
  2278. } else {
  2279. unsigned I = Pos + 1;
  2280. // Check for the \@ pseudo-variable.
  2281. if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
  2282. ++I;
  2283. else
  2284. while (isIdentifierChar(Body[I]) && I + 1 != End)
  2285. ++I;
  2286. const char *Begin = Body.data() + Pos + 1;
  2287. StringRef Argument(Begin, I - (Pos + 1));
  2288. unsigned Index = 0;
  2289. if (Argument == "@") {
  2290. OS << NumOfMacroInstantiations;
  2291. Pos += 2;
  2292. } else {
  2293. for (; Index < NParameters; ++Index)
  2294. if (Parameters[Index].Name == Argument)
  2295. break;
  2296. if (Index == NParameters) {
  2297. if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
  2298. Pos += 3;
  2299. else {
  2300. OS << '\\' << Argument;
  2301. Pos = I;
  2302. }
  2303. } else {
  2304. bool VarargParameter = HasVararg && Index == (NParameters - 1);
  2305. for (const AsmToken &Token : A[Index])
  2306. // For altmacro mode, you can write '%expr'.
  2307. // The prefix '%' evaluates the expression 'expr'
  2308. // and uses the result as a string (e.g. replace %(1+2) with the
  2309. // string "3").
  2310. // Here, we identify the integer token which is the result of the
  2311. // absolute expression evaluation and replace it with its string
  2312. // representation.
  2313. if (AltMacroMode && Token.getString().front() == '%' &&
  2314. Token.is(AsmToken::Integer))
  2315. // Emit an integer value to the buffer.
  2316. OS << Token.getIntVal();
  2317. // Only Token that was validated as a string and begins with '<'
  2318. // is considered altMacroString!!!
  2319. else if (AltMacroMode && Token.getString().front() == '<' &&
  2320. Token.is(AsmToken::String)) {
  2321. OS << angleBracketString(Token.getStringContents());
  2322. }
  2323. // We expect no quotes around the string's contents when
  2324. // parsing for varargs.
  2325. else if (Token.isNot(AsmToken::String) || VarargParameter)
  2326. OS << Token.getString();
  2327. else
  2328. OS << Token.getStringContents();
  2329. Pos += 1 + Argument.size();
  2330. }
  2331. }
  2332. }
  2333. // Update the scan point.
  2334. Body = Body.substr(Pos);
  2335. }
  2336. return false;
  2337. }
  2338. static bool isOperator(AsmToken::TokenKind kind) {
  2339. switch (kind) {
  2340. default:
  2341. return false;
  2342. case AsmToken::Plus:
  2343. case AsmToken::Minus:
  2344. case AsmToken::Tilde:
  2345. case AsmToken::Slash:
  2346. case AsmToken::Star:
  2347. case AsmToken::Dot:
  2348. case AsmToken::Equal:
  2349. case AsmToken::EqualEqual:
  2350. case AsmToken::Pipe:
  2351. case AsmToken::PipePipe:
  2352. case AsmToken::Caret:
  2353. case AsmToken::Amp:
  2354. case AsmToken::AmpAmp:
  2355. case AsmToken::Exclaim:
  2356. case AsmToken::ExclaimEqual:
  2357. case AsmToken::Less:
  2358. case AsmToken::LessEqual:
  2359. case AsmToken::LessLess:
  2360. case AsmToken::LessGreater:
  2361. case AsmToken::Greater:
  2362. case AsmToken::GreaterEqual:
  2363. case AsmToken::GreaterGreater:
  2364. return true;
  2365. }
  2366. }
  2367. namespace {
  2368. class AsmLexerSkipSpaceRAII {
  2369. public:
  2370. AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
  2371. Lexer.setSkipSpace(SkipSpace);
  2372. }
  2373. ~AsmLexerSkipSpaceRAII() {
  2374. Lexer.setSkipSpace(true);
  2375. }
  2376. private:
  2377. AsmLexer &Lexer;
  2378. };
  2379. } // end anonymous namespace
  2380. bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
  2381. if (Vararg) {
  2382. if (Lexer.isNot(AsmToken::EndOfStatement)) {
  2383. StringRef Str = parseStringToEndOfStatement();
  2384. MA.emplace_back(AsmToken::String, Str);
  2385. }
  2386. return false;
  2387. }
  2388. unsigned ParenLevel = 0;
  2389. // Darwin doesn't use spaces to delmit arguments.
  2390. AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
  2391. bool SpaceEaten;
  2392. while (true) {
  2393. SpaceEaten = false;
  2394. if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
  2395. return TokError("unexpected token in macro instantiation");
  2396. if (ParenLevel == 0) {
  2397. if (Lexer.is(AsmToken::Comma))
  2398. break;
  2399. if (Lexer.is(AsmToken::Space)) {
  2400. SpaceEaten = true;
  2401. Lexer.Lex(); // Eat spaces
  2402. }
  2403. // Spaces can delimit parameters, but could also be part an expression.
  2404. // If the token after a space is an operator, add the token and the next
  2405. // one into this argument
  2406. if (!IsDarwin) {
  2407. if (isOperator(Lexer.getKind())) {
  2408. MA.push_back(getTok());
  2409. Lexer.Lex();
  2410. // Whitespace after an operator can be ignored.
  2411. if (Lexer.is(AsmToken::Space))
  2412. Lexer.Lex();
  2413. continue;
  2414. }
  2415. }
  2416. if (SpaceEaten)
  2417. break;
  2418. }
  2419. // handleMacroEntry relies on not advancing the lexer here
  2420. // to be able to fill in the remaining default parameter values
  2421. if (Lexer.is(AsmToken::EndOfStatement))
  2422. break;
  2423. // Adjust the current parentheses level.
  2424. if (Lexer.is(AsmToken::LParen))
  2425. ++ParenLevel;
  2426. else if (Lexer.is(AsmToken::RParen) && ParenLevel)
  2427. --ParenLevel;
  2428. // Append the token to the current argument list.
  2429. MA.push_back(getTok());
  2430. Lexer.Lex();
  2431. }
  2432. if (ParenLevel != 0)
  2433. return TokError("unbalanced parentheses in macro argument");
  2434. return false;
  2435. }
  2436. // Parse the macro instantiation arguments.
  2437. bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
  2438. MCAsmMacroArguments &A) {
  2439. const unsigned NParameters = M ? M->Parameters.size() : 0;
  2440. bool NamedParametersFound = false;
  2441. SmallVector<SMLoc, 4> FALocs;
  2442. A.resize(NParameters);
  2443. FALocs.resize(NParameters);
  2444. // Parse two kinds of macro invocations:
  2445. // - macros defined without any parameters accept an arbitrary number of them
  2446. // - macros defined with parameters accept at most that many of them
  2447. bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
  2448. for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
  2449. ++Parameter) {
  2450. SMLoc IDLoc = Lexer.getLoc();
  2451. MCAsmMacroParameter FA;
  2452. if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
  2453. if (parseIdentifier(FA.Name))
  2454. return Error(IDLoc, "invalid argument identifier for formal argument");
  2455. if (Lexer.isNot(AsmToken::Equal))
  2456. return TokError("expected '=' after formal parameter identifier");
  2457. Lex();
  2458. NamedParametersFound = true;
  2459. }
  2460. bool Vararg = HasVararg && Parameter == (NParameters - 1);
  2461. if (NamedParametersFound && FA.Name.empty())
  2462. return Error(IDLoc, "cannot mix positional and keyword arguments");
  2463. SMLoc StrLoc = Lexer.getLoc();
  2464. SMLoc EndLoc;
  2465. if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
  2466. const MCExpr *AbsoluteExp;
  2467. int64_t Value;
  2468. /// Eat '%'
  2469. Lex();
  2470. if (parseExpression(AbsoluteExp, EndLoc))
  2471. return false;
  2472. if (!AbsoluteExp->evaluateAsAbsolute(Value,
  2473. getStreamer().getAssemblerPtr()))
  2474. return Error(StrLoc, "expected absolute expression");
  2475. const char *StrChar = StrLoc.getPointer();
  2476. const char *EndChar = EndLoc.getPointer();
  2477. AsmToken newToken(AsmToken::Integer,
  2478. StringRef(StrChar, EndChar - StrChar), Value);
  2479. FA.Value.push_back(newToken);
  2480. } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
  2481. isAngleBracketString(StrLoc, EndLoc)) {
  2482. const char *StrChar = StrLoc.getPointer();
  2483. const char *EndChar = EndLoc.getPointer();
  2484. jumpToLoc(EndLoc, CurBuffer);
  2485. /// Eat from '<' to '>'
  2486. Lex();
  2487. AsmToken newToken(AsmToken::String,
  2488. StringRef(StrChar, EndChar - StrChar));
  2489. FA.Value.push_back(newToken);
  2490. } else if(parseMacroArgument(FA.Value, Vararg))
  2491. return true;
  2492. unsigned PI = Parameter;
  2493. if (!FA.Name.empty()) {
  2494. unsigned FAI = 0;
  2495. for (FAI = 0; FAI < NParameters; ++FAI)
  2496. if (M->Parameters[FAI].Name == FA.Name)
  2497. break;
  2498. if (FAI >= NParameters) {
  2499. assert(M && "expected macro to be defined");
  2500. return Error(IDLoc, "parameter named '" + FA.Name +
  2501. "' does not exist for macro '" + M->Name + "'");
  2502. }
  2503. PI = FAI;
  2504. }
  2505. if (!FA.Value.empty()) {
  2506. if (A.size() <= PI)
  2507. A.resize(PI + 1);
  2508. A[PI] = FA.Value;
  2509. if (FALocs.size() <= PI)
  2510. FALocs.resize(PI + 1);
  2511. FALocs[PI] = Lexer.getLoc();
  2512. }
  2513. // At the end of the statement, fill in remaining arguments that have
  2514. // default values. If there aren't any, then the next argument is
  2515. // required but missing
  2516. if (Lexer.is(AsmToken::EndOfStatement)) {
  2517. bool Failure = false;
  2518. for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
  2519. if (A[FAI].empty()) {
  2520. if (M->Parameters[FAI].Required) {
  2521. Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
  2522. "missing value for required parameter "
  2523. "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
  2524. Failure = true;
  2525. }
  2526. if (!M->Parameters[FAI].Value.empty())
  2527. A[FAI] = M->Parameters[FAI].Value;
  2528. }
  2529. }
  2530. return Failure;
  2531. }
  2532. if (Lexer.is(AsmToken::Comma))
  2533. Lex();
  2534. }
  2535. return TokError("too many positional arguments");
  2536. }
  2537. bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
  2538. // Arbitrarily limit macro nesting depth (default matches 'as'). We can
  2539. // eliminate this, although we should protect against infinite loops.
  2540. unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
  2541. if (ActiveMacros.size() == MaxNestingDepth) {
  2542. std::ostringstream MaxNestingDepthError;
  2543. MaxNestingDepthError << "macros cannot be nested more than "
  2544. << MaxNestingDepth << " levels deep."
  2545. << " Use -asm-macro-max-nesting-depth to increase "
  2546. "this limit.";
  2547. return TokError(MaxNestingDepthError.str());
  2548. }
  2549. MCAsmMacroArguments A;
  2550. if (parseMacroArguments(M, A))
  2551. return true;
  2552. // Macro instantiation is lexical, unfortunately. We construct a new buffer
  2553. // to hold the macro body with substitutions.
  2554. SmallString<256> Buf;
  2555. StringRef Body = M->Body;
  2556. raw_svector_ostream OS(Buf);
  2557. if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
  2558. return true;
  2559. // We include the .endmacro in the buffer as our cue to exit the macro
  2560. // instantiation.
  2561. OS << ".endmacro\n";
  2562. std::unique_ptr<MemoryBuffer> Instantiation =
  2563. MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
  2564. // Create the macro instantiation object and add to the current macro
  2565. // instantiation stack.
  2566. MacroInstantiation *MI = new MacroInstantiation{
  2567. NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
  2568. ActiveMacros.push_back(MI);
  2569. ++NumOfMacroInstantiations;
  2570. // Jump to the macro instantiation and prime the lexer.
  2571. CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
  2572. Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
  2573. Lex();
  2574. return false;
  2575. }
  2576. void AsmParser::handleMacroExit() {
  2577. // Jump to the EndOfStatement we should return to, and consume it.
  2578. jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
  2579. Lex();
  2580. // Pop the instantiation entry.
  2581. delete ActiveMacros.back();
  2582. ActiveMacros.pop_back();
  2583. }
  2584. bool AsmParser::parseAssignment(StringRef Name, AssignmentKind Kind) {
  2585. MCSymbol *Sym;
  2586. const MCExpr *Value;
  2587. SMLoc ExprLoc = getTok().getLoc();
  2588. bool AllowRedef =
  2589. Kind == AssignmentKind::Set || Kind == AssignmentKind::Equal;
  2590. if (MCParserUtils::parseAssignmentExpression(Name, AllowRedef, *this, Sym,
  2591. Value))
  2592. return true;
  2593. if (!Sym) {
  2594. // In the case where we parse an expression starting with a '.', we will
  2595. // not generate an error, nor will we create a symbol. In this case we
  2596. // should just return out.
  2597. return false;
  2598. }
  2599. if (discardLTOSymbol(Name))
  2600. return false;
  2601. // Do the assignment.
  2602. switch (Kind) {
  2603. case AssignmentKind::Equal:
  2604. Out.emitAssignment(Sym, Value);
  2605. break;
  2606. case AssignmentKind::Set:
  2607. case AssignmentKind::Equiv:
  2608. Out.emitAssignment(Sym, Value);
  2609. Out.emitSymbolAttribute(Sym, MCSA_NoDeadStrip);
  2610. break;
  2611. case AssignmentKind::LTOSetConditional:
  2612. if (Value->getKind() != MCExpr::SymbolRef)
  2613. return Error(ExprLoc, "expected identifier");
  2614. Out.emitConditionalAssignment(Sym, Value);
  2615. break;
  2616. }
  2617. return false;
  2618. }
  2619. /// parseIdentifier:
  2620. /// ::= identifier
  2621. /// ::= string
  2622. bool AsmParser::parseIdentifier(StringRef &Res) {
  2623. // The assembler has relaxed rules for accepting identifiers, in particular we
  2624. // allow things like '.globl $foo' and '.def @feat.00', which would normally be
  2625. // separate tokens. At this level, we have already lexed so we cannot (currently)
  2626. // handle this as a context dependent token, instead we detect adjacent tokens
  2627. // and return the combined identifier.
  2628. if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
  2629. SMLoc PrefixLoc = getLexer().getLoc();
  2630. // Consume the prefix character, and check for a following identifier.
  2631. AsmToken Buf[1];
  2632. Lexer.peekTokens(Buf, false);
  2633. if (Buf[0].isNot(AsmToken::Identifier) && Buf[0].isNot(AsmToken::Integer))
  2634. return true;
  2635. // We have a '$' or '@' followed by an identifier or integer token, make
  2636. // sure they are adjacent.
  2637. if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
  2638. return true;
  2639. // eat $ or @
  2640. Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
  2641. // Construct the joined identifier and consume the token.
  2642. Res = StringRef(PrefixLoc.getPointer(), getTok().getString().size() + 1);
  2643. Lex(); // Parser Lex to maintain invariants.
  2644. return false;
  2645. }
  2646. if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
  2647. return true;
  2648. Res = getTok().getIdentifier();
  2649. Lex(); // Consume the identifier token.
  2650. return false;
  2651. }
  2652. /// parseDirectiveSet:
  2653. /// ::= .equ identifier ',' expression
  2654. /// ::= .equiv identifier ',' expression
  2655. /// ::= .set identifier ',' expression
  2656. /// ::= .lto_set_conditional identifier ',' expression
  2657. bool AsmParser::parseDirectiveSet(StringRef IDVal, AssignmentKind Kind) {
  2658. StringRef Name;
  2659. if (check(parseIdentifier(Name), "expected identifier") || parseComma() ||
  2660. parseAssignment(Name, Kind))
  2661. return true;
  2662. return false;
  2663. }
  2664. bool AsmParser::parseEscapedString(std::string &Data) {
  2665. if (check(getTok().isNot(AsmToken::String), "expected string"))
  2666. return true;
  2667. Data = "";
  2668. StringRef Str = getTok().getStringContents();
  2669. for (unsigned i = 0, e = Str.size(); i != e; ++i) {
  2670. if (Str[i] != '\\') {
  2671. Data += Str[i];
  2672. continue;
  2673. }
  2674. // Recognize escaped characters. Note that this escape semantics currently
  2675. // loosely follows Darwin 'as'.
  2676. ++i;
  2677. if (i == e)
  2678. return TokError("unexpected backslash at end of string");
  2679. // Recognize hex sequences similarly to GNU 'as'.
  2680. if (Str[i] == 'x' || Str[i] == 'X') {
  2681. size_t length = Str.size();
  2682. if (i + 1 >= length || !isHexDigit(Str[i + 1]))
  2683. return TokError("invalid hexadecimal escape sequence");
  2684. // Consume hex characters. GNU 'as' reads all hexadecimal characters and
  2685. // then truncates to the lower 16 bits. Seems reasonable.
  2686. unsigned Value = 0;
  2687. while (i + 1 < length && isHexDigit(Str[i + 1]))
  2688. Value = Value * 16 + hexDigitValue(Str[++i]);
  2689. Data += (unsigned char)(Value & 0xFF);
  2690. continue;
  2691. }
  2692. // Recognize octal sequences.
  2693. if ((unsigned)(Str[i] - '0') <= 7) {
  2694. // Consume up to three octal characters.
  2695. unsigned Value = Str[i] - '0';
  2696. if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
  2697. ++i;
  2698. Value = Value * 8 + (Str[i] - '0');
  2699. if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
  2700. ++i;
  2701. Value = Value * 8 + (Str[i] - '0');
  2702. }
  2703. }
  2704. if (Value > 255)
  2705. return TokError("invalid octal escape sequence (out of range)");
  2706. Data += (unsigned char)Value;
  2707. continue;
  2708. }
  2709. // Otherwise recognize individual escapes.
  2710. switch (Str[i]) {
  2711. default:
  2712. // Just reject invalid escape sequences for now.
  2713. return TokError("invalid escape sequence (unrecognized character)");
  2714. case 'b': Data += '\b'; break;
  2715. case 'f': Data += '\f'; break;
  2716. case 'n': Data += '\n'; break;
  2717. case 'r': Data += '\r'; break;
  2718. case 't': Data += '\t'; break;
  2719. case '"': Data += '"'; break;
  2720. case '\\': Data += '\\'; break;
  2721. }
  2722. }
  2723. Lex();
  2724. return false;
  2725. }
  2726. bool AsmParser::parseAngleBracketString(std::string &Data) {
  2727. SMLoc EndLoc, StartLoc = getTok().getLoc();
  2728. if (isAngleBracketString(StartLoc, EndLoc)) {
  2729. const char *StartChar = StartLoc.getPointer() + 1;
  2730. const char *EndChar = EndLoc.getPointer() - 1;
  2731. jumpToLoc(EndLoc, CurBuffer);
  2732. /// Eat from '<' to '>'
  2733. Lex();
  2734. Data = angleBracketString(StringRef(StartChar, EndChar - StartChar));
  2735. return false;
  2736. }
  2737. return true;
  2738. }
  2739. /// parseDirectiveAscii:
  2740. // ::= .ascii [ "string"+ ( , "string"+ )* ]
  2741. /// ::= ( .asciz | .string ) [ "string" ( , "string" )* ]
  2742. bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
  2743. auto parseOp = [&]() -> bool {
  2744. std::string Data;
  2745. if (checkForValidSection())
  2746. return true;
  2747. // Only support spaces as separators for .ascii directive for now. See the
  2748. // discusssion at https://reviews.llvm.org/D91460 for more details.
  2749. do {
  2750. if (parseEscapedString(Data))
  2751. return true;
  2752. getStreamer().emitBytes(Data);
  2753. } while (!ZeroTerminated && getTok().is(AsmToken::String));
  2754. if (ZeroTerminated)
  2755. getStreamer().emitBytes(StringRef("\0", 1));
  2756. return false;
  2757. };
  2758. return parseMany(parseOp);
  2759. }
  2760. /// parseDirectiveReloc
  2761. /// ::= .reloc expression , identifier [ , expression ]
  2762. bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
  2763. const MCExpr *Offset;
  2764. const MCExpr *Expr = nullptr;
  2765. SMLoc OffsetLoc = Lexer.getTok().getLoc();
  2766. if (parseExpression(Offset))
  2767. return true;
  2768. if (parseComma() ||
  2769. check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
  2770. return true;
  2771. SMLoc NameLoc = Lexer.getTok().getLoc();
  2772. StringRef Name = Lexer.getTok().getIdentifier();
  2773. Lex();
  2774. if (Lexer.is(AsmToken::Comma)) {
  2775. Lex();
  2776. SMLoc ExprLoc = Lexer.getLoc();
  2777. if (parseExpression(Expr))
  2778. return true;
  2779. MCValue Value;
  2780. if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
  2781. return Error(ExprLoc, "expression must be relocatable");
  2782. }
  2783. if (parseEOL())
  2784. return true;
  2785. const MCTargetAsmParser &MCT = getTargetParser();
  2786. const MCSubtargetInfo &STI = MCT.getSTI();
  2787. if (std::optional<std::pair<bool, std::string>> Err =
  2788. getStreamer().emitRelocDirective(*Offset, Name, Expr, DirectiveLoc,
  2789. STI))
  2790. return Error(Err->first ? NameLoc : OffsetLoc, Err->second);
  2791. return false;
  2792. }
  2793. /// parseDirectiveValue
  2794. /// ::= (.byte | .short | ... ) [ expression (, expression)* ]
  2795. bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
  2796. auto parseOp = [&]() -> bool {
  2797. const MCExpr *Value;
  2798. SMLoc ExprLoc = getLexer().getLoc();
  2799. if (checkForValidSection() || parseExpression(Value))
  2800. return true;
  2801. // Special case constant expressions to match code generator.
  2802. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
  2803. assert(Size <= 8 && "Invalid size");
  2804. uint64_t IntValue = MCE->getValue();
  2805. if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
  2806. return Error(ExprLoc, "out of range literal value");
  2807. getStreamer().emitIntValue(IntValue, Size);
  2808. } else
  2809. getStreamer().emitValue(Value, Size, ExprLoc);
  2810. return false;
  2811. };
  2812. return parseMany(parseOp);
  2813. }
  2814. static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
  2815. if (Asm.getTok().isNot(AsmToken::Integer) &&
  2816. Asm.getTok().isNot(AsmToken::BigNum))
  2817. return Asm.TokError("unknown token in expression");
  2818. SMLoc ExprLoc = Asm.getTok().getLoc();
  2819. APInt IntValue = Asm.getTok().getAPIntVal();
  2820. Asm.Lex();
  2821. if (!IntValue.isIntN(128))
  2822. return Asm.Error(ExprLoc, "out of range literal value");
  2823. if (!IntValue.isIntN(64)) {
  2824. hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
  2825. lo = IntValue.getLoBits(64).getZExtValue();
  2826. } else {
  2827. hi = 0;
  2828. lo = IntValue.getZExtValue();
  2829. }
  2830. return false;
  2831. }
  2832. /// ParseDirectiveOctaValue
  2833. /// ::= .octa [ hexconstant (, hexconstant)* ]
  2834. bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
  2835. auto parseOp = [&]() -> bool {
  2836. if (checkForValidSection())
  2837. return true;
  2838. uint64_t hi, lo;
  2839. if (parseHexOcta(*this, hi, lo))
  2840. return true;
  2841. if (MAI.isLittleEndian()) {
  2842. getStreamer().emitInt64(lo);
  2843. getStreamer().emitInt64(hi);
  2844. } else {
  2845. getStreamer().emitInt64(hi);
  2846. getStreamer().emitInt64(lo);
  2847. }
  2848. return false;
  2849. };
  2850. return parseMany(parseOp);
  2851. }
  2852. bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
  2853. // We don't truly support arithmetic on floating point expressions, so we
  2854. // have to manually parse unary prefixes.
  2855. bool IsNeg = false;
  2856. if (getLexer().is(AsmToken::Minus)) {
  2857. Lexer.Lex();
  2858. IsNeg = true;
  2859. } else if (getLexer().is(AsmToken::Plus))
  2860. Lexer.Lex();
  2861. if (Lexer.is(AsmToken::Error))
  2862. return TokError(Lexer.getErr());
  2863. if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
  2864. Lexer.isNot(AsmToken::Identifier))
  2865. return TokError("unexpected token in directive");
  2866. // Convert to an APFloat.
  2867. APFloat Value(Semantics);
  2868. StringRef IDVal = getTok().getString();
  2869. if (getLexer().is(AsmToken::Identifier)) {
  2870. if (!IDVal.compare_insensitive("infinity") ||
  2871. !IDVal.compare_insensitive("inf"))
  2872. Value = APFloat::getInf(Semantics);
  2873. else if (!IDVal.compare_insensitive("nan"))
  2874. Value = APFloat::getNaN(Semantics, false, ~0);
  2875. else
  2876. return TokError("invalid floating point literal");
  2877. } else if (errorToBool(
  2878. Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven)
  2879. .takeError()))
  2880. return TokError("invalid floating point literal");
  2881. if (IsNeg)
  2882. Value.changeSign();
  2883. // Consume the numeric token.
  2884. Lex();
  2885. Res = Value.bitcastToAPInt();
  2886. return false;
  2887. }
  2888. /// parseDirectiveRealValue
  2889. /// ::= (.single | .double) [ expression (, expression)* ]
  2890. bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
  2891. const fltSemantics &Semantics) {
  2892. auto parseOp = [&]() -> bool {
  2893. APInt AsInt;
  2894. if (checkForValidSection() || parseRealValue(Semantics, AsInt))
  2895. return true;
  2896. getStreamer().emitIntValue(AsInt.getLimitedValue(),
  2897. AsInt.getBitWidth() / 8);
  2898. return false;
  2899. };
  2900. return parseMany(parseOp);
  2901. }
  2902. /// parseDirectiveZero
  2903. /// ::= .zero expression
  2904. bool AsmParser::parseDirectiveZero() {
  2905. SMLoc NumBytesLoc = Lexer.getLoc();
  2906. const MCExpr *NumBytes;
  2907. if (checkForValidSection() || parseExpression(NumBytes))
  2908. return true;
  2909. int64_t Val = 0;
  2910. if (getLexer().is(AsmToken::Comma)) {
  2911. Lex();
  2912. if (parseAbsoluteExpression(Val))
  2913. return true;
  2914. }
  2915. if (parseEOL())
  2916. return true;
  2917. getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
  2918. return false;
  2919. }
  2920. /// parseDirectiveFill
  2921. /// ::= .fill expression [ , expression [ , expression ] ]
  2922. bool AsmParser::parseDirectiveFill() {
  2923. SMLoc NumValuesLoc = Lexer.getLoc();
  2924. const MCExpr *NumValues;
  2925. if (checkForValidSection() || parseExpression(NumValues))
  2926. return true;
  2927. int64_t FillSize = 1;
  2928. int64_t FillExpr = 0;
  2929. SMLoc SizeLoc, ExprLoc;
  2930. if (parseOptionalToken(AsmToken::Comma)) {
  2931. SizeLoc = getTok().getLoc();
  2932. if (parseAbsoluteExpression(FillSize))
  2933. return true;
  2934. if (parseOptionalToken(AsmToken::Comma)) {
  2935. ExprLoc = getTok().getLoc();
  2936. if (parseAbsoluteExpression(FillExpr))
  2937. return true;
  2938. }
  2939. }
  2940. if (parseEOL())
  2941. return true;
  2942. if (FillSize < 0) {
  2943. Warning(SizeLoc, "'.fill' directive with negative size has no effect");
  2944. return false;
  2945. }
  2946. if (FillSize > 8) {
  2947. Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
  2948. FillSize = 8;
  2949. }
  2950. if (!isUInt<32>(FillExpr) && FillSize > 4)
  2951. Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
  2952. getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
  2953. return false;
  2954. }
  2955. /// parseDirectiveOrg
  2956. /// ::= .org expression [ , expression ]
  2957. bool AsmParser::parseDirectiveOrg() {
  2958. const MCExpr *Offset;
  2959. SMLoc OffsetLoc = Lexer.getLoc();
  2960. if (checkForValidSection() || parseExpression(Offset))
  2961. return true;
  2962. // Parse optional fill expression.
  2963. int64_t FillExpr = 0;
  2964. if (parseOptionalToken(AsmToken::Comma))
  2965. if (parseAbsoluteExpression(FillExpr))
  2966. return true;
  2967. if (parseEOL())
  2968. return true;
  2969. getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
  2970. return false;
  2971. }
  2972. /// parseDirectiveAlign
  2973. /// ::= {.align, ...} expression [ , expression [ , expression ]]
  2974. bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
  2975. SMLoc AlignmentLoc = getLexer().getLoc();
  2976. int64_t Alignment;
  2977. SMLoc MaxBytesLoc;
  2978. bool HasFillExpr = false;
  2979. int64_t FillExpr = 0;
  2980. int64_t MaxBytesToFill = 0;
  2981. auto parseAlign = [&]() -> bool {
  2982. if (parseAbsoluteExpression(Alignment))
  2983. return true;
  2984. if (parseOptionalToken(AsmToken::Comma)) {
  2985. // The fill expression can be omitted while specifying a maximum number of
  2986. // alignment bytes, e.g:
  2987. // .align 3,,4
  2988. if (getTok().isNot(AsmToken::Comma)) {
  2989. HasFillExpr = true;
  2990. if (parseAbsoluteExpression(FillExpr))
  2991. return true;
  2992. }
  2993. if (parseOptionalToken(AsmToken::Comma))
  2994. if (parseTokenLoc(MaxBytesLoc) ||
  2995. parseAbsoluteExpression(MaxBytesToFill))
  2996. return true;
  2997. }
  2998. return parseEOL();
  2999. };
  3000. if (checkForValidSection())
  3001. return true;
  3002. // Ignore empty '.p2align' directives for GNU-as compatibility
  3003. if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
  3004. Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
  3005. return parseEOL();
  3006. }
  3007. if (parseAlign())
  3008. return true;
  3009. // Always emit an alignment here even if we thrown an error.
  3010. bool ReturnVal = false;
  3011. // Compute alignment in bytes.
  3012. if (IsPow2) {
  3013. // FIXME: Diagnose overflow.
  3014. if (Alignment >= 32) {
  3015. ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
  3016. Alignment = 31;
  3017. }
  3018. Alignment = 1ULL << Alignment;
  3019. } else {
  3020. // Reject alignments that aren't either a power of two or zero,
  3021. // for gas compatibility. Alignment of zero is silently rounded
  3022. // up to one.
  3023. if (Alignment == 0)
  3024. Alignment = 1;
  3025. else if (!isPowerOf2_64(Alignment)) {
  3026. ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
  3027. Alignment = PowerOf2Floor(Alignment);
  3028. }
  3029. if (!isUInt<32>(Alignment)) {
  3030. ReturnVal |= Error(AlignmentLoc, "alignment must be smaller than 2**32");
  3031. Alignment = 1u << 31;
  3032. }
  3033. }
  3034. // Diagnose non-sensical max bytes to align.
  3035. if (MaxBytesLoc.isValid()) {
  3036. if (MaxBytesToFill < 1) {
  3037. ReturnVal |= Error(MaxBytesLoc,
  3038. "alignment directive can never be satisfied in this "
  3039. "many bytes, ignoring maximum bytes expression");
  3040. MaxBytesToFill = 0;
  3041. }
  3042. if (MaxBytesToFill >= Alignment) {
  3043. Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
  3044. "has no effect");
  3045. MaxBytesToFill = 0;
  3046. }
  3047. }
  3048. // Check whether we should use optimal code alignment for this .align
  3049. // directive.
  3050. const MCSection *Section = getStreamer().getCurrentSectionOnly();
  3051. assert(Section && "must have section to emit alignment");
  3052. bool useCodeAlign = Section->useCodeAlign();
  3053. if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
  3054. ValueSize == 1 && useCodeAlign) {
  3055. getStreamer().emitCodeAlignment(
  3056. Align(Alignment), &getTargetParser().getSTI(), MaxBytesToFill);
  3057. } else {
  3058. // FIXME: Target specific behavior about how the "extra" bytes are filled.
  3059. getStreamer().emitValueToAlignment(Align(Alignment), FillExpr, ValueSize,
  3060. MaxBytesToFill);
  3061. }
  3062. return ReturnVal;
  3063. }
  3064. /// parseDirectiveFile
  3065. /// ::= .file filename
  3066. /// ::= .file number [directory] filename [md5 checksum] [source source-text]
  3067. bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
  3068. // FIXME: I'm not sure what this is.
  3069. int64_t FileNumber = -1;
  3070. if (getLexer().is(AsmToken::Integer)) {
  3071. FileNumber = getTok().getIntVal();
  3072. Lex();
  3073. if (FileNumber < 0)
  3074. return TokError("negative file number");
  3075. }
  3076. std::string Path;
  3077. // Usually the directory and filename together, otherwise just the directory.
  3078. // Allow the strings to have escaped octal character sequence.
  3079. if (parseEscapedString(Path))
  3080. return true;
  3081. StringRef Directory;
  3082. StringRef Filename;
  3083. std::string FilenameData;
  3084. if (getLexer().is(AsmToken::String)) {
  3085. if (check(FileNumber == -1,
  3086. "explicit path specified, but no file number") ||
  3087. parseEscapedString(FilenameData))
  3088. return true;
  3089. Filename = FilenameData;
  3090. Directory = Path;
  3091. } else {
  3092. Filename = Path;
  3093. }
  3094. uint64_t MD5Hi, MD5Lo;
  3095. bool HasMD5 = false;
  3096. std::optional<StringRef> Source;
  3097. bool HasSource = false;
  3098. std::string SourceString;
  3099. while (!parseOptionalToken(AsmToken::EndOfStatement)) {
  3100. StringRef Keyword;
  3101. if (check(getTok().isNot(AsmToken::Identifier),
  3102. "unexpected token in '.file' directive") ||
  3103. parseIdentifier(Keyword))
  3104. return true;
  3105. if (Keyword == "md5") {
  3106. HasMD5 = true;
  3107. if (check(FileNumber == -1,
  3108. "MD5 checksum specified, but no file number") ||
  3109. parseHexOcta(*this, MD5Hi, MD5Lo))
  3110. return true;
  3111. } else if (Keyword == "source") {
  3112. HasSource = true;
  3113. if (check(FileNumber == -1,
  3114. "source specified, but no file number") ||
  3115. check(getTok().isNot(AsmToken::String),
  3116. "unexpected token in '.file' directive") ||
  3117. parseEscapedString(SourceString))
  3118. return true;
  3119. } else {
  3120. return TokError("unexpected token in '.file' directive");
  3121. }
  3122. }
  3123. if (FileNumber == -1) {
  3124. // Ignore the directive if there is no number and the target doesn't support
  3125. // numberless .file directives. This allows some portability of assembler
  3126. // between different object file formats.
  3127. if (getContext().getAsmInfo()->hasSingleParameterDotFile())
  3128. getStreamer().emitFileDirective(Filename);
  3129. } else {
  3130. // In case there is a -g option as well as debug info from directive .file,
  3131. // we turn off the -g option, directly use the existing debug info instead.
  3132. // Throw away any implicit file table for the assembler source.
  3133. if (Ctx.getGenDwarfForAssembly()) {
  3134. Ctx.getMCDwarfLineTable(0).resetFileTable();
  3135. Ctx.setGenDwarfForAssembly(false);
  3136. }
  3137. std::optional<MD5::MD5Result> CKMem;
  3138. if (HasMD5) {
  3139. MD5::MD5Result Sum;
  3140. for (unsigned i = 0; i != 8; ++i) {
  3141. Sum[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
  3142. Sum[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
  3143. }
  3144. CKMem = Sum;
  3145. }
  3146. if (HasSource) {
  3147. char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
  3148. memcpy(SourceBuf, SourceString.data(), SourceString.size());
  3149. Source = StringRef(SourceBuf, SourceString.size());
  3150. }
  3151. if (FileNumber == 0) {
  3152. // Upgrade to Version 5 for assembly actions like clang -c a.s.
  3153. if (Ctx.getDwarfVersion() < 5)
  3154. Ctx.setDwarfVersion(5);
  3155. getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
  3156. } else {
  3157. Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
  3158. FileNumber, Directory, Filename, CKMem, Source);
  3159. if (!FileNumOrErr)
  3160. return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
  3161. }
  3162. // Alert the user if there are some .file directives with MD5 and some not.
  3163. // But only do that once.
  3164. if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
  3165. ReportedInconsistentMD5 = true;
  3166. return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
  3167. }
  3168. }
  3169. return false;
  3170. }
  3171. /// parseDirectiveLine
  3172. /// ::= .line [number]
  3173. bool AsmParser::parseDirectiveLine() {
  3174. int64_t LineNumber;
  3175. if (getLexer().is(AsmToken::Integer)) {
  3176. if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
  3177. return true;
  3178. (void)LineNumber;
  3179. // FIXME: Do something with the .line.
  3180. }
  3181. return parseEOL();
  3182. }
  3183. /// parseDirectiveLoc
  3184. /// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
  3185. /// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
  3186. /// The first number is a file number, must have been previously assigned with
  3187. /// a .file directive, the second number is the line number and optionally the
  3188. /// third number is a column position (zero if not specified). The remaining
  3189. /// optional items are .loc sub-directives.
  3190. bool AsmParser::parseDirectiveLoc() {
  3191. int64_t FileNumber = 0, LineNumber = 0;
  3192. SMLoc Loc = getTok().getLoc();
  3193. if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
  3194. check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
  3195. "file number less than one in '.loc' directive") ||
  3196. check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
  3197. "unassigned file number in '.loc' directive"))
  3198. return true;
  3199. // optional
  3200. if (getLexer().is(AsmToken::Integer)) {
  3201. LineNumber = getTok().getIntVal();
  3202. if (LineNumber < 0)
  3203. return TokError("line number less than zero in '.loc' directive");
  3204. Lex();
  3205. }
  3206. int64_t ColumnPos = 0;
  3207. if (getLexer().is(AsmToken::Integer)) {
  3208. ColumnPos = getTok().getIntVal();
  3209. if (ColumnPos < 0)
  3210. return TokError("column position less than zero in '.loc' directive");
  3211. Lex();
  3212. }
  3213. auto PrevFlags = getContext().getCurrentDwarfLoc().getFlags();
  3214. unsigned Flags = PrevFlags & DWARF2_FLAG_IS_STMT;
  3215. unsigned Isa = 0;
  3216. int64_t Discriminator = 0;
  3217. auto parseLocOp = [&]() -> bool {
  3218. StringRef Name;
  3219. SMLoc Loc = getTok().getLoc();
  3220. if (parseIdentifier(Name))
  3221. return TokError("unexpected token in '.loc' directive");
  3222. if (Name == "basic_block")
  3223. Flags |= DWARF2_FLAG_BASIC_BLOCK;
  3224. else if (Name == "prologue_end")
  3225. Flags |= DWARF2_FLAG_PROLOGUE_END;
  3226. else if (Name == "epilogue_begin")
  3227. Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
  3228. else if (Name == "is_stmt") {
  3229. Loc = getTok().getLoc();
  3230. const MCExpr *Value;
  3231. if (parseExpression(Value))
  3232. return true;
  3233. // The expression must be the constant 0 or 1.
  3234. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
  3235. int Value = MCE->getValue();
  3236. if (Value == 0)
  3237. Flags &= ~DWARF2_FLAG_IS_STMT;
  3238. else if (Value == 1)
  3239. Flags |= DWARF2_FLAG_IS_STMT;
  3240. else
  3241. return Error(Loc, "is_stmt value not 0 or 1");
  3242. } else {
  3243. return Error(Loc, "is_stmt value not the constant value of 0 or 1");
  3244. }
  3245. } else if (Name == "isa") {
  3246. Loc = getTok().getLoc();
  3247. const MCExpr *Value;
  3248. if (parseExpression(Value))
  3249. return true;
  3250. // The expression must be a constant greater or equal to 0.
  3251. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
  3252. int Value = MCE->getValue();
  3253. if (Value < 0)
  3254. return Error(Loc, "isa number less than zero");
  3255. Isa = Value;
  3256. } else {
  3257. return Error(Loc, "isa number not a constant value");
  3258. }
  3259. } else if (Name == "discriminator") {
  3260. if (parseAbsoluteExpression(Discriminator))
  3261. return true;
  3262. } else {
  3263. return Error(Loc, "unknown sub-directive in '.loc' directive");
  3264. }
  3265. return false;
  3266. };
  3267. if (parseMany(parseLocOp, false /*hasComma*/))
  3268. return true;
  3269. getStreamer().emitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
  3270. Isa, Discriminator, StringRef());
  3271. return false;
  3272. }
  3273. /// parseDirectiveStabs
  3274. /// ::= .stabs string, number, number, number
  3275. bool AsmParser::parseDirectiveStabs() {
  3276. return TokError("unsupported directive '.stabs'");
  3277. }
  3278. /// parseDirectiveCVFile
  3279. /// ::= .cv_file number filename [checksum] [checksumkind]
  3280. bool AsmParser::parseDirectiveCVFile() {
  3281. SMLoc FileNumberLoc = getTok().getLoc();
  3282. int64_t FileNumber;
  3283. std::string Filename;
  3284. std::string Checksum;
  3285. int64_t ChecksumKind = 0;
  3286. if (parseIntToken(FileNumber,
  3287. "expected file number in '.cv_file' directive") ||
  3288. check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
  3289. check(getTok().isNot(AsmToken::String),
  3290. "unexpected token in '.cv_file' directive") ||
  3291. parseEscapedString(Filename))
  3292. return true;
  3293. if (!parseOptionalToken(AsmToken::EndOfStatement)) {
  3294. if (check(getTok().isNot(AsmToken::String),
  3295. "unexpected token in '.cv_file' directive") ||
  3296. parseEscapedString(Checksum) ||
  3297. parseIntToken(ChecksumKind,
  3298. "expected checksum kind in '.cv_file' directive") ||
  3299. parseEOL())
  3300. return true;
  3301. }
  3302. Checksum = fromHex(Checksum);
  3303. void *CKMem = Ctx.allocate(Checksum.size(), 1);
  3304. memcpy(CKMem, Checksum.data(), Checksum.size());
  3305. ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
  3306. Checksum.size());
  3307. if (!getStreamer().emitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
  3308. static_cast<uint8_t>(ChecksumKind)))
  3309. return Error(FileNumberLoc, "file number already allocated");
  3310. return false;
  3311. }
  3312. bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
  3313. StringRef DirectiveName) {
  3314. SMLoc Loc;
  3315. return parseTokenLoc(Loc) ||
  3316. parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
  3317. "' directive") ||
  3318. check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
  3319. "expected function id within range [0, UINT_MAX)");
  3320. }
  3321. bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
  3322. SMLoc Loc;
  3323. return parseTokenLoc(Loc) ||
  3324. parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
  3325. "' directive") ||
  3326. check(FileNumber < 1, Loc, "file number less than one in '" +
  3327. DirectiveName + "' directive") ||
  3328. check(!getCVContext().isValidFileNumber(FileNumber), Loc,
  3329. "unassigned file number in '" + DirectiveName + "' directive");
  3330. }
  3331. /// parseDirectiveCVFuncId
  3332. /// ::= .cv_func_id FunctionId
  3333. ///
  3334. /// Introduces a function ID that can be used with .cv_loc.
  3335. bool AsmParser::parseDirectiveCVFuncId() {
  3336. SMLoc FunctionIdLoc = getTok().getLoc();
  3337. int64_t FunctionId;
  3338. if (parseCVFunctionId(FunctionId, ".cv_func_id") || parseEOL())
  3339. return true;
  3340. if (!getStreamer().emitCVFuncIdDirective(FunctionId))
  3341. return Error(FunctionIdLoc, "function id already allocated");
  3342. return false;
  3343. }
  3344. /// parseDirectiveCVInlineSiteId
  3345. /// ::= .cv_inline_site_id FunctionId
  3346. /// "within" IAFunc
  3347. /// "inlined_at" IAFile IALine [IACol]
  3348. ///
  3349. /// Introduces a function ID that can be used with .cv_loc. Includes "inlined
  3350. /// at" source location information for use in the line table of the caller,
  3351. /// whether the caller is a real function or another inlined call site.
  3352. bool AsmParser::parseDirectiveCVInlineSiteId() {
  3353. SMLoc FunctionIdLoc = getTok().getLoc();
  3354. int64_t FunctionId;
  3355. int64_t IAFunc;
  3356. int64_t IAFile;
  3357. int64_t IALine;
  3358. int64_t IACol = 0;
  3359. // FunctionId
  3360. if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
  3361. return true;
  3362. // "within"
  3363. if (check((getLexer().isNot(AsmToken::Identifier) ||
  3364. getTok().getIdentifier() != "within"),
  3365. "expected 'within' identifier in '.cv_inline_site_id' directive"))
  3366. return true;
  3367. Lex();
  3368. // IAFunc
  3369. if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
  3370. return true;
  3371. // "inlined_at"
  3372. if (check((getLexer().isNot(AsmToken::Identifier) ||
  3373. getTok().getIdentifier() != "inlined_at"),
  3374. "expected 'inlined_at' identifier in '.cv_inline_site_id' "
  3375. "directive") )
  3376. return true;
  3377. Lex();
  3378. // IAFile IALine
  3379. if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
  3380. parseIntToken(IALine, "expected line number after 'inlined_at'"))
  3381. return true;
  3382. // [IACol]
  3383. if (getLexer().is(AsmToken::Integer)) {
  3384. IACol = getTok().getIntVal();
  3385. Lex();
  3386. }
  3387. if (parseEOL())
  3388. return true;
  3389. if (!getStreamer().emitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
  3390. IALine, IACol, FunctionIdLoc))
  3391. return Error(FunctionIdLoc, "function id already allocated");
  3392. return false;
  3393. }
  3394. /// parseDirectiveCVLoc
  3395. /// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
  3396. /// [is_stmt VALUE]
  3397. /// The first number is a file number, must have been previously assigned with
  3398. /// a .file directive, the second number is the line number and optionally the
  3399. /// third number is a column position (zero if not specified). The remaining
  3400. /// optional items are .loc sub-directives.
  3401. bool AsmParser::parseDirectiveCVLoc() {
  3402. SMLoc DirectiveLoc = getTok().getLoc();
  3403. int64_t FunctionId, FileNumber;
  3404. if (parseCVFunctionId(FunctionId, ".cv_loc") ||
  3405. parseCVFileId(FileNumber, ".cv_loc"))
  3406. return true;
  3407. int64_t LineNumber = 0;
  3408. if (getLexer().is(AsmToken::Integer)) {
  3409. LineNumber = getTok().getIntVal();
  3410. if (LineNumber < 0)
  3411. return TokError("line number less than zero in '.cv_loc' directive");
  3412. Lex();
  3413. }
  3414. int64_t ColumnPos = 0;
  3415. if (getLexer().is(AsmToken::Integer)) {
  3416. ColumnPos = getTok().getIntVal();
  3417. if (ColumnPos < 0)
  3418. return TokError("column position less than zero in '.cv_loc' directive");
  3419. Lex();
  3420. }
  3421. bool PrologueEnd = false;
  3422. uint64_t IsStmt = 0;
  3423. auto parseOp = [&]() -> bool {
  3424. StringRef Name;
  3425. SMLoc Loc = getTok().getLoc();
  3426. if (parseIdentifier(Name))
  3427. return TokError("unexpected token in '.cv_loc' directive");
  3428. if (Name == "prologue_end")
  3429. PrologueEnd = true;
  3430. else if (Name == "is_stmt") {
  3431. Loc = getTok().getLoc();
  3432. const MCExpr *Value;
  3433. if (parseExpression(Value))
  3434. return true;
  3435. // The expression must be the constant 0 or 1.
  3436. IsStmt = ~0ULL;
  3437. if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
  3438. IsStmt = MCE->getValue();
  3439. if (IsStmt > 1)
  3440. return Error(Loc, "is_stmt value not 0 or 1");
  3441. } else {
  3442. return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
  3443. }
  3444. return false;
  3445. };
  3446. if (parseMany(parseOp, false /*hasComma*/))
  3447. return true;
  3448. getStreamer().emitCVLocDirective(FunctionId, FileNumber, LineNumber,
  3449. ColumnPos, PrologueEnd, IsStmt, StringRef(),
  3450. DirectiveLoc);
  3451. return false;
  3452. }
  3453. /// parseDirectiveCVLinetable
  3454. /// ::= .cv_linetable FunctionId, FnStart, FnEnd
  3455. bool AsmParser::parseDirectiveCVLinetable() {
  3456. int64_t FunctionId;
  3457. StringRef FnStartName, FnEndName;
  3458. SMLoc Loc = getTok().getLoc();
  3459. if (parseCVFunctionId(FunctionId, ".cv_linetable") || parseComma() ||
  3460. parseTokenLoc(Loc) ||
  3461. check(parseIdentifier(FnStartName), Loc,
  3462. "expected identifier in directive") ||
  3463. parseComma() || parseTokenLoc(Loc) ||
  3464. check(parseIdentifier(FnEndName), Loc,
  3465. "expected identifier in directive"))
  3466. return true;
  3467. MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
  3468. MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
  3469. getStreamer().emitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
  3470. return false;
  3471. }
  3472. /// parseDirectiveCVInlineLinetable
  3473. /// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
  3474. bool AsmParser::parseDirectiveCVInlineLinetable() {
  3475. int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
  3476. StringRef FnStartName, FnEndName;
  3477. SMLoc Loc = getTok().getLoc();
  3478. if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
  3479. parseTokenLoc(Loc) ||
  3480. parseIntToken(
  3481. SourceFileId,
  3482. "expected SourceField in '.cv_inline_linetable' directive") ||
  3483. check(SourceFileId <= 0, Loc,
  3484. "File id less than zero in '.cv_inline_linetable' directive") ||
  3485. parseTokenLoc(Loc) ||
  3486. parseIntToken(
  3487. SourceLineNum,
  3488. "expected SourceLineNum in '.cv_inline_linetable' directive") ||
  3489. check(SourceLineNum < 0, Loc,
  3490. "Line number less than zero in '.cv_inline_linetable' directive") ||
  3491. parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
  3492. "expected identifier in directive") ||
  3493. parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
  3494. "expected identifier in directive"))
  3495. return true;
  3496. if (parseEOL())
  3497. return true;
  3498. MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
  3499. MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
  3500. getStreamer().emitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
  3501. SourceLineNum, FnStartSym,
  3502. FnEndSym);
  3503. return false;
  3504. }
  3505. void AsmParser::initializeCVDefRangeTypeMap() {
  3506. CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
  3507. CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
  3508. CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
  3509. CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
  3510. }
  3511. /// parseDirectiveCVDefRange
  3512. /// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
  3513. bool AsmParser::parseDirectiveCVDefRange() {
  3514. SMLoc Loc;
  3515. std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
  3516. while (getLexer().is(AsmToken::Identifier)) {
  3517. Loc = getLexer().getLoc();
  3518. StringRef GapStartName;
  3519. if (parseIdentifier(GapStartName))
  3520. return Error(Loc, "expected identifier in directive");
  3521. MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
  3522. Loc = getLexer().getLoc();
  3523. StringRef GapEndName;
  3524. if (parseIdentifier(GapEndName))
  3525. return Error(Loc, "expected identifier in directive");
  3526. MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
  3527. Ranges.push_back({GapStartSym, GapEndSym});
  3528. }
  3529. StringRef CVDefRangeTypeStr;
  3530. if (parseToken(
  3531. AsmToken::Comma,
  3532. "expected comma before def_range type in .cv_def_range directive") ||
  3533. parseIdentifier(CVDefRangeTypeStr))
  3534. return Error(Loc, "expected def_range type in directive");
  3535. StringMap<CVDefRangeType>::const_iterator CVTypeIt =
  3536. CVDefRangeTypeMap.find(CVDefRangeTypeStr);
  3537. CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
  3538. ? CVDR_DEFRANGE
  3539. : CVTypeIt->getValue();
  3540. switch (CVDRType) {
  3541. case CVDR_DEFRANGE_REGISTER: {
  3542. int64_t DRRegister;
  3543. if (parseToken(AsmToken::Comma, "expected comma before register number in "
  3544. ".cv_def_range directive") ||
  3545. parseAbsoluteExpression(DRRegister))
  3546. return Error(Loc, "expected register number");
  3547. codeview::DefRangeRegisterHeader DRHdr;
  3548. DRHdr.Register = DRRegister;
  3549. DRHdr.MayHaveNoName = 0;
  3550. getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
  3551. break;
  3552. }
  3553. case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
  3554. int64_t DROffset;
  3555. if (parseToken(AsmToken::Comma,
  3556. "expected comma before offset in .cv_def_range directive") ||
  3557. parseAbsoluteExpression(DROffset))
  3558. return Error(Loc, "expected offset value");
  3559. codeview::DefRangeFramePointerRelHeader DRHdr;
  3560. DRHdr.Offset = DROffset;
  3561. getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
  3562. break;
  3563. }
  3564. case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
  3565. int64_t DRRegister;
  3566. int64_t DROffsetInParent;
  3567. if (parseToken(AsmToken::Comma, "expected comma before register number in "
  3568. ".cv_def_range directive") ||
  3569. parseAbsoluteExpression(DRRegister))
  3570. return Error(Loc, "expected register number");
  3571. if (parseToken(AsmToken::Comma,
  3572. "expected comma before offset in .cv_def_range directive") ||
  3573. parseAbsoluteExpression(DROffsetInParent))
  3574. return Error(Loc, "expected offset value");
  3575. codeview::DefRangeSubfieldRegisterHeader DRHdr;
  3576. DRHdr.Register = DRRegister;
  3577. DRHdr.MayHaveNoName = 0;
  3578. DRHdr.OffsetInParent = DROffsetInParent;
  3579. getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
  3580. break;
  3581. }
  3582. case CVDR_DEFRANGE_REGISTER_REL: {
  3583. int64_t DRRegister;
  3584. int64_t DRFlags;
  3585. int64_t DRBasePointerOffset;
  3586. if (parseToken(AsmToken::Comma, "expected comma before register number in "
  3587. ".cv_def_range directive") ||
  3588. parseAbsoluteExpression(DRRegister))
  3589. return Error(Loc, "expected register value");
  3590. if (parseToken(
  3591. AsmToken::Comma,
  3592. "expected comma before flag value in .cv_def_range directive") ||
  3593. parseAbsoluteExpression(DRFlags))
  3594. return Error(Loc, "expected flag value");
  3595. if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
  3596. "in .cv_def_range directive") ||
  3597. parseAbsoluteExpression(DRBasePointerOffset))
  3598. return Error(Loc, "expected base pointer offset value");
  3599. codeview::DefRangeRegisterRelHeader DRHdr;
  3600. DRHdr.Register = DRRegister;
  3601. DRHdr.Flags = DRFlags;
  3602. DRHdr.BasePointerOffset = DRBasePointerOffset;
  3603. getStreamer().emitCVDefRangeDirective(Ranges, DRHdr);
  3604. break;
  3605. }
  3606. default:
  3607. return Error(Loc, "unexpected def_range type in .cv_def_range directive");
  3608. }
  3609. return true;
  3610. }
  3611. /// parseDirectiveCVString
  3612. /// ::= .cv_stringtable "string"
  3613. bool AsmParser::parseDirectiveCVString() {
  3614. std::string Data;
  3615. if (checkForValidSection() || parseEscapedString(Data))
  3616. return true;
  3617. // Put the string in the table and emit the offset.
  3618. std::pair<StringRef, unsigned> Insertion =
  3619. getCVContext().addToStringTable(Data);
  3620. getStreamer().emitInt32(Insertion.second);
  3621. return false;
  3622. }
  3623. /// parseDirectiveCVStringTable
  3624. /// ::= .cv_stringtable
  3625. bool AsmParser::parseDirectiveCVStringTable() {
  3626. getStreamer().emitCVStringTableDirective();
  3627. return false;
  3628. }
  3629. /// parseDirectiveCVFileChecksums
  3630. /// ::= .cv_filechecksums
  3631. bool AsmParser::parseDirectiveCVFileChecksums() {
  3632. getStreamer().emitCVFileChecksumsDirective();
  3633. return false;
  3634. }
  3635. /// parseDirectiveCVFileChecksumOffset
  3636. /// ::= .cv_filechecksumoffset fileno
  3637. bool AsmParser::parseDirectiveCVFileChecksumOffset() {
  3638. int64_t FileNo;
  3639. if (parseIntToken(FileNo, "expected identifier in directive"))
  3640. return true;
  3641. if (parseEOL())
  3642. return true;
  3643. getStreamer().emitCVFileChecksumOffsetDirective(FileNo);
  3644. return false;
  3645. }
  3646. /// parseDirectiveCVFPOData
  3647. /// ::= .cv_fpo_data procsym
  3648. bool AsmParser::parseDirectiveCVFPOData() {
  3649. SMLoc DirLoc = getLexer().getLoc();
  3650. StringRef ProcName;
  3651. if (parseIdentifier(ProcName))
  3652. return TokError("expected symbol name");
  3653. if (parseEOL())
  3654. return true;
  3655. MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
  3656. getStreamer().emitCVFPOData(ProcSym, DirLoc);
  3657. return false;
  3658. }
  3659. /// parseDirectiveCFISections
  3660. /// ::= .cfi_sections section [, section]
  3661. bool AsmParser::parseDirectiveCFISections() {
  3662. StringRef Name;
  3663. bool EH = false;
  3664. bool Debug = false;
  3665. if (!parseOptionalToken(AsmToken::EndOfStatement)) {
  3666. for (;;) {
  3667. if (parseIdentifier(Name))
  3668. return TokError("expected .eh_frame or .debug_frame");
  3669. if (Name == ".eh_frame")
  3670. EH = true;
  3671. else if (Name == ".debug_frame")
  3672. Debug = true;
  3673. if (parseOptionalToken(AsmToken::EndOfStatement))
  3674. break;
  3675. if (parseComma())
  3676. return true;
  3677. }
  3678. }
  3679. getStreamer().emitCFISections(EH, Debug);
  3680. return false;
  3681. }
  3682. /// parseDirectiveCFIStartProc
  3683. /// ::= .cfi_startproc [simple]
  3684. bool AsmParser::parseDirectiveCFIStartProc() {
  3685. StringRef Simple;
  3686. if (!parseOptionalToken(AsmToken::EndOfStatement)) {
  3687. if (check(parseIdentifier(Simple) || Simple != "simple",
  3688. "unexpected token") ||
  3689. parseEOL())
  3690. return true;
  3691. }
  3692. // TODO(kristina): Deal with a corner case of incorrect diagnostic context
  3693. // being produced if this directive is emitted as part of preprocessor macro
  3694. // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
  3695. // Tools like llvm-mc on the other hand are not affected by it, and report
  3696. // correct context information.
  3697. getStreamer().emitCFIStartProc(!Simple.empty(), Lexer.getLoc());
  3698. return false;
  3699. }
  3700. /// parseDirectiveCFIEndProc
  3701. /// ::= .cfi_endproc
  3702. bool AsmParser::parseDirectiveCFIEndProc() {
  3703. if (parseEOL())
  3704. return true;
  3705. getStreamer().emitCFIEndProc();
  3706. return false;
  3707. }
  3708. /// parse register name or number.
  3709. bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
  3710. SMLoc DirectiveLoc) {
  3711. MCRegister RegNo;
  3712. if (getLexer().isNot(AsmToken::Integer)) {
  3713. if (getTargetParser().parseRegister(RegNo, DirectiveLoc, DirectiveLoc))
  3714. return true;
  3715. Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
  3716. } else
  3717. return parseAbsoluteExpression(Register);
  3718. return false;
  3719. }
  3720. /// parseDirectiveCFIDefCfa
  3721. /// ::= .cfi_def_cfa register, offset
  3722. bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
  3723. int64_t Register = 0, Offset = 0;
  3724. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
  3725. parseAbsoluteExpression(Offset) || parseEOL())
  3726. return true;
  3727. getStreamer().emitCFIDefCfa(Register, Offset);
  3728. return false;
  3729. }
  3730. /// parseDirectiveCFIDefCfaOffset
  3731. /// ::= .cfi_def_cfa_offset offset
  3732. bool AsmParser::parseDirectiveCFIDefCfaOffset() {
  3733. int64_t Offset = 0;
  3734. if (parseAbsoluteExpression(Offset) || parseEOL())
  3735. return true;
  3736. getStreamer().emitCFIDefCfaOffset(Offset);
  3737. return false;
  3738. }
  3739. /// parseDirectiveCFIRegister
  3740. /// ::= .cfi_register register, register
  3741. bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
  3742. int64_t Register1 = 0, Register2 = 0;
  3743. if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) || parseComma() ||
  3744. parseRegisterOrRegisterNumber(Register2, DirectiveLoc) || parseEOL())
  3745. return true;
  3746. getStreamer().emitCFIRegister(Register1, Register2);
  3747. return false;
  3748. }
  3749. /// parseDirectiveCFIWindowSave
  3750. /// ::= .cfi_window_save
  3751. bool AsmParser::parseDirectiveCFIWindowSave() {
  3752. if (parseEOL())
  3753. return true;
  3754. getStreamer().emitCFIWindowSave();
  3755. return false;
  3756. }
  3757. /// parseDirectiveCFIAdjustCfaOffset
  3758. /// ::= .cfi_adjust_cfa_offset adjustment
  3759. bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
  3760. int64_t Adjustment = 0;
  3761. if (parseAbsoluteExpression(Adjustment) || parseEOL())
  3762. return true;
  3763. getStreamer().emitCFIAdjustCfaOffset(Adjustment);
  3764. return false;
  3765. }
  3766. /// parseDirectiveCFIDefCfaRegister
  3767. /// ::= .cfi_def_cfa_register register
  3768. bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
  3769. int64_t Register = 0;
  3770. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
  3771. return true;
  3772. getStreamer().emitCFIDefCfaRegister(Register);
  3773. return false;
  3774. }
  3775. /// parseDirectiveCFILLVMDefAspaceCfa
  3776. /// ::= .cfi_llvm_def_aspace_cfa register, offset, address_space
  3777. bool AsmParser::parseDirectiveCFILLVMDefAspaceCfa(SMLoc DirectiveLoc) {
  3778. int64_t Register = 0, Offset = 0, AddressSpace = 0;
  3779. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
  3780. parseAbsoluteExpression(Offset) || parseComma() ||
  3781. parseAbsoluteExpression(AddressSpace) || parseEOL())
  3782. return true;
  3783. getStreamer().emitCFILLVMDefAspaceCfa(Register, Offset, AddressSpace);
  3784. return false;
  3785. }
  3786. /// parseDirectiveCFIOffset
  3787. /// ::= .cfi_offset register, offset
  3788. bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
  3789. int64_t Register = 0;
  3790. int64_t Offset = 0;
  3791. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
  3792. parseAbsoluteExpression(Offset) || parseEOL())
  3793. return true;
  3794. getStreamer().emitCFIOffset(Register, Offset);
  3795. return false;
  3796. }
  3797. /// parseDirectiveCFIRelOffset
  3798. /// ::= .cfi_rel_offset register, offset
  3799. bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
  3800. int64_t Register = 0, Offset = 0;
  3801. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseComma() ||
  3802. parseAbsoluteExpression(Offset) || parseEOL())
  3803. return true;
  3804. getStreamer().emitCFIRelOffset(Register, Offset);
  3805. return false;
  3806. }
  3807. static bool isValidEncoding(int64_t Encoding) {
  3808. if (Encoding & ~0xff)
  3809. return false;
  3810. if (Encoding == dwarf::DW_EH_PE_omit)
  3811. return true;
  3812. const unsigned Format = Encoding & 0xf;
  3813. if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
  3814. Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
  3815. Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
  3816. Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
  3817. return false;
  3818. const unsigned Application = Encoding & 0x70;
  3819. if (Application != dwarf::DW_EH_PE_absptr &&
  3820. Application != dwarf::DW_EH_PE_pcrel)
  3821. return false;
  3822. return true;
  3823. }
  3824. /// parseDirectiveCFIPersonalityOrLsda
  3825. /// IsPersonality true for cfi_personality, false for cfi_lsda
  3826. /// ::= .cfi_personality encoding, [symbol_name]
  3827. /// ::= .cfi_lsda encoding, [symbol_name]
  3828. bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
  3829. int64_t Encoding = 0;
  3830. if (parseAbsoluteExpression(Encoding))
  3831. return true;
  3832. if (Encoding == dwarf::DW_EH_PE_omit)
  3833. return false;
  3834. StringRef Name;
  3835. if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
  3836. parseComma() ||
  3837. check(parseIdentifier(Name), "expected identifier in directive") ||
  3838. parseEOL())
  3839. return true;
  3840. MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
  3841. if (IsPersonality)
  3842. getStreamer().emitCFIPersonality(Sym, Encoding);
  3843. else
  3844. getStreamer().emitCFILsda(Sym, Encoding);
  3845. return false;
  3846. }
  3847. /// parseDirectiveCFIRememberState
  3848. /// ::= .cfi_remember_state
  3849. bool AsmParser::parseDirectiveCFIRememberState() {
  3850. if (parseEOL())
  3851. return true;
  3852. getStreamer().emitCFIRememberState();
  3853. return false;
  3854. }
  3855. /// parseDirectiveCFIRestoreState
  3856. /// ::= .cfi_remember_state
  3857. bool AsmParser::parseDirectiveCFIRestoreState() {
  3858. if (parseEOL())
  3859. return true;
  3860. getStreamer().emitCFIRestoreState();
  3861. return false;
  3862. }
  3863. /// parseDirectiveCFISameValue
  3864. /// ::= .cfi_same_value register
  3865. bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
  3866. int64_t Register = 0;
  3867. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
  3868. return true;
  3869. getStreamer().emitCFISameValue(Register);
  3870. return false;
  3871. }
  3872. /// parseDirectiveCFIRestore
  3873. /// ::= .cfi_restore register
  3874. bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
  3875. int64_t Register = 0;
  3876. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
  3877. return true;
  3878. getStreamer().emitCFIRestore(Register);
  3879. return false;
  3880. }
  3881. /// parseDirectiveCFIEscape
  3882. /// ::= .cfi_escape expression[,...]
  3883. bool AsmParser::parseDirectiveCFIEscape() {
  3884. std::string Values;
  3885. int64_t CurrValue;
  3886. if (parseAbsoluteExpression(CurrValue))
  3887. return true;
  3888. Values.push_back((uint8_t)CurrValue);
  3889. while (getLexer().is(AsmToken::Comma)) {
  3890. Lex();
  3891. if (parseAbsoluteExpression(CurrValue))
  3892. return true;
  3893. Values.push_back((uint8_t)CurrValue);
  3894. }
  3895. getStreamer().emitCFIEscape(Values);
  3896. return false;
  3897. }
  3898. /// parseDirectiveCFIReturnColumn
  3899. /// ::= .cfi_return_column register
  3900. bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
  3901. int64_t Register = 0;
  3902. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
  3903. return true;
  3904. getStreamer().emitCFIReturnColumn(Register);
  3905. return false;
  3906. }
  3907. /// parseDirectiveCFISignalFrame
  3908. /// ::= .cfi_signal_frame
  3909. bool AsmParser::parseDirectiveCFISignalFrame() {
  3910. if (parseEOL())
  3911. return true;
  3912. getStreamer().emitCFISignalFrame();
  3913. return false;
  3914. }
  3915. /// parseDirectiveCFIUndefined
  3916. /// ::= .cfi_undefined register
  3917. bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
  3918. int64_t Register = 0;
  3919. if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) || parseEOL())
  3920. return true;
  3921. getStreamer().emitCFIUndefined(Register);
  3922. return false;
  3923. }
  3924. /// parseDirectiveAltmacro
  3925. /// ::= .altmacro
  3926. /// ::= .noaltmacro
  3927. bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
  3928. if (parseEOL())
  3929. return true;
  3930. AltMacroMode = (Directive == ".altmacro");
  3931. return false;
  3932. }
  3933. /// parseDirectiveMacrosOnOff
  3934. /// ::= .macros_on
  3935. /// ::= .macros_off
  3936. bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
  3937. if (parseEOL())
  3938. return true;
  3939. setMacrosEnabled(Directive == ".macros_on");
  3940. return false;
  3941. }
  3942. /// parseDirectiveMacro
  3943. /// ::= .macro name[,] [parameters]
  3944. bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
  3945. StringRef Name;
  3946. if (parseIdentifier(Name))
  3947. return TokError("expected identifier in '.macro' directive");
  3948. if (getLexer().is(AsmToken::Comma))
  3949. Lex();
  3950. MCAsmMacroParameters Parameters;
  3951. while (getLexer().isNot(AsmToken::EndOfStatement)) {
  3952. if (!Parameters.empty() && Parameters.back().Vararg)
  3953. return Error(Lexer.getLoc(), "vararg parameter '" +
  3954. Parameters.back().Name +
  3955. "' should be the last parameter");
  3956. MCAsmMacroParameter Parameter;
  3957. if (parseIdentifier(Parameter.Name))
  3958. return TokError("expected identifier in '.macro' directive");
  3959. // Emit an error if two (or more) named parameters share the same name
  3960. for (const MCAsmMacroParameter& CurrParam : Parameters)
  3961. if (CurrParam.Name.equals(Parameter.Name))
  3962. return TokError("macro '" + Name + "' has multiple parameters"
  3963. " named '" + Parameter.Name + "'");
  3964. if (Lexer.is(AsmToken::Colon)) {
  3965. Lex(); // consume ':'
  3966. SMLoc QualLoc;
  3967. StringRef Qualifier;
  3968. QualLoc = Lexer.getLoc();
  3969. if (parseIdentifier(Qualifier))
  3970. return Error(QualLoc, "missing parameter qualifier for "
  3971. "'" + Parameter.Name + "' in macro '" + Name + "'");
  3972. if (Qualifier == "req")
  3973. Parameter.Required = true;
  3974. else if (Qualifier == "vararg")
  3975. Parameter.Vararg = true;
  3976. else
  3977. return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
  3978. "for '" + Parameter.Name + "' in macro '" + Name + "'");
  3979. }
  3980. if (getLexer().is(AsmToken::Equal)) {
  3981. Lex();
  3982. SMLoc ParamLoc;
  3983. ParamLoc = Lexer.getLoc();
  3984. if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
  3985. return true;
  3986. if (Parameter.Required)
  3987. Warning(ParamLoc, "pointless default value for required parameter "
  3988. "'" + Parameter.Name + "' in macro '" + Name + "'");
  3989. }
  3990. Parameters.push_back(std::move(Parameter));
  3991. if (getLexer().is(AsmToken::Comma))
  3992. Lex();
  3993. }
  3994. // Eat just the end of statement.
  3995. Lexer.Lex();
  3996. // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
  3997. AsmToken EndToken, StartToken = getTok();
  3998. unsigned MacroDepth = 0;
  3999. // Lex the macro definition.
  4000. while (true) {
  4001. // Ignore Lexing errors in macros.
  4002. while (Lexer.is(AsmToken::Error)) {
  4003. Lexer.Lex();
  4004. }
  4005. // Check whether we have reached the end of the file.
  4006. if (getLexer().is(AsmToken::Eof))
  4007. return Error(DirectiveLoc, "no matching '.endmacro' in definition");
  4008. // Otherwise, check whether we have reach the .endmacro or the start of a
  4009. // preprocessor line marker.
  4010. if (getLexer().is(AsmToken::Identifier)) {
  4011. if (getTok().getIdentifier() == ".endm" ||
  4012. getTok().getIdentifier() == ".endmacro") {
  4013. if (MacroDepth == 0) { // Outermost macro.
  4014. EndToken = getTok();
  4015. Lexer.Lex();
  4016. if (getLexer().isNot(AsmToken::EndOfStatement))
  4017. return TokError("unexpected token in '" + EndToken.getIdentifier() +
  4018. "' directive");
  4019. break;
  4020. } else {
  4021. // Otherwise we just found the end of an inner macro.
  4022. --MacroDepth;
  4023. }
  4024. } else if (getTok().getIdentifier() == ".macro") {
  4025. // We allow nested macros. Those aren't instantiated until the outermost
  4026. // macro is expanded so just ignore them for now.
  4027. ++MacroDepth;
  4028. }
  4029. } else if (Lexer.is(AsmToken::HashDirective)) {
  4030. (void)parseCppHashLineFilenameComment(getLexer().getLoc());
  4031. }
  4032. // Otherwise, scan til the end of the statement.
  4033. eatToEndOfStatement();
  4034. }
  4035. if (getContext().lookupMacro(Name)) {
  4036. return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
  4037. }
  4038. const char *BodyStart = StartToken.getLoc().getPointer();
  4039. const char *BodyEnd = EndToken.getLoc().getPointer();
  4040. StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
  4041. checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
  4042. MCAsmMacro Macro(Name, Body, std::move(Parameters));
  4043. DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
  4044. Macro.dump());
  4045. getContext().defineMacro(Name, std::move(Macro));
  4046. return false;
  4047. }
  4048. /// checkForBadMacro
  4049. ///
  4050. /// With the support added for named parameters there may be code out there that
  4051. /// is transitioning from positional parameters. In versions of gas that did
  4052. /// not support named parameters they would be ignored on the macro definition.
  4053. /// But to support both styles of parameters this is not possible so if a macro
  4054. /// definition has named parameters but does not use them and has what appears
  4055. /// to be positional parameters, strings like $1, $2, ... and $n, then issue a
  4056. /// warning that the positional parameter found in body which have no effect.
  4057. /// Hoping the developer will either remove the named parameters from the macro
  4058. /// definition so the positional parameters get used if that was what was
  4059. /// intended or change the macro to use the named parameters. It is possible
  4060. /// this warning will trigger when the none of the named parameters are used
  4061. /// and the strings like $1 are infact to simply to be passed trough unchanged.
  4062. void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
  4063. StringRef Body,
  4064. ArrayRef<MCAsmMacroParameter> Parameters) {
  4065. // If this macro is not defined with named parameters the warning we are
  4066. // checking for here doesn't apply.
  4067. unsigned NParameters = Parameters.size();
  4068. if (NParameters == 0)
  4069. return;
  4070. bool NamedParametersFound = false;
  4071. bool PositionalParametersFound = false;
  4072. // Look at the body of the macro for use of both the named parameters and what
  4073. // are likely to be positional parameters. This is what expandMacro() is
  4074. // doing when it finds the parameters in the body.
  4075. while (!Body.empty()) {
  4076. // Scan for the next possible parameter.
  4077. std::size_t End = Body.size(), Pos = 0;
  4078. for (; Pos != End; ++Pos) {
  4079. // Check for a substitution or escape.
  4080. // This macro is defined with parameters, look for \foo, \bar, etc.
  4081. if (Body[Pos] == '\\' && Pos + 1 != End)
  4082. break;
  4083. // This macro should have parameters, but look for $0, $1, ..., $n too.
  4084. if (Body[Pos] != '$' || Pos + 1 == End)
  4085. continue;
  4086. char Next = Body[Pos + 1];
  4087. if (Next == '$' || Next == 'n' ||
  4088. isdigit(static_cast<unsigned char>(Next)))
  4089. break;
  4090. }
  4091. // Check if we reached the end.
  4092. if (Pos == End)
  4093. break;
  4094. if (Body[Pos] == '$') {
  4095. switch (Body[Pos + 1]) {
  4096. // $$ => $
  4097. case '$':
  4098. break;
  4099. // $n => number of arguments
  4100. case 'n':
  4101. PositionalParametersFound = true;
  4102. break;
  4103. // $[0-9] => argument
  4104. default: {
  4105. PositionalParametersFound = true;
  4106. break;
  4107. }
  4108. }
  4109. Pos += 2;
  4110. } else {
  4111. unsigned I = Pos + 1;
  4112. while (isIdentifierChar(Body[I]) && I + 1 != End)
  4113. ++I;
  4114. const char *Begin = Body.data() + Pos + 1;
  4115. StringRef Argument(Begin, I - (Pos + 1));
  4116. unsigned Index = 0;
  4117. for (; Index < NParameters; ++Index)
  4118. if (Parameters[Index].Name == Argument)
  4119. break;
  4120. if (Index == NParameters) {
  4121. if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
  4122. Pos += 3;
  4123. else {
  4124. Pos = I;
  4125. }
  4126. } else {
  4127. NamedParametersFound = true;
  4128. Pos += 1 + Argument.size();
  4129. }
  4130. }
  4131. // Update the scan point.
  4132. Body = Body.substr(Pos);
  4133. }
  4134. if (!NamedParametersFound && PositionalParametersFound)
  4135. Warning(DirectiveLoc, "macro defined with named parameters which are not "
  4136. "used in macro body, possible positional parameter "
  4137. "found in body which will have no effect");
  4138. }
  4139. /// parseDirectiveExitMacro
  4140. /// ::= .exitm
  4141. bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
  4142. if (parseEOL())
  4143. return true;
  4144. if (!isInsideMacroInstantiation())
  4145. return TokError("unexpected '" + Directive + "' in file, "
  4146. "no current macro definition");
  4147. // Exit all conditionals that are active in the current macro.
  4148. while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
  4149. TheCondState = TheCondStack.back();
  4150. TheCondStack.pop_back();
  4151. }
  4152. handleMacroExit();
  4153. return false;
  4154. }
  4155. /// parseDirectiveEndMacro
  4156. /// ::= .endm
  4157. /// ::= .endmacro
  4158. bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
  4159. if (getLexer().isNot(AsmToken::EndOfStatement))
  4160. return TokError("unexpected token in '" + Directive + "' directive");
  4161. // If we are inside a macro instantiation, terminate the current
  4162. // instantiation.
  4163. if (isInsideMacroInstantiation()) {
  4164. handleMacroExit();
  4165. return false;
  4166. }
  4167. // Otherwise, this .endmacro is a stray entry in the file; well formed
  4168. // .endmacro directives are handled during the macro definition parsing.
  4169. return TokError("unexpected '" + Directive + "' in file, "
  4170. "no current macro definition");
  4171. }
  4172. /// parseDirectivePurgeMacro
  4173. /// ::= .purgem name
  4174. bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
  4175. StringRef Name;
  4176. SMLoc Loc;
  4177. if (parseTokenLoc(Loc) ||
  4178. check(parseIdentifier(Name), Loc,
  4179. "expected identifier in '.purgem' directive") ||
  4180. parseEOL())
  4181. return true;
  4182. if (!getContext().lookupMacro(Name))
  4183. return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
  4184. getContext().undefineMacro(Name);
  4185. DEBUG_WITH_TYPE("asm-macros", dbgs()
  4186. << "Un-defining macro: " << Name << "\n");
  4187. return false;
  4188. }
  4189. /// parseDirectiveBundleAlignMode
  4190. /// ::= {.bundle_align_mode} expression
  4191. bool AsmParser::parseDirectiveBundleAlignMode() {
  4192. // Expect a single argument: an expression that evaluates to a constant
  4193. // in the inclusive range 0-30.
  4194. SMLoc ExprLoc = getLexer().getLoc();
  4195. int64_t AlignSizePow2;
  4196. if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
  4197. parseEOL() ||
  4198. check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
  4199. "invalid bundle alignment size (expected between 0 and 30)"))
  4200. return true;
  4201. getStreamer().emitBundleAlignMode(Align(1ULL << AlignSizePow2));
  4202. return false;
  4203. }
  4204. /// parseDirectiveBundleLock
  4205. /// ::= {.bundle_lock} [align_to_end]
  4206. bool AsmParser::parseDirectiveBundleLock() {
  4207. if (checkForValidSection())
  4208. return true;
  4209. bool AlignToEnd = false;
  4210. StringRef Option;
  4211. SMLoc Loc = getTok().getLoc();
  4212. const char *kInvalidOptionError =
  4213. "invalid option for '.bundle_lock' directive";
  4214. if (!parseOptionalToken(AsmToken::EndOfStatement)) {
  4215. if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
  4216. check(Option != "align_to_end", Loc, kInvalidOptionError) || parseEOL())
  4217. return true;
  4218. AlignToEnd = true;
  4219. }
  4220. getStreamer().emitBundleLock(AlignToEnd);
  4221. return false;
  4222. }
  4223. /// parseDirectiveBundleLock
  4224. /// ::= {.bundle_lock}
  4225. bool AsmParser::parseDirectiveBundleUnlock() {
  4226. if (checkForValidSection() || parseEOL())
  4227. return true;
  4228. getStreamer().emitBundleUnlock();
  4229. return false;
  4230. }
  4231. /// parseDirectiveSpace
  4232. /// ::= (.skip | .space) expression [ , expression ]
  4233. bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
  4234. SMLoc NumBytesLoc = Lexer.getLoc();
  4235. const MCExpr *NumBytes;
  4236. if (checkForValidSection() || parseExpression(NumBytes))
  4237. return true;
  4238. int64_t FillExpr = 0;
  4239. if (parseOptionalToken(AsmToken::Comma))
  4240. if (parseAbsoluteExpression(FillExpr))
  4241. return true;
  4242. if (parseEOL())
  4243. return true;
  4244. // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
  4245. getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
  4246. return false;
  4247. }
  4248. /// parseDirectiveDCB
  4249. /// ::= .dcb.{b, l, w} expression, expression
  4250. bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
  4251. SMLoc NumValuesLoc = Lexer.getLoc();
  4252. int64_t NumValues;
  4253. if (checkForValidSection() || parseAbsoluteExpression(NumValues))
  4254. return true;
  4255. if (NumValues < 0) {
  4256. Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
  4257. return false;
  4258. }
  4259. if (parseComma())
  4260. return true;
  4261. const MCExpr *Value;
  4262. SMLoc ExprLoc = getLexer().getLoc();
  4263. if (parseExpression(Value))
  4264. return true;
  4265. // Special case constant expressions to match code generator.
  4266. if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
  4267. assert(Size <= 8 && "Invalid size");
  4268. uint64_t IntValue = MCE->getValue();
  4269. if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
  4270. return Error(ExprLoc, "literal value out of range for directive");
  4271. for (uint64_t i = 0, e = NumValues; i != e; ++i)
  4272. getStreamer().emitIntValue(IntValue, Size);
  4273. } else {
  4274. for (uint64_t i = 0, e = NumValues; i != e; ++i)
  4275. getStreamer().emitValue(Value, Size, ExprLoc);
  4276. }
  4277. return parseEOL();
  4278. }
  4279. /// parseDirectiveRealDCB
  4280. /// ::= .dcb.{d, s} expression, expression
  4281. bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
  4282. SMLoc NumValuesLoc = Lexer.getLoc();
  4283. int64_t NumValues;
  4284. if (checkForValidSection() || parseAbsoluteExpression(NumValues))
  4285. return true;
  4286. if (NumValues < 0) {
  4287. Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
  4288. return false;
  4289. }
  4290. if (parseComma())
  4291. return true;
  4292. APInt AsInt;
  4293. if (parseRealValue(Semantics, AsInt) || parseEOL())
  4294. return true;
  4295. for (uint64_t i = 0, e = NumValues; i != e; ++i)
  4296. getStreamer().emitIntValue(AsInt.getLimitedValue(),
  4297. AsInt.getBitWidth() / 8);
  4298. return false;
  4299. }
  4300. /// parseDirectiveDS
  4301. /// ::= .ds.{b, d, l, p, s, w, x} expression
  4302. bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
  4303. SMLoc NumValuesLoc = Lexer.getLoc();
  4304. int64_t NumValues;
  4305. if (checkForValidSection() || parseAbsoluteExpression(NumValues) ||
  4306. parseEOL())
  4307. return true;
  4308. if (NumValues < 0) {
  4309. Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
  4310. return false;
  4311. }
  4312. for (uint64_t i = 0, e = NumValues; i != e; ++i)
  4313. getStreamer().emitFill(Size, 0);
  4314. return false;
  4315. }
  4316. /// parseDirectiveLEB128
  4317. /// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
  4318. bool AsmParser::parseDirectiveLEB128(bool Signed) {
  4319. if (checkForValidSection())
  4320. return true;
  4321. auto parseOp = [&]() -> bool {
  4322. const MCExpr *Value;
  4323. if (parseExpression(Value))
  4324. return true;
  4325. if (Signed)
  4326. getStreamer().emitSLEB128Value(Value);
  4327. else
  4328. getStreamer().emitULEB128Value(Value);
  4329. return false;
  4330. };
  4331. return parseMany(parseOp);
  4332. }
  4333. /// parseDirectiveSymbolAttribute
  4334. /// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
  4335. bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
  4336. auto parseOp = [&]() -> bool {
  4337. StringRef Name;
  4338. SMLoc Loc = getTok().getLoc();
  4339. if (parseIdentifier(Name))
  4340. return Error(Loc, "expected identifier");
  4341. if (discardLTOSymbol(Name))
  4342. return false;
  4343. MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
  4344. // Assembler local symbols don't make any sense here, except for directives
  4345. // that the symbol should be tagged.
  4346. if (Sym->isTemporary() && Attr != MCSA_Memtag)
  4347. return Error(Loc, "non-local symbol required");
  4348. if (!getStreamer().emitSymbolAttribute(Sym, Attr))
  4349. return Error(Loc, "unable to emit symbol attribute");
  4350. return false;
  4351. };
  4352. return parseMany(parseOp);
  4353. }
  4354. /// parseDirectiveComm
  4355. /// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
  4356. bool AsmParser::parseDirectiveComm(bool IsLocal) {
  4357. if (checkForValidSection())
  4358. return true;
  4359. SMLoc IDLoc = getLexer().getLoc();
  4360. StringRef Name;
  4361. if (parseIdentifier(Name))
  4362. return TokError("expected identifier in directive");
  4363. // Handle the identifier as the key symbol.
  4364. MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
  4365. if (parseComma())
  4366. return true;
  4367. int64_t Size;
  4368. SMLoc SizeLoc = getLexer().getLoc();
  4369. if (parseAbsoluteExpression(Size))
  4370. return true;
  4371. int64_t Pow2Alignment = 0;
  4372. SMLoc Pow2AlignmentLoc;
  4373. if (getLexer().is(AsmToken::Comma)) {
  4374. Lex();
  4375. Pow2AlignmentLoc = getLexer().getLoc();
  4376. if (parseAbsoluteExpression(Pow2Alignment))
  4377. return true;
  4378. LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
  4379. if (IsLocal && LCOMM == LCOMM::NoAlignment)
  4380. return Error(Pow2AlignmentLoc, "alignment not supported on this target");
  4381. // If this target takes alignments in bytes (not log) validate and convert.
  4382. if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
  4383. (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
  4384. if (!isPowerOf2_64(Pow2Alignment))
  4385. return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
  4386. Pow2Alignment = Log2_64(Pow2Alignment);
  4387. }
  4388. }
  4389. if (parseEOL())
  4390. return true;
  4391. // NOTE: a size of zero for a .comm should create a undefined symbol
  4392. // but a size of .lcomm creates a bss symbol of size zero.
  4393. if (Size < 0)
  4394. return Error(SizeLoc, "size must be non-negative");
  4395. Sym->redefineIfPossible();
  4396. if (!Sym->isUndefined())
  4397. return Error(IDLoc, "invalid symbol redefinition");
  4398. // Create the Symbol as a common or local common with Size and Pow2Alignment
  4399. if (IsLocal) {
  4400. getStreamer().emitLocalCommonSymbol(Sym, Size,
  4401. Align(1ULL << Pow2Alignment));
  4402. return false;
  4403. }
  4404. getStreamer().emitCommonSymbol(Sym, Size, Align(1ULL << Pow2Alignment));
  4405. return false;
  4406. }
  4407. /// parseDirectiveAbort
  4408. /// ::= .abort [... message ...]
  4409. bool AsmParser::parseDirectiveAbort() {
  4410. // FIXME: Use loc from directive.
  4411. SMLoc Loc = getLexer().getLoc();
  4412. StringRef Str = parseStringToEndOfStatement();
  4413. if (parseEOL())
  4414. return true;
  4415. if (Str.empty())
  4416. return Error(Loc, ".abort detected. Assembly stopping.");
  4417. else
  4418. return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
  4419. // FIXME: Actually abort assembly here.
  4420. return false;
  4421. }
  4422. /// parseDirectiveInclude
  4423. /// ::= .include "filename"
  4424. bool AsmParser::parseDirectiveInclude() {
  4425. // Allow the strings to have escaped octal character sequence.
  4426. std::string Filename;
  4427. SMLoc IncludeLoc = getTok().getLoc();
  4428. if (check(getTok().isNot(AsmToken::String),
  4429. "expected string in '.include' directive") ||
  4430. parseEscapedString(Filename) ||
  4431. check(getTok().isNot(AsmToken::EndOfStatement),
  4432. "unexpected token in '.include' directive") ||
  4433. // Attempt to switch the lexer to the included file before consuming the
  4434. // end of statement to avoid losing it when we switch.
  4435. check(enterIncludeFile(Filename), IncludeLoc,
  4436. "Could not find include file '" + Filename + "'"))
  4437. return true;
  4438. return false;
  4439. }
  4440. /// parseDirectiveIncbin
  4441. /// ::= .incbin "filename" [ , skip [ , count ] ]
  4442. bool AsmParser::parseDirectiveIncbin() {
  4443. // Allow the strings to have escaped octal character sequence.
  4444. std::string Filename;
  4445. SMLoc IncbinLoc = getTok().getLoc();
  4446. if (check(getTok().isNot(AsmToken::String),
  4447. "expected string in '.incbin' directive") ||
  4448. parseEscapedString(Filename))
  4449. return true;
  4450. int64_t Skip = 0;
  4451. const MCExpr *Count = nullptr;
  4452. SMLoc SkipLoc, CountLoc;
  4453. if (parseOptionalToken(AsmToken::Comma)) {
  4454. // The skip expression can be omitted while specifying the count, e.g:
  4455. // .incbin "filename",,4
  4456. if (getTok().isNot(AsmToken::Comma)) {
  4457. if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
  4458. return true;
  4459. }
  4460. if (parseOptionalToken(AsmToken::Comma)) {
  4461. CountLoc = getTok().getLoc();
  4462. if (parseExpression(Count))
  4463. return true;
  4464. }
  4465. }
  4466. if (parseEOL())
  4467. return true;
  4468. if (check(Skip < 0, SkipLoc, "skip is negative"))
  4469. return true;
  4470. // Attempt to process the included file.
  4471. if (processIncbinFile(Filename, Skip, Count, CountLoc))
  4472. return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
  4473. return false;
  4474. }
  4475. /// parseDirectiveIf
  4476. /// ::= .if{,eq,ge,gt,le,lt,ne} expression
  4477. bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
  4478. TheCondStack.push_back(TheCondState);
  4479. TheCondState.TheCond = AsmCond::IfCond;
  4480. if (TheCondState.Ignore) {
  4481. eatToEndOfStatement();
  4482. } else {
  4483. int64_t ExprValue;
  4484. if (parseAbsoluteExpression(ExprValue) || parseEOL())
  4485. return true;
  4486. switch (DirKind) {
  4487. default:
  4488. llvm_unreachable("unsupported directive");
  4489. case DK_IF:
  4490. case DK_IFNE:
  4491. break;
  4492. case DK_IFEQ:
  4493. ExprValue = ExprValue == 0;
  4494. break;
  4495. case DK_IFGE:
  4496. ExprValue = ExprValue >= 0;
  4497. break;
  4498. case DK_IFGT:
  4499. ExprValue = ExprValue > 0;
  4500. break;
  4501. case DK_IFLE:
  4502. ExprValue = ExprValue <= 0;
  4503. break;
  4504. case DK_IFLT:
  4505. ExprValue = ExprValue < 0;
  4506. break;
  4507. }
  4508. TheCondState.CondMet = ExprValue;
  4509. TheCondState.Ignore = !TheCondState.CondMet;
  4510. }
  4511. return false;
  4512. }
  4513. /// parseDirectiveIfb
  4514. /// ::= .ifb string
  4515. bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
  4516. TheCondStack.push_back(TheCondState);
  4517. TheCondState.TheCond = AsmCond::IfCond;
  4518. if (TheCondState.Ignore) {
  4519. eatToEndOfStatement();
  4520. } else {
  4521. StringRef Str = parseStringToEndOfStatement();
  4522. if (parseEOL())
  4523. return true;
  4524. TheCondState.CondMet = ExpectBlank == Str.empty();
  4525. TheCondState.Ignore = !TheCondState.CondMet;
  4526. }
  4527. return false;
  4528. }
  4529. /// parseDirectiveIfc
  4530. /// ::= .ifc string1, string2
  4531. /// ::= .ifnc string1, string2
  4532. bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
  4533. TheCondStack.push_back(TheCondState);
  4534. TheCondState.TheCond = AsmCond::IfCond;
  4535. if (TheCondState.Ignore) {
  4536. eatToEndOfStatement();
  4537. } else {
  4538. StringRef Str1 = parseStringToComma();
  4539. if (parseComma())
  4540. return true;
  4541. StringRef Str2 = parseStringToEndOfStatement();
  4542. if (parseEOL())
  4543. return true;
  4544. TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
  4545. TheCondState.Ignore = !TheCondState.CondMet;
  4546. }
  4547. return false;
  4548. }
  4549. /// parseDirectiveIfeqs
  4550. /// ::= .ifeqs string1, string2
  4551. bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
  4552. if (Lexer.isNot(AsmToken::String)) {
  4553. if (ExpectEqual)
  4554. return TokError("expected string parameter for '.ifeqs' directive");
  4555. return TokError("expected string parameter for '.ifnes' directive");
  4556. }
  4557. StringRef String1 = getTok().getStringContents();
  4558. Lex();
  4559. if (Lexer.isNot(AsmToken::Comma)) {
  4560. if (ExpectEqual)
  4561. return TokError(
  4562. "expected comma after first string for '.ifeqs' directive");
  4563. return TokError("expected comma after first string for '.ifnes' directive");
  4564. }
  4565. Lex();
  4566. if (Lexer.isNot(AsmToken::String)) {
  4567. if (ExpectEqual)
  4568. return TokError("expected string parameter for '.ifeqs' directive");
  4569. return TokError("expected string parameter for '.ifnes' directive");
  4570. }
  4571. StringRef String2 = getTok().getStringContents();
  4572. Lex();
  4573. TheCondStack.push_back(TheCondState);
  4574. TheCondState.TheCond = AsmCond::IfCond;
  4575. TheCondState.CondMet = ExpectEqual == (String1 == String2);
  4576. TheCondState.Ignore = !TheCondState.CondMet;
  4577. return false;
  4578. }
  4579. /// parseDirectiveIfdef
  4580. /// ::= .ifdef symbol
  4581. bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
  4582. StringRef Name;
  4583. TheCondStack.push_back(TheCondState);
  4584. TheCondState.TheCond = AsmCond::IfCond;
  4585. if (TheCondState.Ignore) {
  4586. eatToEndOfStatement();
  4587. } else {
  4588. if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
  4589. parseEOL())
  4590. return true;
  4591. MCSymbol *Sym = getContext().lookupSymbol(Name);
  4592. if (expect_defined)
  4593. TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
  4594. else
  4595. TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
  4596. TheCondState.Ignore = !TheCondState.CondMet;
  4597. }
  4598. return false;
  4599. }
  4600. /// parseDirectiveElseIf
  4601. /// ::= .elseif expression
  4602. bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
  4603. if (TheCondState.TheCond != AsmCond::IfCond &&
  4604. TheCondState.TheCond != AsmCond::ElseIfCond)
  4605. return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
  4606. " .if or an .elseif");
  4607. TheCondState.TheCond = AsmCond::ElseIfCond;
  4608. bool LastIgnoreState = false;
  4609. if (!TheCondStack.empty())
  4610. LastIgnoreState = TheCondStack.back().Ignore;
  4611. if (LastIgnoreState || TheCondState.CondMet) {
  4612. TheCondState.Ignore = true;
  4613. eatToEndOfStatement();
  4614. } else {
  4615. int64_t ExprValue;
  4616. if (parseAbsoluteExpression(ExprValue))
  4617. return true;
  4618. if (parseEOL())
  4619. return true;
  4620. TheCondState.CondMet = ExprValue;
  4621. TheCondState.Ignore = !TheCondState.CondMet;
  4622. }
  4623. return false;
  4624. }
  4625. /// parseDirectiveElse
  4626. /// ::= .else
  4627. bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
  4628. if (parseEOL())
  4629. return true;
  4630. if (TheCondState.TheCond != AsmCond::IfCond &&
  4631. TheCondState.TheCond != AsmCond::ElseIfCond)
  4632. return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
  4633. " an .if or an .elseif");
  4634. TheCondState.TheCond = AsmCond::ElseCond;
  4635. bool LastIgnoreState = false;
  4636. if (!TheCondStack.empty())
  4637. LastIgnoreState = TheCondStack.back().Ignore;
  4638. if (LastIgnoreState || TheCondState.CondMet)
  4639. TheCondState.Ignore = true;
  4640. else
  4641. TheCondState.Ignore = false;
  4642. return false;
  4643. }
  4644. /// parseDirectiveEnd
  4645. /// ::= .end
  4646. bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
  4647. if (parseEOL())
  4648. return true;
  4649. while (Lexer.isNot(AsmToken::Eof))
  4650. Lexer.Lex();
  4651. return false;
  4652. }
  4653. /// parseDirectiveError
  4654. /// ::= .err
  4655. /// ::= .error [string]
  4656. bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
  4657. if (!TheCondStack.empty()) {
  4658. if (TheCondStack.back().Ignore) {
  4659. eatToEndOfStatement();
  4660. return false;
  4661. }
  4662. }
  4663. if (!WithMessage)
  4664. return Error(L, ".err encountered");
  4665. StringRef Message = ".error directive invoked in source file";
  4666. if (Lexer.isNot(AsmToken::EndOfStatement)) {
  4667. if (Lexer.isNot(AsmToken::String))
  4668. return TokError(".error argument must be a string");
  4669. Message = getTok().getStringContents();
  4670. Lex();
  4671. }
  4672. return Error(L, Message);
  4673. }
  4674. /// parseDirectiveWarning
  4675. /// ::= .warning [string]
  4676. bool AsmParser::parseDirectiveWarning(SMLoc L) {
  4677. if (!TheCondStack.empty()) {
  4678. if (TheCondStack.back().Ignore) {
  4679. eatToEndOfStatement();
  4680. return false;
  4681. }
  4682. }
  4683. StringRef Message = ".warning directive invoked in source file";
  4684. if (!parseOptionalToken(AsmToken::EndOfStatement)) {
  4685. if (Lexer.isNot(AsmToken::String))
  4686. return TokError(".warning argument must be a string");
  4687. Message = getTok().getStringContents();
  4688. Lex();
  4689. if (parseEOL())
  4690. return true;
  4691. }
  4692. return Warning(L, Message);
  4693. }
  4694. /// parseDirectiveEndIf
  4695. /// ::= .endif
  4696. bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
  4697. if (parseEOL())
  4698. return true;
  4699. if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
  4700. return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
  4701. "an .if or .else");
  4702. if (!TheCondStack.empty()) {
  4703. TheCondState = TheCondStack.back();
  4704. TheCondStack.pop_back();
  4705. }
  4706. return false;
  4707. }
  4708. void AsmParser::initializeDirectiveKindMap() {
  4709. /* Lookup will be done with the directive
  4710. * converted to lower case, so all these
  4711. * keys should be lower case.
  4712. * (target specific directives are handled
  4713. * elsewhere)
  4714. */
  4715. DirectiveKindMap[".set"] = DK_SET;
  4716. DirectiveKindMap[".equ"] = DK_EQU;
  4717. DirectiveKindMap[".equiv"] = DK_EQUIV;
  4718. DirectiveKindMap[".ascii"] = DK_ASCII;
  4719. DirectiveKindMap[".asciz"] = DK_ASCIZ;
  4720. DirectiveKindMap[".string"] = DK_STRING;
  4721. DirectiveKindMap[".byte"] = DK_BYTE;
  4722. DirectiveKindMap[".short"] = DK_SHORT;
  4723. DirectiveKindMap[".value"] = DK_VALUE;
  4724. DirectiveKindMap[".2byte"] = DK_2BYTE;
  4725. DirectiveKindMap[".long"] = DK_LONG;
  4726. DirectiveKindMap[".int"] = DK_INT;
  4727. DirectiveKindMap[".4byte"] = DK_4BYTE;
  4728. DirectiveKindMap[".quad"] = DK_QUAD;
  4729. DirectiveKindMap[".8byte"] = DK_8BYTE;
  4730. DirectiveKindMap[".octa"] = DK_OCTA;
  4731. DirectiveKindMap[".single"] = DK_SINGLE;
  4732. DirectiveKindMap[".float"] = DK_FLOAT;
  4733. DirectiveKindMap[".double"] = DK_DOUBLE;
  4734. DirectiveKindMap[".align"] = DK_ALIGN;
  4735. DirectiveKindMap[".align32"] = DK_ALIGN32;
  4736. DirectiveKindMap[".balign"] = DK_BALIGN;
  4737. DirectiveKindMap[".balignw"] = DK_BALIGNW;
  4738. DirectiveKindMap[".balignl"] = DK_BALIGNL;
  4739. DirectiveKindMap[".p2align"] = DK_P2ALIGN;
  4740. DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
  4741. DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
  4742. DirectiveKindMap[".org"] = DK_ORG;
  4743. DirectiveKindMap[".fill"] = DK_FILL;
  4744. DirectiveKindMap[".zero"] = DK_ZERO;
  4745. DirectiveKindMap[".extern"] = DK_EXTERN;
  4746. DirectiveKindMap[".globl"] = DK_GLOBL;
  4747. DirectiveKindMap[".global"] = DK_GLOBAL;
  4748. DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
  4749. DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
  4750. DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
  4751. DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
  4752. DirectiveKindMap[".reference"] = DK_REFERENCE;
  4753. DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
  4754. DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
  4755. DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
  4756. DirectiveKindMap[".cold"] = DK_COLD;
  4757. DirectiveKindMap[".comm"] = DK_COMM;
  4758. DirectiveKindMap[".common"] = DK_COMMON;
  4759. DirectiveKindMap[".lcomm"] = DK_LCOMM;
  4760. DirectiveKindMap[".abort"] = DK_ABORT;
  4761. DirectiveKindMap[".include"] = DK_INCLUDE;
  4762. DirectiveKindMap[".incbin"] = DK_INCBIN;
  4763. DirectiveKindMap[".code16"] = DK_CODE16;
  4764. DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
  4765. DirectiveKindMap[".rept"] = DK_REPT;
  4766. DirectiveKindMap[".rep"] = DK_REPT;
  4767. DirectiveKindMap[".irp"] = DK_IRP;
  4768. DirectiveKindMap[".irpc"] = DK_IRPC;
  4769. DirectiveKindMap[".endr"] = DK_ENDR;
  4770. DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
  4771. DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
  4772. DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
  4773. DirectiveKindMap[".if"] = DK_IF;
  4774. DirectiveKindMap[".ifeq"] = DK_IFEQ;
  4775. DirectiveKindMap[".ifge"] = DK_IFGE;
  4776. DirectiveKindMap[".ifgt"] = DK_IFGT;
  4777. DirectiveKindMap[".ifle"] = DK_IFLE;
  4778. DirectiveKindMap[".iflt"] = DK_IFLT;
  4779. DirectiveKindMap[".ifne"] = DK_IFNE;
  4780. DirectiveKindMap[".ifb"] = DK_IFB;
  4781. DirectiveKindMap[".ifnb"] = DK_IFNB;
  4782. DirectiveKindMap[".ifc"] = DK_IFC;
  4783. DirectiveKindMap[".ifeqs"] = DK_IFEQS;
  4784. DirectiveKindMap[".ifnc"] = DK_IFNC;
  4785. DirectiveKindMap[".ifnes"] = DK_IFNES;
  4786. DirectiveKindMap[".ifdef"] = DK_IFDEF;
  4787. DirectiveKindMap[".ifndef"] = DK_IFNDEF;
  4788. DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
  4789. DirectiveKindMap[".elseif"] = DK_ELSEIF;
  4790. DirectiveKindMap[".else"] = DK_ELSE;
  4791. DirectiveKindMap[".end"] = DK_END;
  4792. DirectiveKindMap[".endif"] = DK_ENDIF;
  4793. DirectiveKindMap[".skip"] = DK_SKIP;
  4794. DirectiveKindMap[".space"] = DK_SPACE;
  4795. DirectiveKindMap[".file"] = DK_FILE;
  4796. DirectiveKindMap[".line"] = DK_LINE;
  4797. DirectiveKindMap[".loc"] = DK_LOC;
  4798. DirectiveKindMap[".stabs"] = DK_STABS;
  4799. DirectiveKindMap[".cv_file"] = DK_CV_FILE;
  4800. DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
  4801. DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
  4802. DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
  4803. DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
  4804. DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
  4805. DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
  4806. DirectiveKindMap[".cv_string"] = DK_CV_STRING;
  4807. DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
  4808. DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
  4809. DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
  4810. DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
  4811. DirectiveKindMap[".sleb128"] = DK_SLEB128;
  4812. DirectiveKindMap[".uleb128"] = DK_ULEB128;
  4813. DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
  4814. DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
  4815. DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
  4816. DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
  4817. DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
  4818. DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
  4819. DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
  4820. DirectiveKindMap[".cfi_llvm_def_aspace_cfa"] = DK_CFI_LLVM_DEF_ASPACE_CFA;
  4821. DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
  4822. DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
  4823. DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
  4824. DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
  4825. DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
  4826. DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
  4827. DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
  4828. DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
  4829. DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
  4830. DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
  4831. DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
  4832. DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
  4833. DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
  4834. DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
  4835. DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
  4836. DirectiveKindMap[".cfi_mte_tagged_frame"] = DK_CFI_MTE_TAGGED_FRAME;
  4837. DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
  4838. DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
  4839. DirectiveKindMap[".macro"] = DK_MACRO;
  4840. DirectiveKindMap[".exitm"] = DK_EXITM;
  4841. DirectiveKindMap[".endm"] = DK_ENDM;
  4842. DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
  4843. DirectiveKindMap[".purgem"] = DK_PURGEM;
  4844. DirectiveKindMap[".err"] = DK_ERR;
  4845. DirectiveKindMap[".error"] = DK_ERROR;
  4846. DirectiveKindMap[".warning"] = DK_WARNING;
  4847. DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
  4848. DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
  4849. DirectiveKindMap[".reloc"] = DK_RELOC;
  4850. DirectiveKindMap[".dc"] = DK_DC;
  4851. DirectiveKindMap[".dc.a"] = DK_DC_A;
  4852. DirectiveKindMap[".dc.b"] = DK_DC_B;
  4853. DirectiveKindMap[".dc.d"] = DK_DC_D;
  4854. DirectiveKindMap[".dc.l"] = DK_DC_L;
  4855. DirectiveKindMap[".dc.s"] = DK_DC_S;
  4856. DirectiveKindMap[".dc.w"] = DK_DC_W;
  4857. DirectiveKindMap[".dc.x"] = DK_DC_X;
  4858. DirectiveKindMap[".dcb"] = DK_DCB;
  4859. DirectiveKindMap[".dcb.b"] = DK_DCB_B;
  4860. DirectiveKindMap[".dcb.d"] = DK_DCB_D;
  4861. DirectiveKindMap[".dcb.l"] = DK_DCB_L;
  4862. DirectiveKindMap[".dcb.s"] = DK_DCB_S;
  4863. DirectiveKindMap[".dcb.w"] = DK_DCB_W;
  4864. DirectiveKindMap[".dcb.x"] = DK_DCB_X;
  4865. DirectiveKindMap[".ds"] = DK_DS;
  4866. DirectiveKindMap[".ds.b"] = DK_DS_B;
  4867. DirectiveKindMap[".ds.d"] = DK_DS_D;
  4868. DirectiveKindMap[".ds.l"] = DK_DS_L;
  4869. DirectiveKindMap[".ds.p"] = DK_DS_P;
  4870. DirectiveKindMap[".ds.s"] = DK_DS_S;
  4871. DirectiveKindMap[".ds.w"] = DK_DS_W;
  4872. DirectiveKindMap[".ds.x"] = DK_DS_X;
  4873. DirectiveKindMap[".print"] = DK_PRINT;
  4874. DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
  4875. DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
  4876. DirectiveKindMap[".pseudoprobe"] = DK_PSEUDO_PROBE;
  4877. DirectiveKindMap[".lto_discard"] = DK_LTO_DISCARD;
  4878. DirectiveKindMap[".lto_set_conditional"] = DK_LTO_SET_CONDITIONAL;
  4879. DirectiveKindMap[".memtag"] = DK_MEMTAG;
  4880. }
  4881. MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
  4882. AsmToken EndToken, StartToken = getTok();
  4883. unsigned NestLevel = 0;
  4884. while (true) {
  4885. // Check whether we have reached the end of the file.
  4886. if (getLexer().is(AsmToken::Eof)) {
  4887. printError(DirectiveLoc, "no matching '.endr' in definition");
  4888. return nullptr;
  4889. }
  4890. if (Lexer.is(AsmToken::Identifier) &&
  4891. (getTok().getIdentifier() == ".rep" ||
  4892. getTok().getIdentifier() == ".rept" ||
  4893. getTok().getIdentifier() == ".irp" ||
  4894. getTok().getIdentifier() == ".irpc")) {
  4895. ++NestLevel;
  4896. }
  4897. // Otherwise, check whether we have reached the .endr.
  4898. if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
  4899. if (NestLevel == 0) {
  4900. EndToken = getTok();
  4901. Lex();
  4902. if (Lexer.isNot(AsmToken::EndOfStatement)) {
  4903. printError(getTok().getLoc(),
  4904. "unexpected token in '.endr' directive");
  4905. return nullptr;
  4906. }
  4907. break;
  4908. }
  4909. --NestLevel;
  4910. }
  4911. // Otherwise, scan till the end of the statement.
  4912. eatToEndOfStatement();
  4913. }
  4914. const char *BodyStart = StartToken.getLoc().getPointer();
  4915. const char *BodyEnd = EndToken.getLoc().getPointer();
  4916. StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
  4917. // We Are Anonymous.
  4918. MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
  4919. return &MacroLikeBodies.back();
  4920. }
  4921. void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
  4922. raw_svector_ostream &OS) {
  4923. OS << ".endr\n";
  4924. std::unique_ptr<MemoryBuffer> Instantiation =
  4925. MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
  4926. // Create the macro instantiation object and add to the current macro
  4927. // instantiation stack.
  4928. MacroInstantiation *MI = new MacroInstantiation{
  4929. DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size()};
  4930. ActiveMacros.push_back(MI);
  4931. // Jump to the macro instantiation and prime the lexer.
  4932. CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
  4933. Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
  4934. Lex();
  4935. }
  4936. /// parseDirectiveRept
  4937. /// ::= .rep | .rept count
  4938. bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
  4939. const MCExpr *CountExpr;
  4940. SMLoc CountLoc = getTok().getLoc();
  4941. if (parseExpression(CountExpr))
  4942. return true;
  4943. int64_t Count;
  4944. if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
  4945. return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
  4946. }
  4947. if (check(Count < 0, CountLoc, "Count is negative") || parseEOL())
  4948. return true;
  4949. // Lex the rept definition.
  4950. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
  4951. if (!M)
  4952. return true;
  4953. // Macro instantiation is lexical, unfortunately. We construct a new buffer
  4954. // to hold the macro body with substitutions.
  4955. SmallString<256> Buf;
  4956. raw_svector_ostream OS(Buf);
  4957. while (Count--) {
  4958. // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
  4959. if (expandMacro(OS, M->Body, std::nullopt, std::nullopt, false,
  4960. getTok().getLoc()))
  4961. return true;
  4962. }
  4963. instantiateMacroLikeBody(M, DirectiveLoc, OS);
  4964. return false;
  4965. }
  4966. /// parseDirectiveIrp
  4967. /// ::= .irp symbol,values
  4968. bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
  4969. MCAsmMacroParameter Parameter;
  4970. MCAsmMacroArguments A;
  4971. if (check(parseIdentifier(Parameter.Name),
  4972. "expected identifier in '.irp' directive") ||
  4973. parseComma() || parseMacroArguments(nullptr, A) || parseEOL())
  4974. return true;
  4975. // Lex the irp definition.
  4976. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
  4977. if (!M)
  4978. return true;
  4979. // Macro instantiation is lexical, unfortunately. We construct a new buffer
  4980. // to hold the macro body with substitutions.
  4981. SmallString<256> Buf;
  4982. raw_svector_ostream OS(Buf);
  4983. for (const MCAsmMacroArgument &Arg : A) {
  4984. // Note that the AtPseudoVariable is enabled for instantiations of .irp.
  4985. // This is undocumented, but GAS seems to support it.
  4986. if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
  4987. return true;
  4988. }
  4989. instantiateMacroLikeBody(M, DirectiveLoc, OS);
  4990. return false;
  4991. }
  4992. /// parseDirectiveIrpc
  4993. /// ::= .irpc symbol,values
  4994. bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
  4995. MCAsmMacroParameter Parameter;
  4996. MCAsmMacroArguments A;
  4997. if (check(parseIdentifier(Parameter.Name),
  4998. "expected identifier in '.irpc' directive") ||
  4999. parseComma() || parseMacroArguments(nullptr, A))
  5000. return true;
  5001. if (A.size() != 1 || A.front().size() != 1)
  5002. return TokError("unexpected token in '.irpc' directive");
  5003. if (parseEOL())
  5004. return true;
  5005. // Lex the irpc definition.
  5006. MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
  5007. if (!M)
  5008. return true;
  5009. // Macro instantiation is lexical, unfortunately. We construct a new buffer
  5010. // to hold the macro body with substitutions.
  5011. SmallString<256> Buf;
  5012. raw_svector_ostream OS(Buf);
  5013. StringRef Values = A.front().front().getString();
  5014. for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
  5015. MCAsmMacroArgument Arg;
  5016. Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
  5017. // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
  5018. // This is undocumented, but GAS seems to support it.
  5019. if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
  5020. return true;
  5021. }
  5022. instantiateMacroLikeBody(M, DirectiveLoc, OS);
  5023. return false;
  5024. }
  5025. bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
  5026. if (ActiveMacros.empty())
  5027. return TokError("unmatched '.endr' directive");
  5028. // The only .repl that should get here are the ones created by
  5029. // instantiateMacroLikeBody.
  5030. assert(getLexer().is(AsmToken::EndOfStatement));
  5031. handleMacroExit();
  5032. return false;
  5033. }
  5034. bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
  5035. size_t Len) {
  5036. const MCExpr *Value;
  5037. SMLoc ExprLoc = getLexer().getLoc();
  5038. if (parseExpression(Value))
  5039. return true;
  5040. const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
  5041. if (!MCE)
  5042. return Error(ExprLoc, "unexpected expression in _emit");
  5043. uint64_t IntValue = MCE->getValue();
  5044. if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
  5045. return Error(ExprLoc, "literal value out of range for directive");
  5046. Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
  5047. return false;
  5048. }
  5049. bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
  5050. const MCExpr *Value;
  5051. SMLoc ExprLoc = getLexer().getLoc();
  5052. if (parseExpression(Value))
  5053. return true;
  5054. const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
  5055. if (!MCE)
  5056. return Error(ExprLoc, "unexpected expression in align");
  5057. uint64_t IntValue = MCE->getValue();
  5058. if (!isPowerOf2_64(IntValue))
  5059. return Error(ExprLoc, "literal value not a power of two greater then zero");
  5060. Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
  5061. return false;
  5062. }
  5063. bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
  5064. const AsmToken StrTok = getTok();
  5065. Lex();
  5066. if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
  5067. return Error(DirectiveLoc, "expected double quoted string after .print");
  5068. if (parseEOL())
  5069. return true;
  5070. llvm::outs() << StrTok.getStringContents() << '\n';
  5071. return false;
  5072. }
  5073. bool AsmParser::parseDirectiveAddrsig() {
  5074. if (parseEOL())
  5075. return true;
  5076. getStreamer().emitAddrsig();
  5077. return false;
  5078. }
  5079. bool AsmParser::parseDirectiveAddrsigSym() {
  5080. StringRef Name;
  5081. if (check(parseIdentifier(Name), "expected identifier") || parseEOL())
  5082. return true;
  5083. MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
  5084. getStreamer().emitAddrsigSym(Sym);
  5085. return false;
  5086. }
  5087. bool AsmParser::parseDirectivePseudoProbe() {
  5088. int64_t Guid;
  5089. int64_t Index;
  5090. int64_t Type;
  5091. int64_t Attr;
  5092. if (getLexer().is(AsmToken::Integer)) {
  5093. if (parseIntToken(Guid, "unexpected token in '.pseudoprobe' directive"))
  5094. return true;
  5095. }
  5096. if (getLexer().is(AsmToken::Integer)) {
  5097. if (parseIntToken(Index, "unexpected token in '.pseudoprobe' directive"))
  5098. return true;
  5099. }
  5100. if (getLexer().is(AsmToken::Integer)) {
  5101. if (parseIntToken(Type, "unexpected token in '.pseudoprobe' directive"))
  5102. return true;
  5103. }
  5104. if (getLexer().is(AsmToken::Integer)) {
  5105. if (parseIntToken(Attr, "unexpected token in '.pseudoprobe' directive"))
  5106. return true;
  5107. }
  5108. // Parse inline stack like @ GUID:11:12 @ GUID:1:11 @ GUID:3:21
  5109. MCPseudoProbeInlineStack InlineStack;
  5110. while (getLexer().is(AsmToken::At)) {
  5111. // eat @
  5112. Lex();
  5113. int64_t CallerGuid = 0;
  5114. if (getLexer().is(AsmToken::Integer)) {
  5115. if (parseIntToken(CallerGuid,
  5116. "unexpected token in '.pseudoprobe' directive"))
  5117. return true;
  5118. }
  5119. // eat colon
  5120. if (getLexer().is(AsmToken::Colon))
  5121. Lex();
  5122. int64_t CallerProbeId = 0;
  5123. if (getLexer().is(AsmToken::Integer)) {
  5124. if (parseIntToken(CallerProbeId,
  5125. "unexpected token in '.pseudoprobe' directive"))
  5126. return true;
  5127. }
  5128. InlineSite Site(CallerGuid, CallerProbeId);
  5129. InlineStack.push_back(Site);
  5130. }
  5131. // Parse function entry name
  5132. StringRef FnName;
  5133. if (parseIdentifier(FnName))
  5134. return Error(getLexer().getLoc(), "unexpected token in '.pseudoprobe' directive");
  5135. MCSymbol *FnSym = getContext().lookupSymbol(FnName);
  5136. if (parseEOL())
  5137. return true;
  5138. getStreamer().emitPseudoProbe(Guid, Index, Type, Attr, InlineStack, FnSym);
  5139. return false;
  5140. }
  5141. /// parseDirectiveLTODiscard
  5142. /// ::= ".lto_discard" [ identifier ( , identifier )* ]
  5143. /// The LTO library emits this directive to discard non-prevailing symbols.
  5144. /// We ignore symbol assignments and attribute changes for the specified
  5145. /// symbols.
  5146. bool AsmParser::parseDirectiveLTODiscard() {
  5147. auto ParseOp = [&]() -> bool {
  5148. StringRef Name;
  5149. SMLoc Loc = getTok().getLoc();
  5150. if (parseIdentifier(Name))
  5151. return Error(Loc, "expected identifier");
  5152. LTODiscardSymbols.insert(Name);
  5153. return false;
  5154. };
  5155. LTODiscardSymbols.clear();
  5156. return parseMany(ParseOp);
  5157. }
  5158. // We are comparing pointers, but the pointers are relative to a single string.
  5159. // Thus, this should always be deterministic.
  5160. static int rewritesSort(const AsmRewrite *AsmRewriteA,
  5161. const AsmRewrite *AsmRewriteB) {
  5162. if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
  5163. return -1;
  5164. if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
  5165. return 1;
  5166. // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
  5167. // rewrite to the same location. Make sure the SizeDirective rewrite is
  5168. // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
  5169. // ensures the sort algorithm is stable.
  5170. if (AsmRewritePrecedence[AsmRewriteA->Kind] >
  5171. AsmRewritePrecedence[AsmRewriteB->Kind])
  5172. return -1;
  5173. if (AsmRewritePrecedence[AsmRewriteA->Kind] <
  5174. AsmRewritePrecedence[AsmRewriteB->Kind])
  5175. return 1;
  5176. llvm_unreachable("Unstable rewrite sort.");
  5177. }
  5178. bool AsmParser::parseMSInlineAsm(
  5179. std::string &AsmString, unsigned &NumOutputs, unsigned &NumInputs,
  5180. SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
  5181. SmallVectorImpl<std::string> &Constraints,
  5182. SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
  5183. const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
  5184. SmallVector<void *, 4> InputDecls;
  5185. SmallVector<void *, 4> OutputDecls;
  5186. SmallVector<bool, 4> InputDeclsAddressOf;
  5187. SmallVector<bool, 4> OutputDeclsAddressOf;
  5188. SmallVector<std::string, 4> InputConstraints;
  5189. SmallVector<std::string, 4> OutputConstraints;
  5190. SmallVector<unsigned, 4> ClobberRegs;
  5191. SmallVector<AsmRewrite, 4> AsmStrRewrites;
  5192. // Prime the lexer.
  5193. Lex();
  5194. // While we have input, parse each statement.
  5195. unsigned InputIdx = 0;
  5196. unsigned OutputIdx = 0;
  5197. while (getLexer().isNot(AsmToken::Eof)) {
  5198. // Parse curly braces marking block start/end
  5199. if (parseCurlyBlockScope(AsmStrRewrites))
  5200. continue;
  5201. ParseStatementInfo Info(&AsmStrRewrites);
  5202. bool StatementErr = parseStatement(Info, &SI);
  5203. if (StatementErr || Info.ParseError) {
  5204. // Emit pending errors if any exist.
  5205. printPendingErrors();
  5206. return true;
  5207. }
  5208. // No pending error should exist here.
  5209. assert(!hasPendingError() && "unexpected error from parseStatement");
  5210. if (Info.Opcode == ~0U)
  5211. continue;
  5212. const MCInstrDesc &Desc = MII->get(Info.Opcode);
  5213. // Build the list of clobbers, outputs and inputs.
  5214. for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
  5215. MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
  5216. // Register operand.
  5217. if (Operand.isReg() && !Operand.needAddressOf() &&
  5218. !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
  5219. unsigned NumDefs = Desc.getNumDefs();
  5220. // Clobber.
  5221. if (NumDefs && Operand.getMCOperandNum() < NumDefs)
  5222. ClobberRegs.push_back(Operand.getReg());
  5223. continue;
  5224. }
  5225. // Expr/Input or Output.
  5226. StringRef SymName = Operand.getSymName();
  5227. if (SymName.empty())
  5228. continue;
  5229. void *OpDecl = Operand.getOpDecl();
  5230. if (!OpDecl)
  5231. continue;
  5232. StringRef Constraint = Operand.getConstraint();
  5233. if (Operand.isImm()) {
  5234. // Offset as immediate
  5235. if (Operand.isOffsetOfLocal())
  5236. Constraint = "r";
  5237. else
  5238. Constraint = "i";
  5239. }
  5240. bool isOutput = (i == 1) && Desc.mayStore();
  5241. bool Restricted = Operand.isMemUseUpRegs();
  5242. SMLoc Start = SMLoc::getFromPointer(SymName.data());
  5243. if (isOutput) {
  5244. ++InputIdx;
  5245. OutputDecls.push_back(OpDecl);
  5246. OutputDeclsAddressOf.push_back(Operand.needAddressOf());
  5247. OutputConstraints.push_back(("=" + Constraint).str());
  5248. AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size(), 0,
  5249. Restricted);
  5250. } else {
  5251. InputDecls.push_back(OpDecl);
  5252. InputDeclsAddressOf.push_back(Operand.needAddressOf());
  5253. InputConstraints.push_back(Constraint.str());
  5254. if (Desc.operands()[i - 1].isBranchTarget())
  5255. AsmStrRewrites.emplace_back(AOK_CallInput, Start, SymName.size(), 0,
  5256. Restricted);
  5257. else
  5258. AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size(), 0,
  5259. Restricted);
  5260. }
  5261. }
  5262. // Consider implicit defs to be clobbers. Think of cpuid and push.
  5263. llvm::append_range(ClobberRegs, Desc.implicit_defs());
  5264. }
  5265. // Set the number of Outputs and Inputs.
  5266. NumOutputs = OutputDecls.size();
  5267. NumInputs = InputDecls.size();
  5268. // Set the unique clobbers.
  5269. array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
  5270. ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
  5271. ClobberRegs.end());
  5272. Clobbers.assign(ClobberRegs.size(), std::string());
  5273. for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
  5274. raw_string_ostream OS(Clobbers[I]);
  5275. IP->printRegName(OS, ClobberRegs[I]);
  5276. }
  5277. // Merge the various outputs and inputs. Output are expected first.
  5278. if (NumOutputs || NumInputs) {
  5279. unsigned NumExprs = NumOutputs + NumInputs;
  5280. OpDecls.resize(NumExprs);
  5281. Constraints.resize(NumExprs);
  5282. for (unsigned i = 0; i < NumOutputs; ++i) {
  5283. OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
  5284. Constraints[i] = OutputConstraints[i];
  5285. }
  5286. for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
  5287. OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
  5288. Constraints[j] = InputConstraints[i];
  5289. }
  5290. }
  5291. // Build the IR assembly string.
  5292. std::string AsmStringIR;
  5293. raw_string_ostream OS(AsmStringIR);
  5294. StringRef ASMString =
  5295. SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
  5296. const char *AsmStart = ASMString.begin();
  5297. const char *AsmEnd = ASMString.end();
  5298. array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
  5299. for (auto it = AsmStrRewrites.begin(); it != AsmStrRewrites.end(); ++it) {
  5300. const AsmRewrite &AR = *it;
  5301. // Check if this has already been covered by another rewrite...
  5302. if (AR.Done)
  5303. continue;
  5304. AsmRewriteKind Kind = AR.Kind;
  5305. const char *Loc = AR.Loc.getPointer();
  5306. assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
  5307. // Emit everything up to the immediate/expression.
  5308. if (unsigned Len = Loc - AsmStart)
  5309. OS << StringRef(AsmStart, Len);
  5310. // Skip the original expression.
  5311. if (Kind == AOK_Skip) {
  5312. AsmStart = Loc + AR.Len;
  5313. continue;
  5314. }
  5315. unsigned AdditionalSkip = 0;
  5316. // Rewrite expressions in $N notation.
  5317. switch (Kind) {
  5318. default:
  5319. break;
  5320. case AOK_IntelExpr:
  5321. assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
  5322. if (AR.IntelExp.NeedBracs)
  5323. OS << "[";
  5324. if (AR.IntelExp.hasBaseReg())
  5325. OS << AR.IntelExp.BaseReg;
  5326. if (AR.IntelExp.hasIndexReg())
  5327. OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
  5328. << AR.IntelExp.IndexReg;
  5329. if (AR.IntelExp.Scale > 1)
  5330. OS << " * $$" << AR.IntelExp.Scale;
  5331. if (AR.IntelExp.hasOffset()) {
  5332. if (AR.IntelExp.hasRegs())
  5333. OS << " + ";
  5334. // Fuse this rewrite with a rewrite of the offset name, if present.
  5335. StringRef OffsetName = AR.IntelExp.OffsetName;
  5336. SMLoc OffsetLoc = SMLoc::getFromPointer(AR.IntelExp.OffsetName.data());
  5337. size_t OffsetLen = OffsetName.size();
  5338. auto rewrite_it = std::find_if(
  5339. it, AsmStrRewrites.end(), [&](const AsmRewrite &FusingAR) {
  5340. return FusingAR.Loc == OffsetLoc && FusingAR.Len == OffsetLen &&
  5341. (FusingAR.Kind == AOK_Input ||
  5342. FusingAR.Kind == AOK_CallInput);
  5343. });
  5344. if (rewrite_it == AsmStrRewrites.end()) {
  5345. OS << "offset " << OffsetName;
  5346. } else if (rewrite_it->Kind == AOK_CallInput) {
  5347. OS << "${" << InputIdx++ << ":P}";
  5348. rewrite_it->Done = true;
  5349. } else {
  5350. OS << '$' << InputIdx++;
  5351. rewrite_it->Done = true;
  5352. }
  5353. }
  5354. if (AR.IntelExp.Imm || AR.IntelExp.emitImm())
  5355. OS << (AR.IntelExp.emitImm() ? "$$" : " + $$") << AR.IntelExp.Imm;
  5356. if (AR.IntelExp.NeedBracs)
  5357. OS << "]";
  5358. break;
  5359. case AOK_Label:
  5360. OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
  5361. break;
  5362. case AOK_Input:
  5363. if (AR.IntelExpRestricted)
  5364. OS << "${" << InputIdx++ << ":P}";
  5365. else
  5366. OS << '$' << InputIdx++;
  5367. break;
  5368. case AOK_CallInput:
  5369. OS << "${" << InputIdx++ << ":P}";
  5370. break;
  5371. case AOK_Output:
  5372. if (AR.IntelExpRestricted)
  5373. OS << "${" << OutputIdx++ << ":P}";
  5374. else
  5375. OS << '$' << OutputIdx++;
  5376. break;
  5377. case AOK_SizeDirective:
  5378. switch (AR.Val) {
  5379. default: break;
  5380. case 8: OS << "byte ptr "; break;
  5381. case 16: OS << "word ptr "; break;
  5382. case 32: OS << "dword ptr "; break;
  5383. case 64: OS << "qword ptr "; break;
  5384. case 80: OS << "xword ptr "; break;
  5385. case 128: OS << "xmmword ptr "; break;
  5386. case 256: OS << "ymmword ptr "; break;
  5387. }
  5388. break;
  5389. case AOK_Emit:
  5390. OS << ".byte";
  5391. break;
  5392. case AOK_Align: {
  5393. // MS alignment directives are measured in bytes. If the native assembler
  5394. // measures alignment in bytes, we can pass it straight through.
  5395. OS << ".align";
  5396. if (getContext().getAsmInfo()->getAlignmentIsInBytes())
  5397. break;
  5398. // Alignment is in log2 form, so print that instead and skip the original
  5399. // immediate.
  5400. unsigned Val = AR.Val;
  5401. OS << ' ' << Val;
  5402. assert(Val < 10 && "Expected alignment less then 2^10.");
  5403. AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
  5404. break;
  5405. }
  5406. case AOK_EVEN:
  5407. OS << ".even";
  5408. break;
  5409. case AOK_EndOfStatement:
  5410. OS << "\n\t";
  5411. break;
  5412. }
  5413. // Skip the original expression.
  5414. AsmStart = Loc + AR.Len + AdditionalSkip;
  5415. }
  5416. // Emit the remainder of the asm string.
  5417. if (AsmStart != AsmEnd)
  5418. OS << StringRef(AsmStart, AsmEnd - AsmStart);
  5419. AsmString = OS.str();
  5420. return false;
  5421. }
  5422. bool HLASMAsmParser::parseAsHLASMLabel(ParseStatementInfo &Info,
  5423. MCAsmParserSemaCallback *SI) {
  5424. AsmToken LabelTok = getTok();
  5425. SMLoc LabelLoc = LabelTok.getLoc();
  5426. StringRef LabelVal;
  5427. if (parseIdentifier(LabelVal))
  5428. return Error(LabelLoc, "The HLASM Label has to be an Identifier");
  5429. // We have validated whether the token is an Identifier.
  5430. // Now we have to validate whether the token is a
  5431. // valid HLASM Label.
  5432. if (!getTargetParser().isLabel(LabelTok) || checkForValidSection())
  5433. return true;
  5434. // Lex leading spaces to get to the next operand.
  5435. lexLeadingSpaces();
  5436. // We shouldn't emit the label if there is nothing else after the label.
  5437. // i.e asm("<token>\n")
  5438. if (getTok().is(AsmToken::EndOfStatement))
  5439. return Error(LabelLoc,
  5440. "Cannot have just a label for an HLASM inline asm statement");
  5441. MCSymbol *Sym = getContext().getOrCreateSymbol(
  5442. getContext().getAsmInfo()->shouldEmitLabelsInUpperCase()
  5443. ? LabelVal.upper()
  5444. : LabelVal);
  5445. getTargetParser().doBeforeLabelEmit(Sym, LabelLoc);
  5446. // Emit the label.
  5447. Out.emitLabel(Sym, LabelLoc);
  5448. // If we are generating dwarf for assembly source files then gather the
  5449. // info to make a dwarf label entry for this label if needed.
  5450. if (enabledGenDwarfForAssembly())
  5451. MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
  5452. LabelLoc);
  5453. getTargetParser().onLabelParsed(Sym);
  5454. return false;
  5455. }
  5456. bool HLASMAsmParser::parseAsMachineInstruction(ParseStatementInfo &Info,
  5457. MCAsmParserSemaCallback *SI) {
  5458. AsmToken OperationEntryTok = Lexer.getTok();
  5459. SMLoc OperationEntryLoc = OperationEntryTok.getLoc();
  5460. StringRef OperationEntryVal;
  5461. // Attempt to parse the first token as an Identifier
  5462. if (parseIdentifier(OperationEntryVal))
  5463. return Error(OperationEntryLoc, "unexpected token at start of statement");
  5464. // Once we've parsed the operation entry successfully, lex
  5465. // any spaces to get to the OperandEntries.
  5466. lexLeadingSpaces();
  5467. return parseAndMatchAndEmitTargetInstruction(
  5468. Info, OperationEntryVal, OperationEntryTok, OperationEntryLoc);
  5469. }
  5470. bool HLASMAsmParser::parseStatement(ParseStatementInfo &Info,
  5471. MCAsmParserSemaCallback *SI) {
  5472. assert(!hasPendingError() && "parseStatement started with pending error");
  5473. // Should the first token be interpreted as a HLASM Label.
  5474. bool ShouldParseAsHLASMLabel = false;
  5475. // If a Name Entry exists, it should occur at the very
  5476. // start of the string. In this case, we should parse the
  5477. // first non-space token as a Label.
  5478. // If the Name entry is missing (i.e. there's some other
  5479. // token), then we attempt to parse the first non-space
  5480. // token as a Machine Instruction.
  5481. if (getTok().isNot(AsmToken::Space))
  5482. ShouldParseAsHLASMLabel = true;
  5483. // If we have an EndOfStatement (which includes the target's comment
  5484. // string) we can appropriately lex it early on)
  5485. if (Lexer.is(AsmToken::EndOfStatement)) {
  5486. // if this is a line comment we can drop it safely
  5487. if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
  5488. getTok().getString().front() == '\n')
  5489. Out.addBlankLine();
  5490. Lex();
  5491. return false;
  5492. }
  5493. // We have established how to parse the inline asm statement.
  5494. // Now we can safely lex any leading spaces to get to the
  5495. // first token.
  5496. lexLeadingSpaces();
  5497. // If we see a new line or carriage return as the first operand,
  5498. // after lexing leading spaces, emit the new line and lex the
  5499. // EndOfStatement token.
  5500. if (Lexer.is(AsmToken::EndOfStatement)) {
  5501. if (getTok().getString().front() == '\n' ||
  5502. getTok().getString().front() == '\r') {
  5503. Out.addBlankLine();
  5504. Lex();
  5505. return false;
  5506. }
  5507. }
  5508. // Handle the label first if we have to before processing the rest
  5509. // of the tokens as a machine instruction.
  5510. if (ShouldParseAsHLASMLabel) {
  5511. // If there were any errors while handling and emitting the label,
  5512. // early return.
  5513. if (parseAsHLASMLabel(Info, SI)) {
  5514. // If we know we've failed in parsing, simply eat until end of the
  5515. // statement. This ensures that we don't process any other statements.
  5516. eatToEndOfStatement();
  5517. return true;
  5518. }
  5519. }
  5520. return parseAsMachineInstruction(Info, SI);
  5521. }
  5522. namespace llvm {
  5523. namespace MCParserUtils {
  5524. /// Returns whether the given symbol is used anywhere in the given expression,
  5525. /// or subexpressions.
  5526. static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
  5527. switch (Value->getKind()) {
  5528. case MCExpr::Binary: {
  5529. const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
  5530. return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
  5531. isSymbolUsedInExpression(Sym, BE->getRHS());
  5532. }
  5533. case MCExpr::Target:
  5534. case MCExpr::Constant:
  5535. return false;
  5536. case MCExpr::SymbolRef: {
  5537. const MCSymbol &S =
  5538. static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
  5539. if (S.isVariable())
  5540. return isSymbolUsedInExpression(Sym, S.getVariableValue());
  5541. return &S == Sym;
  5542. }
  5543. case MCExpr::Unary:
  5544. return isSymbolUsedInExpression(
  5545. Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
  5546. }
  5547. llvm_unreachable("Unknown expr kind!");
  5548. }
  5549. bool parseAssignmentExpression(StringRef Name, bool allow_redef,
  5550. MCAsmParser &Parser, MCSymbol *&Sym,
  5551. const MCExpr *&Value) {
  5552. // FIXME: Use better location, we should use proper tokens.
  5553. SMLoc EqualLoc = Parser.getTok().getLoc();
  5554. if (Parser.parseExpression(Value))
  5555. return Parser.TokError("missing expression");
  5556. // Note: we don't count b as used in "a = b". This is to allow
  5557. // a = b
  5558. // b = c
  5559. if (Parser.parseEOL())
  5560. return true;
  5561. // Validate that the LHS is allowed to be a variable (either it has not been
  5562. // used as a symbol, or it is an absolute symbol).
  5563. Sym = Parser.getContext().lookupSymbol(Name);
  5564. if (Sym) {
  5565. // Diagnose assignment to a label.
  5566. //
  5567. // FIXME: Diagnostics. Note the location of the definition as a label.
  5568. // FIXME: Diagnose assignment to protected identifier (e.g., register name).
  5569. if (isSymbolUsedInExpression(Sym, Value))
  5570. return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
  5571. else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
  5572. !Sym->isVariable())
  5573. ; // Allow redefinitions of undefined symbols only used in directives.
  5574. else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
  5575. ; // Allow redefinitions of variables that haven't yet been used.
  5576. else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
  5577. return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
  5578. else if (!Sym->isVariable())
  5579. return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
  5580. else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
  5581. return Parser.Error(EqualLoc,
  5582. "invalid reassignment of non-absolute variable '" +
  5583. Name + "'");
  5584. } else if (Name == ".") {
  5585. Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
  5586. return false;
  5587. } else
  5588. Sym = Parser.getContext().getOrCreateSymbol(Name);
  5589. Sym->setRedefinable(allow_redef);
  5590. return false;
  5591. }
  5592. } // end namespace MCParserUtils
  5593. } // end namespace llvm
  5594. /// Create an MCAsmParser instance.
  5595. MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
  5596. MCStreamer &Out, const MCAsmInfo &MAI,
  5597. unsigned CB) {
  5598. if (C.getTargetTriple().isSystemZ() && C.getTargetTriple().isOSzOS())
  5599. return new HLASMAsmParser(SM, C, Out, MAI, CB);
  5600. return new AsmParser(SM, C, Out, MAI, CB);
  5601. }