AsmParser.cpp 206 KB

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