LLParser.cpp 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512
  1. //===-- LLParser.cpp - Parser Class ---------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the parser class for .ll files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LLParser.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/None.h"
  16. #include "llvm/ADT/Optional.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/STLExtras.h"
  19. #include "llvm/AsmParser/SlotMapping.h"
  20. #include "llvm/IR/Argument.h"
  21. #include "llvm/IR/AutoUpgrade.h"
  22. #include "llvm/IR/BasicBlock.h"
  23. #include "llvm/IR/CallingConv.h"
  24. #include "llvm/IR/Comdat.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DebugInfoMetadata.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/GlobalIFunc.h"
  30. #include "llvm/IR/GlobalObject.h"
  31. #include "llvm/IR/InlineAsm.h"
  32. #include "llvm/IR/Instruction.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/Intrinsics.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/Metadata.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/Type.h"
  40. #include "llvm/IR/Value.h"
  41. #include "llvm/IR/ValueSymbolTable.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/Dwarf.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/MathExtras.h"
  46. #include "llvm/Support/SaveAndRestore.h"
  47. #include "llvm/Support/raw_ostream.h"
  48. #include <algorithm>
  49. #include <cassert>
  50. #include <cstring>
  51. #include <iterator>
  52. #include <vector>
  53. using namespace llvm;
  54. static std::string getTypeString(Type *T) {
  55. std::string Result;
  56. raw_string_ostream Tmp(Result);
  57. Tmp << *T;
  58. return Tmp.str();
  59. }
  60. /// Run: module ::= toplevelentity*
  61. bool LLParser::Run() {
  62. // Prime the lexer.
  63. Lex.Lex();
  64. if (Context.shouldDiscardValueNames())
  65. return Error(
  66. Lex.getLoc(),
  67. "Can't read textual IR with a Context that discards named Values");
  68. return ParseTopLevelEntities() ||
  69. ValidateEndOfModule();
  70. }
  71. bool LLParser::parseStandaloneConstantValue(Constant *&C,
  72. const SlotMapping *Slots) {
  73. restoreParsingState(Slots);
  74. Lex.Lex();
  75. Type *Ty = nullptr;
  76. if (ParseType(Ty) || parseConstantValue(Ty, C))
  77. return true;
  78. if (Lex.getKind() != lltok::Eof)
  79. return Error(Lex.getLoc(), "expected end of string");
  80. return false;
  81. }
  82. bool LLParser::parseTypeAtBeginning(Type *&Ty, unsigned &Read,
  83. const SlotMapping *Slots) {
  84. restoreParsingState(Slots);
  85. Lex.Lex();
  86. Read = 0;
  87. SMLoc Start = Lex.getLoc();
  88. Ty = nullptr;
  89. if (ParseType(Ty))
  90. return true;
  91. SMLoc End = Lex.getLoc();
  92. Read = End.getPointer() - Start.getPointer();
  93. return false;
  94. }
  95. void LLParser::restoreParsingState(const SlotMapping *Slots) {
  96. if (!Slots)
  97. return;
  98. NumberedVals = Slots->GlobalValues;
  99. NumberedMetadata = Slots->MetadataNodes;
  100. for (const auto &I : Slots->NamedTypes)
  101. NamedTypes.insert(
  102. std::make_pair(I.getKey(), std::make_pair(I.second, LocTy())));
  103. for (const auto &I : Slots->Types)
  104. NumberedTypes.insert(
  105. std::make_pair(I.first, std::make_pair(I.second, LocTy())));
  106. }
  107. /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
  108. /// module.
  109. bool LLParser::ValidateEndOfModule() {
  110. // Handle any function attribute group forward references.
  111. for (std::map<Value*, std::vector<unsigned> >::iterator
  112. I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
  113. I != E; ++I) {
  114. Value *V = I->first;
  115. std::vector<unsigned> &Vec = I->second;
  116. AttrBuilder B;
  117. for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
  118. VI != VE; ++VI)
  119. B.merge(NumberedAttrBuilders[*VI]);
  120. if (Function *Fn = dyn_cast<Function>(V)) {
  121. AttributeSet AS = Fn->getAttributes();
  122. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  123. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  124. AS.getFnAttributes());
  125. FnAttrs.merge(B);
  126. // If the alignment was parsed as an attribute, move to the alignment
  127. // field.
  128. if (FnAttrs.hasAlignmentAttr()) {
  129. Fn->setAlignment(FnAttrs.getAlignment());
  130. FnAttrs.removeAttribute(Attribute::Alignment);
  131. }
  132. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  133. AttributeSet::get(Context,
  134. AttributeSet::FunctionIndex,
  135. FnAttrs));
  136. Fn->setAttributes(AS);
  137. } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
  138. AttributeSet AS = CI->getAttributes();
  139. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  140. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  141. AS.getFnAttributes());
  142. FnAttrs.merge(B);
  143. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  144. AttributeSet::get(Context,
  145. AttributeSet::FunctionIndex,
  146. FnAttrs));
  147. CI->setAttributes(AS);
  148. } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
  149. AttributeSet AS = II->getAttributes();
  150. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  151. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  152. AS.getFnAttributes());
  153. FnAttrs.merge(B);
  154. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  155. AttributeSet::get(Context,
  156. AttributeSet::FunctionIndex,
  157. FnAttrs));
  158. II->setAttributes(AS);
  159. } else {
  160. llvm_unreachable("invalid object with forward attribute group reference");
  161. }
  162. }
  163. // If there are entries in ForwardRefBlockAddresses at this point, the
  164. // function was never defined.
  165. if (!ForwardRefBlockAddresses.empty())
  166. return Error(ForwardRefBlockAddresses.begin()->first.Loc,
  167. "expected function name in blockaddress");
  168. for (const auto &NT : NumberedTypes)
  169. if (NT.second.second.isValid())
  170. return Error(NT.second.second,
  171. "use of undefined type '%" + Twine(NT.first) + "'");
  172. for (StringMap<std::pair<Type*, LocTy> >::iterator I =
  173. NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
  174. if (I->second.second.isValid())
  175. return Error(I->second.second,
  176. "use of undefined type named '" + I->getKey() + "'");
  177. if (!ForwardRefComdats.empty())
  178. return Error(ForwardRefComdats.begin()->second,
  179. "use of undefined comdat '$" +
  180. ForwardRefComdats.begin()->first + "'");
  181. if (!ForwardRefVals.empty())
  182. return Error(ForwardRefVals.begin()->second.second,
  183. "use of undefined value '@" + ForwardRefVals.begin()->first +
  184. "'");
  185. if (!ForwardRefValIDs.empty())
  186. return Error(ForwardRefValIDs.begin()->second.second,
  187. "use of undefined value '@" +
  188. Twine(ForwardRefValIDs.begin()->first) + "'");
  189. if (!ForwardRefMDNodes.empty())
  190. return Error(ForwardRefMDNodes.begin()->second.second,
  191. "use of undefined metadata '!" +
  192. Twine(ForwardRefMDNodes.begin()->first) + "'");
  193. // Resolve metadata cycles.
  194. for (auto &N : NumberedMetadata) {
  195. if (N.second && !N.second->isResolved())
  196. N.second->resolveCycles();
  197. }
  198. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  199. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  200. // Look for intrinsic functions and CallInst that need to be upgraded
  201. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
  202. UpgradeCallsToIntrinsic(&*FI++); // must be post-increment, as we remove
  203. // Some types could be renamed during loading if several modules are
  204. // loaded in the same LLVMContext (LTO scenario). In this case we should
  205. // remangle intrinsics names as well.
  206. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; ) {
  207. Function *F = &*FI++;
  208. if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
  209. F->replaceAllUsesWith(Remangled.getValue());
  210. F->eraseFromParent();
  211. }
  212. }
  213. UpgradeDebugInfo(*M);
  214. UpgradeModuleFlags(*M);
  215. if (!Slots)
  216. return false;
  217. // Initialize the slot mapping.
  218. // Because by this point we've parsed and validated everything, we can "steal"
  219. // the mapping from LLParser as it doesn't need it anymore.
  220. Slots->GlobalValues = std::move(NumberedVals);
  221. Slots->MetadataNodes = std::move(NumberedMetadata);
  222. for (const auto &I : NamedTypes)
  223. Slots->NamedTypes.insert(std::make_pair(I.getKey(), I.second.first));
  224. for (const auto &I : NumberedTypes)
  225. Slots->Types.insert(std::make_pair(I.first, I.second.first));
  226. return false;
  227. }
  228. //===----------------------------------------------------------------------===//
  229. // Top-Level Entities
  230. //===----------------------------------------------------------------------===//
  231. bool LLParser::ParseTopLevelEntities() {
  232. while (true) {
  233. switch (Lex.getKind()) {
  234. default: return TokError("expected top-level entity");
  235. case lltok::Eof: return false;
  236. case lltok::kw_declare: if (ParseDeclare()) return true; break;
  237. case lltok::kw_define: if (ParseDefine()) return true; break;
  238. case lltok::kw_module: if (ParseModuleAsm()) return true; break;
  239. case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
  240. case lltok::kw_source_filename:
  241. if (ParseSourceFileName())
  242. return true;
  243. break;
  244. case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
  245. case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
  246. case lltok::LocalVar: if (ParseNamedType()) return true; break;
  247. case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
  248. case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
  249. case lltok::ComdatVar: if (parseComdat()) return true; break;
  250. case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
  251. case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
  252. case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
  253. case lltok::kw_uselistorder: if (ParseUseListOrder()) return true; break;
  254. case lltok::kw_uselistorder_bb:
  255. if (ParseUseListOrderBB())
  256. return true;
  257. break;
  258. }
  259. }
  260. }
  261. /// toplevelentity
  262. /// ::= 'module' 'asm' STRINGCONSTANT
  263. bool LLParser::ParseModuleAsm() {
  264. assert(Lex.getKind() == lltok::kw_module);
  265. Lex.Lex();
  266. std::string AsmStr;
  267. if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
  268. ParseStringConstant(AsmStr)) return true;
  269. M->appendModuleInlineAsm(AsmStr);
  270. return false;
  271. }
  272. /// toplevelentity
  273. /// ::= 'target' 'triple' '=' STRINGCONSTANT
  274. /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
  275. bool LLParser::ParseTargetDefinition() {
  276. assert(Lex.getKind() == lltok::kw_target);
  277. std::string Str;
  278. switch (Lex.Lex()) {
  279. default: return TokError("unknown target property");
  280. case lltok::kw_triple:
  281. Lex.Lex();
  282. if (ParseToken(lltok::equal, "expected '=' after target triple") ||
  283. ParseStringConstant(Str))
  284. return true;
  285. M->setTargetTriple(Str);
  286. return false;
  287. case lltok::kw_datalayout:
  288. Lex.Lex();
  289. if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
  290. ParseStringConstant(Str))
  291. return true;
  292. M->setDataLayout(Str);
  293. return false;
  294. }
  295. }
  296. /// toplevelentity
  297. /// ::= 'source_filename' '=' STRINGCONSTANT
  298. bool LLParser::ParseSourceFileName() {
  299. assert(Lex.getKind() == lltok::kw_source_filename);
  300. std::string Str;
  301. Lex.Lex();
  302. if (ParseToken(lltok::equal, "expected '=' after source_filename") ||
  303. ParseStringConstant(Str))
  304. return true;
  305. M->setSourceFileName(Str);
  306. return false;
  307. }
  308. /// toplevelentity
  309. /// ::= 'deplibs' '=' '[' ']'
  310. /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
  311. /// FIXME: Remove in 4.0. Currently parse, but ignore.
  312. bool LLParser::ParseDepLibs() {
  313. assert(Lex.getKind() == lltok::kw_deplibs);
  314. Lex.Lex();
  315. if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
  316. ParseToken(lltok::lsquare, "expected '=' after deplibs"))
  317. return true;
  318. if (EatIfPresent(lltok::rsquare))
  319. return false;
  320. do {
  321. std::string Str;
  322. if (ParseStringConstant(Str)) return true;
  323. } while (EatIfPresent(lltok::comma));
  324. return ParseToken(lltok::rsquare, "expected ']' at end of list");
  325. }
  326. /// ParseUnnamedType:
  327. /// ::= LocalVarID '=' 'type' type
  328. bool LLParser::ParseUnnamedType() {
  329. LocTy TypeLoc = Lex.getLoc();
  330. unsigned TypeID = Lex.getUIntVal();
  331. Lex.Lex(); // eat LocalVarID;
  332. if (ParseToken(lltok::equal, "expected '=' after name") ||
  333. ParseToken(lltok::kw_type, "expected 'type' after '='"))
  334. return true;
  335. Type *Result = nullptr;
  336. if (ParseStructDefinition(TypeLoc, "",
  337. NumberedTypes[TypeID], Result)) return true;
  338. if (!isa<StructType>(Result)) {
  339. std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
  340. if (Entry.first)
  341. return Error(TypeLoc, "non-struct types may not be recursive");
  342. Entry.first = Result;
  343. Entry.second = SMLoc();
  344. }
  345. return false;
  346. }
  347. /// toplevelentity
  348. /// ::= LocalVar '=' 'type' type
  349. bool LLParser::ParseNamedType() {
  350. std::string Name = Lex.getStrVal();
  351. LocTy NameLoc = Lex.getLoc();
  352. Lex.Lex(); // eat LocalVar.
  353. if (ParseToken(lltok::equal, "expected '=' after name") ||
  354. ParseToken(lltok::kw_type, "expected 'type' after name"))
  355. return true;
  356. Type *Result = nullptr;
  357. if (ParseStructDefinition(NameLoc, Name,
  358. NamedTypes[Name], Result)) return true;
  359. if (!isa<StructType>(Result)) {
  360. std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
  361. if (Entry.first)
  362. return Error(NameLoc, "non-struct types may not be recursive");
  363. Entry.first = Result;
  364. Entry.second = SMLoc();
  365. }
  366. return false;
  367. }
  368. /// toplevelentity
  369. /// ::= 'declare' FunctionHeader
  370. bool LLParser::ParseDeclare() {
  371. assert(Lex.getKind() == lltok::kw_declare);
  372. Lex.Lex();
  373. std::vector<std::pair<unsigned, MDNode *>> MDs;
  374. while (Lex.getKind() == lltok::MetadataVar) {
  375. unsigned MDK;
  376. MDNode *N;
  377. if (ParseMetadataAttachment(MDK, N))
  378. return true;
  379. MDs.push_back({MDK, N});
  380. }
  381. Function *F;
  382. if (ParseFunctionHeader(F, false))
  383. return true;
  384. for (auto &MD : MDs)
  385. F->addMetadata(MD.first, *MD.second);
  386. return false;
  387. }
  388. /// toplevelentity
  389. /// ::= 'define' FunctionHeader (!dbg !56)* '{' ...
  390. bool LLParser::ParseDefine() {
  391. assert(Lex.getKind() == lltok::kw_define);
  392. Lex.Lex();
  393. Function *F;
  394. return ParseFunctionHeader(F, true) ||
  395. ParseOptionalFunctionMetadata(*F) ||
  396. ParseFunctionBody(*F);
  397. }
  398. /// ParseGlobalType
  399. /// ::= 'constant'
  400. /// ::= 'global'
  401. bool LLParser::ParseGlobalType(bool &IsConstant) {
  402. if (Lex.getKind() == lltok::kw_constant)
  403. IsConstant = true;
  404. else if (Lex.getKind() == lltok::kw_global)
  405. IsConstant = false;
  406. else {
  407. IsConstant = false;
  408. return TokError("expected 'global' or 'constant'");
  409. }
  410. Lex.Lex();
  411. return false;
  412. }
  413. bool LLParser::ParseOptionalUnnamedAddr(
  414. GlobalVariable::UnnamedAddr &UnnamedAddr) {
  415. if (EatIfPresent(lltok::kw_unnamed_addr))
  416. UnnamedAddr = GlobalValue::UnnamedAddr::Global;
  417. else if (EatIfPresent(lltok::kw_local_unnamed_addr))
  418. UnnamedAddr = GlobalValue::UnnamedAddr::Local;
  419. else
  420. UnnamedAddr = GlobalValue::UnnamedAddr::None;
  421. return false;
  422. }
  423. /// ParseUnnamedGlobal:
  424. /// OptionalVisibility (ALIAS | IFUNC) ...
  425. /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  426. /// ... -> global variable
  427. /// GlobalID '=' OptionalVisibility (ALIAS | IFUNC) ...
  428. /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  429. /// ... -> global variable
  430. bool LLParser::ParseUnnamedGlobal() {
  431. unsigned VarID = NumberedVals.size();
  432. std::string Name;
  433. LocTy NameLoc = Lex.getLoc();
  434. // Handle the GlobalID form.
  435. if (Lex.getKind() == lltok::GlobalID) {
  436. if (Lex.getUIntVal() != VarID)
  437. return Error(Lex.getLoc(), "variable expected to be numbered '%" +
  438. Twine(VarID) + "'");
  439. Lex.Lex(); // eat GlobalID;
  440. if (ParseToken(lltok::equal, "expected '=' after name"))
  441. return true;
  442. }
  443. bool HasLinkage;
  444. unsigned Linkage, Visibility, DLLStorageClass;
  445. GlobalVariable::ThreadLocalMode TLM;
  446. GlobalVariable::UnnamedAddr UnnamedAddr;
  447. if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
  448. ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
  449. return true;
  450. if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
  451. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  452. DLLStorageClass, TLM, UnnamedAddr);
  453. return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
  454. DLLStorageClass, TLM, UnnamedAddr);
  455. }
  456. /// ParseNamedGlobal:
  457. /// GlobalVar '=' OptionalVisibility (ALIAS | IFUNC) ...
  458. /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  459. /// ... -> global variable
  460. bool LLParser::ParseNamedGlobal() {
  461. assert(Lex.getKind() == lltok::GlobalVar);
  462. LocTy NameLoc = Lex.getLoc();
  463. std::string Name = Lex.getStrVal();
  464. Lex.Lex();
  465. bool HasLinkage;
  466. unsigned Linkage, Visibility, DLLStorageClass;
  467. GlobalVariable::ThreadLocalMode TLM;
  468. GlobalVariable::UnnamedAddr UnnamedAddr;
  469. if (ParseToken(lltok::equal, "expected '=' in global variable") ||
  470. ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
  471. ParseOptionalThreadLocal(TLM) || ParseOptionalUnnamedAddr(UnnamedAddr))
  472. return true;
  473. if (Lex.getKind() != lltok::kw_alias && Lex.getKind() != lltok::kw_ifunc)
  474. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  475. DLLStorageClass, TLM, UnnamedAddr);
  476. return parseIndirectSymbol(Name, NameLoc, Linkage, Visibility,
  477. DLLStorageClass, TLM, UnnamedAddr);
  478. }
  479. bool LLParser::parseComdat() {
  480. assert(Lex.getKind() == lltok::ComdatVar);
  481. std::string Name = Lex.getStrVal();
  482. LocTy NameLoc = Lex.getLoc();
  483. Lex.Lex();
  484. if (ParseToken(lltok::equal, "expected '=' here"))
  485. return true;
  486. if (ParseToken(lltok::kw_comdat, "expected comdat keyword"))
  487. return TokError("expected comdat type");
  488. Comdat::SelectionKind SK;
  489. switch (Lex.getKind()) {
  490. default:
  491. return TokError("unknown selection kind");
  492. case lltok::kw_any:
  493. SK = Comdat::Any;
  494. break;
  495. case lltok::kw_exactmatch:
  496. SK = Comdat::ExactMatch;
  497. break;
  498. case lltok::kw_largest:
  499. SK = Comdat::Largest;
  500. break;
  501. case lltok::kw_noduplicates:
  502. SK = Comdat::NoDuplicates;
  503. break;
  504. case lltok::kw_samesize:
  505. SK = Comdat::SameSize;
  506. break;
  507. }
  508. Lex.Lex();
  509. // See if the comdat was forward referenced, if so, use the comdat.
  510. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  511. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  512. if (I != ComdatSymTab.end() && !ForwardRefComdats.erase(Name))
  513. return Error(NameLoc, "redefinition of comdat '$" + Name + "'");
  514. Comdat *C;
  515. if (I != ComdatSymTab.end())
  516. C = &I->second;
  517. else
  518. C = M->getOrInsertComdat(Name);
  519. C->setSelectionKind(SK);
  520. return false;
  521. }
  522. // MDString:
  523. // ::= '!' STRINGCONSTANT
  524. bool LLParser::ParseMDString(MDString *&Result) {
  525. std::string Str;
  526. if (ParseStringConstant(Str)) return true;
  527. Result = MDString::get(Context, Str);
  528. return false;
  529. }
  530. // MDNode:
  531. // ::= '!' MDNodeNumber
  532. bool LLParser::ParseMDNodeID(MDNode *&Result) {
  533. // !{ ..., !42, ... }
  534. LocTy IDLoc = Lex.getLoc();
  535. unsigned MID = 0;
  536. if (ParseUInt32(MID))
  537. return true;
  538. // If not a forward reference, just return it now.
  539. if (NumberedMetadata.count(MID)) {
  540. Result = NumberedMetadata[MID];
  541. return false;
  542. }
  543. // Otherwise, create MDNode forward reference.
  544. auto &FwdRef = ForwardRefMDNodes[MID];
  545. FwdRef = std::make_pair(MDTuple::getTemporary(Context, None), IDLoc);
  546. Result = FwdRef.first.get();
  547. NumberedMetadata[MID].reset(Result);
  548. return false;
  549. }
  550. /// ParseNamedMetadata:
  551. /// !foo = !{ !1, !2 }
  552. bool LLParser::ParseNamedMetadata() {
  553. assert(Lex.getKind() == lltok::MetadataVar);
  554. std::string Name = Lex.getStrVal();
  555. Lex.Lex();
  556. if (ParseToken(lltok::equal, "expected '=' here") ||
  557. ParseToken(lltok::exclaim, "Expected '!' here") ||
  558. ParseToken(lltok::lbrace, "Expected '{' here"))
  559. return true;
  560. NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
  561. if (Lex.getKind() != lltok::rbrace)
  562. do {
  563. if (ParseToken(lltok::exclaim, "Expected '!' here"))
  564. return true;
  565. MDNode *N = nullptr;
  566. if (ParseMDNodeID(N)) return true;
  567. NMD->addOperand(N);
  568. } while (EatIfPresent(lltok::comma));
  569. return ParseToken(lltok::rbrace, "expected end of metadata node");
  570. }
  571. /// ParseStandaloneMetadata:
  572. /// !42 = !{...}
  573. bool LLParser::ParseStandaloneMetadata() {
  574. assert(Lex.getKind() == lltok::exclaim);
  575. Lex.Lex();
  576. unsigned MetadataID = 0;
  577. MDNode *Init;
  578. if (ParseUInt32(MetadataID) ||
  579. ParseToken(lltok::equal, "expected '=' here"))
  580. return true;
  581. // Detect common error, from old metadata syntax.
  582. if (Lex.getKind() == lltok::Type)
  583. return TokError("unexpected type in metadata definition");
  584. bool IsDistinct = EatIfPresent(lltok::kw_distinct);
  585. if (Lex.getKind() == lltok::MetadataVar) {
  586. if (ParseSpecializedMDNode(Init, IsDistinct))
  587. return true;
  588. } else if (ParseToken(lltok::exclaim, "Expected '!' here") ||
  589. ParseMDTuple(Init, IsDistinct))
  590. return true;
  591. // See if this was forward referenced, if so, handle it.
  592. auto FI = ForwardRefMDNodes.find(MetadataID);
  593. if (FI != ForwardRefMDNodes.end()) {
  594. FI->second.first->replaceAllUsesWith(Init);
  595. ForwardRefMDNodes.erase(FI);
  596. assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
  597. } else {
  598. if (NumberedMetadata.count(MetadataID))
  599. return TokError("Metadata id is already used");
  600. NumberedMetadata[MetadataID].reset(Init);
  601. }
  602. return false;
  603. }
  604. static bool isValidVisibilityForLinkage(unsigned V, unsigned L) {
  605. return !GlobalValue::isLocalLinkage((GlobalValue::LinkageTypes)L) ||
  606. (GlobalValue::VisibilityTypes)V == GlobalValue::DefaultVisibility;
  607. }
  608. /// parseIndirectSymbol:
  609. /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility
  610. /// OptionalDLLStorageClass OptionalThreadLocal
  611. /// OptionalUnnamedAddr 'alias|ifunc' IndirectSymbol
  612. ///
  613. /// IndirectSymbol
  614. /// ::= TypeAndValue
  615. ///
  616. /// Everything through OptionalUnnamedAddr has already been parsed.
  617. ///
  618. bool LLParser::parseIndirectSymbol(
  619. const std::string &Name, LocTy NameLoc, unsigned L, unsigned Visibility,
  620. unsigned DLLStorageClass, GlobalVariable::ThreadLocalMode TLM,
  621. GlobalVariable::UnnamedAddr UnnamedAddr) {
  622. bool IsAlias;
  623. if (Lex.getKind() == lltok::kw_alias)
  624. IsAlias = true;
  625. else if (Lex.getKind() == lltok::kw_ifunc)
  626. IsAlias = false;
  627. else
  628. llvm_unreachable("Not an alias or ifunc!");
  629. Lex.Lex();
  630. GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
  631. if(IsAlias && !GlobalAlias::isValidLinkage(Linkage))
  632. return Error(NameLoc, "invalid linkage type for alias");
  633. if (!isValidVisibilityForLinkage(Visibility, L))
  634. return Error(NameLoc,
  635. "symbol with local linkage must have default visibility");
  636. Type *Ty;
  637. LocTy ExplicitTypeLoc = Lex.getLoc();
  638. if (ParseType(Ty) ||
  639. ParseToken(lltok::comma, "expected comma after alias or ifunc's type"))
  640. return true;
  641. Constant *Aliasee;
  642. LocTy AliaseeLoc = Lex.getLoc();
  643. if (Lex.getKind() != lltok::kw_bitcast &&
  644. Lex.getKind() != lltok::kw_getelementptr &&
  645. Lex.getKind() != lltok::kw_addrspacecast &&
  646. Lex.getKind() != lltok::kw_inttoptr) {
  647. if (ParseGlobalTypeAndValue(Aliasee))
  648. return true;
  649. } else {
  650. // The bitcast dest type is not present, it is implied by the dest type.
  651. ValID ID;
  652. if (ParseValID(ID))
  653. return true;
  654. if (ID.Kind != ValID::t_Constant)
  655. return Error(AliaseeLoc, "invalid aliasee");
  656. Aliasee = ID.ConstantVal;
  657. }
  658. Type *AliaseeType = Aliasee->getType();
  659. auto *PTy = dyn_cast<PointerType>(AliaseeType);
  660. if (!PTy)
  661. return Error(AliaseeLoc, "An alias or ifunc must have pointer type");
  662. unsigned AddrSpace = PTy->getAddressSpace();
  663. if (IsAlias && Ty != PTy->getElementType())
  664. return Error(
  665. ExplicitTypeLoc,
  666. "explicit pointee type doesn't match operand's pointee type");
  667. if (!IsAlias && !PTy->getElementType()->isFunctionTy())
  668. return Error(
  669. ExplicitTypeLoc,
  670. "explicit pointee type should be a function type");
  671. GlobalValue *GVal = nullptr;
  672. // See if the alias was forward referenced, if so, prepare to replace the
  673. // forward reference.
  674. if (!Name.empty()) {
  675. GVal = M->getNamedValue(Name);
  676. if (GVal) {
  677. if (!ForwardRefVals.erase(Name))
  678. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  679. }
  680. } else {
  681. auto I = ForwardRefValIDs.find(NumberedVals.size());
  682. if (I != ForwardRefValIDs.end()) {
  683. GVal = I->second.first;
  684. ForwardRefValIDs.erase(I);
  685. }
  686. }
  687. // Okay, create the alias but do not insert it into the module yet.
  688. std::unique_ptr<GlobalIndirectSymbol> GA;
  689. if (IsAlias)
  690. GA.reset(GlobalAlias::create(Ty, AddrSpace,
  691. (GlobalValue::LinkageTypes)Linkage, Name,
  692. Aliasee, /*Parent*/ nullptr));
  693. else
  694. GA.reset(GlobalIFunc::create(Ty, AddrSpace,
  695. (GlobalValue::LinkageTypes)Linkage, Name,
  696. Aliasee, /*Parent*/ nullptr));
  697. GA->setThreadLocalMode(TLM);
  698. GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  699. GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  700. GA->setUnnamedAddr(UnnamedAddr);
  701. if (Name.empty())
  702. NumberedVals.push_back(GA.get());
  703. if (GVal) {
  704. // Verify that types agree.
  705. if (GVal->getType() != GA->getType())
  706. return Error(
  707. ExplicitTypeLoc,
  708. "forward reference and definition of alias have different types");
  709. // If they agree, just RAUW the old value with the alias and remove the
  710. // forward ref info.
  711. GVal->replaceAllUsesWith(GA.get());
  712. GVal->eraseFromParent();
  713. }
  714. // Insert into the module, we know its name won't collide now.
  715. if (IsAlias)
  716. M->getAliasList().push_back(cast<GlobalAlias>(GA.get()));
  717. else
  718. M->getIFuncList().push_back(cast<GlobalIFunc>(GA.get()));
  719. assert(GA->getName() == Name && "Should not be a name conflict!");
  720. // The module owns this now
  721. GA.release();
  722. return false;
  723. }
  724. /// ParseGlobal
  725. /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  726. /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
  727. /// OptionalExternallyInitialized GlobalType Type Const
  728. /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  729. /// OptionalThreadLocal OptionalUnnamedAddr OptionalAddrSpace
  730. /// OptionalExternallyInitialized GlobalType Type Const
  731. ///
  732. /// Everything up to and including OptionalUnnamedAddr has been parsed
  733. /// already.
  734. ///
  735. bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
  736. unsigned Linkage, bool HasLinkage,
  737. unsigned Visibility, unsigned DLLStorageClass,
  738. GlobalVariable::ThreadLocalMode TLM,
  739. GlobalVariable::UnnamedAddr UnnamedAddr) {
  740. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  741. return Error(NameLoc,
  742. "symbol with local linkage must have default visibility");
  743. unsigned AddrSpace;
  744. bool IsConstant, IsExternallyInitialized;
  745. LocTy IsExternallyInitializedLoc;
  746. LocTy TyLoc;
  747. Type *Ty = nullptr;
  748. if (ParseOptionalAddrSpace(AddrSpace) ||
  749. ParseOptionalToken(lltok::kw_externally_initialized,
  750. IsExternallyInitialized,
  751. &IsExternallyInitializedLoc) ||
  752. ParseGlobalType(IsConstant) ||
  753. ParseType(Ty, TyLoc))
  754. return true;
  755. // If the linkage is specified and is external, then no initializer is
  756. // present.
  757. Constant *Init = nullptr;
  758. if (!HasLinkage ||
  759. !GlobalValue::isValidDeclarationLinkage(
  760. (GlobalValue::LinkageTypes)Linkage)) {
  761. if (ParseGlobalValue(Ty, Init))
  762. return true;
  763. }
  764. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  765. return Error(TyLoc, "invalid type for global variable");
  766. GlobalValue *GVal = nullptr;
  767. // See if the global was forward referenced, if so, use the global.
  768. if (!Name.empty()) {
  769. GVal = M->getNamedValue(Name);
  770. if (GVal) {
  771. if (!ForwardRefVals.erase(Name))
  772. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  773. }
  774. } else {
  775. auto I = ForwardRefValIDs.find(NumberedVals.size());
  776. if (I != ForwardRefValIDs.end()) {
  777. GVal = I->second.first;
  778. ForwardRefValIDs.erase(I);
  779. }
  780. }
  781. GlobalVariable *GV;
  782. if (!GVal) {
  783. GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, nullptr,
  784. Name, nullptr, GlobalVariable::NotThreadLocal,
  785. AddrSpace);
  786. } else {
  787. if (GVal->getValueType() != Ty)
  788. return Error(TyLoc,
  789. "forward reference and definition of global have different types");
  790. GV = cast<GlobalVariable>(GVal);
  791. // Move the forward-reference to the correct spot in the module.
  792. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
  793. }
  794. if (Name.empty())
  795. NumberedVals.push_back(GV);
  796. // Set the parsed properties on the global.
  797. if (Init)
  798. GV->setInitializer(Init);
  799. GV->setConstant(IsConstant);
  800. GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
  801. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  802. GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  803. GV->setExternallyInitialized(IsExternallyInitialized);
  804. GV->setThreadLocalMode(TLM);
  805. GV->setUnnamedAddr(UnnamedAddr);
  806. // Parse attributes on the global.
  807. while (Lex.getKind() == lltok::comma) {
  808. Lex.Lex();
  809. if (Lex.getKind() == lltok::kw_section) {
  810. Lex.Lex();
  811. GV->setSection(Lex.getStrVal());
  812. if (ParseToken(lltok::StringConstant, "expected global section string"))
  813. return true;
  814. } else if (Lex.getKind() == lltok::kw_align) {
  815. unsigned Alignment;
  816. if (ParseOptionalAlignment(Alignment)) return true;
  817. GV->setAlignment(Alignment);
  818. } else if (Lex.getKind() == lltok::MetadataVar) {
  819. if (ParseGlobalObjectMetadataAttachment(*GV))
  820. return true;
  821. } else {
  822. Comdat *C;
  823. if (parseOptionalComdat(Name, C))
  824. return true;
  825. if (C)
  826. GV->setComdat(C);
  827. else
  828. return TokError("unknown global variable property!");
  829. }
  830. }
  831. return false;
  832. }
  833. /// ParseUnnamedAttrGrp
  834. /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
  835. bool LLParser::ParseUnnamedAttrGrp() {
  836. assert(Lex.getKind() == lltok::kw_attributes);
  837. LocTy AttrGrpLoc = Lex.getLoc();
  838. Lex.Lex();
  839. if (Lex.getKind() != lltok::AttrGrpID)
  840. return TokError("expected attribute group id");
  841. unsigned VarID = Lex.getUIntVal();
  842. std::vector<unsigned> unused;
  843. LocTy BuiltinLoc;
  844. Lex.Lex();
  845. if (ParseToken(lltok::equal, "expected '=' here") ||
  846. ParseToken(lltok::lbrace, "expected '{' here") ||
  847. ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
  848. BuiltinLoc) ||
  849. ParseToken(lltok::rbrace, "expected end of attribute group"))
  850. return true;
  851. if (!NumberedAttrBuilders[VarID].hasAttributes())
  852. return Error(AttrGrpLoc, "attribute group has no attributes");
  853. return false;
  854. }
  855. /// ParseFnAttributeValuePairs
  856. /// ::= <attr> | <attr> '=' <value>
  857. bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
  858. std::vector<unsigned> &FwdRefAttrGrps,
  859. bool inAttrGrp, LocTy &BuiltinLoc) {
  860. bool HaveError = false;
  861. B.clear();
  862. while (true) {
  863. lltok::Kind Token = Lex.getKind();
  864. if (Token == lltok::kw_builtin)
  865. BuiltinLoc = Lex.getLoc();
  866. switch (Token) {
  867. default:
  868. if (!inAttrGrp) return HaveError;
  869. return Error(Lex.getLoc(), "unterminated attribute group");
  870. case lltok::rbrace:
  871. // Finished.
  872. return false;
  873. case lltok::AttrGrpID: {
  874. // Allow a function to reference an attribute group:
  875. //
  876. // define void @foo() #1 { ... }
  877. if (inAttrGrp)
  878. HaveError |=
  879. Error(Lex.getLoc(),
  880. "cannot have an attribute group reference in an attribute group");
  881. unsigned AttrGrpNum = Lex.getUIntVal();
  882. if (inAttrGrp) break;
  883. // Save the reference to the attribute group. We'll fill it in later.
  884. FwdRefAttrGrps.push_back(AttrGrpNum);
  885. break;
  886. }
  887. // Target-dependent attributes:
  888. case lltok::StringConstant: {
  889. if (ParseStringAttribute(B))
  890. return true;
  891. continue;
  892. }
  893. // Target-independent attributes:
  894. case lltok::kw_align: {
  895. // As a hack, we allow function alignment to be initially parsed as an
  896. // attribute on a function declaration/definition or added to an attribute
  897. // group and later moved to the alignment field.
  898. unsigned Alignment;
  899. if (inAttrGrp) {
  900. Lex.Lex();
  901. if (ParseToken(lltok::equal, "expected '=' here") ||
  902. ParseUInt32(Alignment))
  903. return true;
  904. } else {
  905. if (ParseOptionalAlignment(Alignment))
  906. return true;
  907. }
  908. B.addAlignmentAttr(Alignment);
  909. continue;
  910. }
  911. case lltok::kw_alignstack: {
  912. unsigned Alignment;
  913. if (inAttrGrp) {
  914. Lex.Lex();
  915. if (ParseToken(lltok::equal, "expected '=' here") ||
  916. ParseUInt32(Alignment))
  917. return true;
  918. } else {
  919. if (ParseOptionalStackAlignment(Alignment))
  920. return true;
  921. }
  922. B.addStackAlignmentAttr(Alignment);
  923. continue;
  924. }
  925. case lltok::kw_allocsize: {
  926. unsigned ElemSizeArg;
  927. Optional<unsigned> NumElemsArg;
  928. // inAttrGrp doesn't matter; we only support allocsize(a[, b])
  929. if (parseAllocSizeArguments(ElemSizeArg, NumElemsArg))
  930. return true;
  931. B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
  932. continue;
  933. }
  934. case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
  935. case lltok::kw_argmemonly: B.addAttribute(Attribute::ArgMemOnly); break;
  936. case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
  937. case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
  938. case lltok::kw_convergent: B.addAttribute(Attribute::Convergent); break;
  939. case lltok::kw_inaccessiblememonly:
  940. B.addAttribute(Attribute::InaccessibleMemOnly); break;
  941. case lltok::kw_inaccessiblemem_or_argmemonly:
  942. B.addAttribute(Attribute::InaccessibleMemOrArgMemOnly); break;
  943. case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
  944. case lltok::kw_jumptable: B.addAttribute(Attribute::JumpTable); break;
  945. case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
  946. case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
  947. case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
  948. case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
  949. case lltok::kw_noimplicitfloat:
  950. B.addAttribute(Attribute::NoImplicitFloat); break;
  951. case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
  952. case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
  953. case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
  954. case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
  955. case lltok::kw_norecurse: B.addAttribute(Attribute::NoRecurse); break;
  956. case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
  957. case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
  958. case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
  959. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  960. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  961. case lltok::kw_returns_twice:
  962. B.addAttribute(Attribute::ReturnsTwice); break;
  963. case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
  964. case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
  965. case lltok::kw_sspstrong:
  966. B.addAttribute(Attribute::StackProtectStrong); break;
  967. case lltok::kw_safestack: B.addAttribute(Attribute::SafeStack); break;
  968. case lltok::kw_sanitize_address:
  969. B.addAttribute(Attribute::SanitizeAddress); break;
  970. case lltok::kw_sanitize_thread:
  971. B.addAttribute(Attribute::SanitizeThread); break;
  972. case lltok::kw_sanitize_memory:
  973. B.addAttribute(Attribute::SanitizeMemory); break;
  974. case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
  975. case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
  976. // Error handling.
  977. case lltok::kw_inreg:
  978. case lltok::kw_signext:
  979. case lltok::kw_zeroext:
  980. HaveError |=
  981. Error(Lex.getLoc(),
  982. "invalid use of attribute on a function");
  983. break;
  984. case lltok::kw_byval:
  985. case lltok::kw_dereferenceable:
  986. case lltok::kw_dereferenceable_or_null:
  987. case lltok::kw_inalloca:
  988. case lltok::kw_nest:
  989. case lltok::kw_noalias:
  990. case lltok::kw_nocapture:
  991. case lltok::kw_nonnull:
  992. case lltok::kw_returned:
  993. case lltok::kw_sret:
  994. case lltok::kw_swifterror:
  995. case lltok::kw_swiftself:
  996. HaveError |=
  997. Error(Lex.getLoc(),
  998. "invalid use of parameter-only attribute on a function");
  999. break;
  1000. }
  1001. Lex.Lex();
  1002. }
  1003. }
  1004. //===----------------------------------------------------------------------===//
  1005. // GlobalValue Reference/Resolution Routines.
  1006. //===----------------------------------------------------------------------===//
  1007. static inline GlobalValue *createGlobalFwdRef(Module *M, PointerType *PTy,
  1008. const std::string &Name) {
  1009. if (auto *FT = dyn_cast<FunctionType>(PTy->getElementType()))
  1010. return Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
  1011. else
  1012. return new GlobalVariable(*M, PTy->getElementType(), false,
  1013. GlobalValue::ExternalWeakLinkage, nullptr, Name,
  1014. nullptr, GlobalVariable::NotThreadLocal,
  1015. PTy->getAddressSpace());
  1016. }
  1017. /// GetGlobalVal - Get a value with the specified name or ID, creating a
  1018. /// forward reference record if needed. This can return null if the value
  1019. /// exists but does not have the right type.
  1020. GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
  1021. LocTy Loc) {
  1022. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1023. if (!PTy) {
  1024. Error(Loc, "global variable reference must have pointer type");
  1025. return nullptr;
  1026. }
  1027. // Look this name up in the normal function symbol table.
  1028. GlobalValue *Val =
  1029. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
  1030. // If this is a forward reference for the value, see if we already created a
  1031. // forward ref record.
  1032. if (!Val) {
  1033. auto I = ForwardRefVals.find(Name);
  1034. if (I != ForwardRefVals.end())
  1035. Val = I->second.first;
  1036. }
  1037. // If we have the value in the symbol table or fwd-ref table, return it.
  1038. if (Val) {
  1039. if (Val->getType() == Ty) return Val;
  1040. Error(Loc, "'@" + Name + "' defined with type '" +
  1041. getTypeString(Val->getType()) + "'");
  1042. return nullptr;
  1043. }
  1044. // Otherwise, create a new forward reference for this value and remember it.
  1045. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, Name);
  1046. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  1047. return FwdVal;
  1048. }
  1049. GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
  1050. PointerType *PTy = dyn_cast<PointerType>(Ty);
  1051. if (!PTy) {
  1052. Error(Loc, "global variable reference must have pointer type");
  1053. return nullptr;
  1054. }
  1055. GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  1056. // If this is a forward reference for the value, see if we already created a
  1057. // forward ref record.
  1058. if (!Val) {
  1059. auto I = ForwardRefValIDs.find(ID);
  1060. if (I != ForwardRefValIDs.end())
  1061. Val = I->second.first;
  1062. }
  1063. // If we have the value in the symbol table or fwd-ref table, return it.
  1064. if (Val) {
  1065. if (Val->getType() == Ty) return Val;
  1066. Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
  1067. getTypeString(Val->getType()) + "'");
  1068. return nullptr;
  1069. }
  1070. // Otherwise, create a new forward reference for this value and remember it.
  1071. GlobalValue *FwdVal = createGlobalFwdRef(M, PTy, "");
  1072. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  1073. return FwdVal;
  1074. }
  1075. //===----------------------------------------------------------------------===//
  1076. // Comdat Reference/Resolution Routines.
  1077. //===----------------------------------------------------------------------===//
  1078. Comdat *LLParser::getComdat(const std::string &Name, LocTy Loc) {
  1079. // Look this name up in the comdat symbol table.
  1080. Module::ComdatSymTabType &ComdatSymTab = M->getComdatSymbolTable();
  1081. Module::ComdatSymTabType::iterator I = ComdatSymTab.find(Name);
  1082. if (I != ComdatSymTab.end())
  1083. return &I->second;
  1084. // Otherwise, create a new forward reference for this value and remember it.
  1085. Comdat *C = M->getOrInsertComdat(Name);
  1086. ForwardRefComdats[Name] = Loc;
  1087. return C;
  1088. }
  1089. //===----------------------------------------------------------------------===//
  1090. // Helper Routines.
  1091. //===----------------------------------------------------------------------===//
  1092. /// ParseToken - If the current token has the specified kind, eat it and return
  1093. /// success. Otherwise, emit the specified error and return failure.
  1094. bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
  1095. if (Lex.getKind() != T)
  1096. return TokError(ErrMsg);
  1097. Lex.Lex();
  1098. return false;
  1099. }
  1100. /// ParseStringConstant
  1101. /// ::= StringConstant
  1102. bool LLParser::ParseStringConstant(std::string &Result) {
  1103. if (Lex.getKind() != lltok::StringConstant)
  1104. return TokError("expected string constant");
  1105. Result = Lex.getStrVal();
  1106. Lex.Lex();
  1107. return false;
  1108. }
  1109. /// ParseUInt32
  1110. /// ::= uint32
  1111. bool LLParser::ParseUInt32(uint32_t &Val) {
  1112. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1113. return TokError("expected integer");
  1114. uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
  1115. if (Val64 != unsigned(Val64))
  1116. return TokError("expected 32-bit integer (too large)");
  1117. Val = Val64;
  1118. Lex.Lex();
  1119. return false;
  1120. }
  1121. /// ParseUInt64
  1122. /// ::= uint64
  1123. bool LLParser::ParseUInt64(uint64_t &Val) {
  1124. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  1125. return TokError("expected integer");
  1126. Val = Lex.getAPSIntVal().getLimitedValue();
  1127. Lex.Lex();
  1128. return false;
  1129. }
  1130. /// ParseTLSModel
  1131. /// := 'localdynamic'
  1132. /// := 'initialexec'
  1133. /// := 'localexec'
  1134. bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
  1135. switch (Lex.getKind()) {
  1136. default:
  1137. return TokError("expected localdynamic, initialexec or localexec");
  1138. case lltok::kw_localdynamic:
  1139. TLM = GlobalVariable::LocalDynamicTLSModel;
  1140. break;
  1141. case lltok::kw_initialexec:
  1142. TLM = GlobalVariable::InitialExecTLSModel;
  1143. break;
  1144. case lltok::kw_localexec:
  1145. TLM = GlobalVariable::LocalExecTLSModel;
  1146. break;
  1147. }
  1148. Lex.Lex();
  1149. return false;
  1150. }
  1151. /// ParseOptionalThreadLocal
  1152. /// := /*empty*/
  1153. /// := 'thread_local'
  1154. /// := 'thread_local' '(' tlsmodel ')'
  1155. bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
  1156. TLM = GlobalVariable::NotThreadLocal;
  1157. if (!EatIfPresent(lltok::kw_thread_local))
  1158. return false;
  1159. TLM = GlobalVariable::GeneralDynamicTLSModel;
  1160. if (Lex.getKind() == lltok::lparen) {
  1161. Lex.Lex();
  1162. return ParseTLSModel(TLM) ||
  1163. ParseToken(lltok::rparen, "expected ')' after thread local model");
  1164. }
  1165. return false;
  1166. }
  1167. /// ParseOptionalAddrSpace
  1168. /// := /*empty*/
  1169. /// := 'addrspace' '(' uint32 ')'
  1170. bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
  1171. AddrSpace = 0;
  1172. if (!EatIfPresent(lltok::kw_addrspace))
  1173. return false;
  1174. return ParseToken(lltok::lparen, "expected '(' in address space") ||
  1175. ParseUInt32(AddrSpace) ||
  1176. ParseToken(lltok::rparen, "expected ')' in address space");
  1177. }
  1178. /// ParseStringAttribute
  1179. /// := StringConstant
  1180. /// := StringConstant '=' StringConstant
  1181. bool LLParser::ParseStringAttribute(AttrBuilder &B) {
  1182. std::string Attr = Lex.getStrVal();
  1183. Lex.Lex();
  1184. std::string Val;
  1185. if (EatIfPresent(lltok::equal) && ParseStringConstant(Val))
  1186. return true;
  1187. B.addAttribute(Attr, Val);
  1188. return false;
  1189. }
  1190. /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
  1191. bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
  1192. bool HaveError = false;
  1193. B.clear();
  1194. while (true) {
  1195. lltok::Kind Token = Lex.getKind();
  1196. switch (Token) {
  1197. default: // End of attributes.
  1198. return HaveError;
  1199. case lltok::StringConstant: {
  1200. if (ParseStringAttribute(B))
  1201. return true;
  1202. continue;
  1203. }
  1204. case lltok::kw_align: {
  1205. unsigned Alignment;
  1206. if (ParseOptionalAlignment(Alignment))
  1207. return true;
  1208. B.addAlignmentAttr(Alignment);
  1209. continue;
  1210. }
  1211. case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
  1212. case lltok::kw_dereferenceable: {
  1213. uint64_t Bytes;
  1214. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
  1215. return true;
  1216. B.addDereferenceableAttr(Bytes);
  1217. continue;
  1218. }
  1219. case lltok::kw_dereferenceable_or_null: {
  1220. uint64_t Bytes;
  1221. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
  1222. return true;
  1223. B.addDereferenceableOrNullAttr(Bytes);
  1224. continue;
  1225. }
  1226. case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
  1227. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1228. case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
  1229. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1230. case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
  1231. case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
  1232. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  1233. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  1234. case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
  1235. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1236. case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
  1237. case lltok::kw_swifterror: B.addAttribute(Attribute::SwiftError); break;
  1238. case lltok::kw_swiftself: B.addAttribute(Attribute::SwiftSelf); break;
  1239. case lltok::kw_writeonly: B.addAttribute(Attribute::WriteOnly); break;
  1240. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1241. case lltok::kw_alignstack:
  1242. case lltok::kw_alwaysinline:
  1243. case lltok::kw_argmemonly:
  1244. case lltok::kw_builtin:
  1245. case lltok::kw_inlinehint:
  1246. case lltok::kw_jumptable:
  1247. case lltok::kw_minsize:
  1248. case lltok::kw_naked:
  1249. case lltok::kw_nobuiltin:
  1250. case lltok::kw_noduplicate:
  1251. case lltok::kw_noimplicitfloat:
  1252. case lltok::kw_noinline:
  1253. case lltok::kw_nonlazybind:
  1254. case lltok::kw_noredzone:
  1255. case lltok::kw_noreturn:
  1256. case lltok::kw_nounwind:
  1257. case lltok::kw_optnone:
  1258. case lltok::kw_optsize:
  1259. case lltok::kw_returns_twice:
  1260. case lltok::kw_sanitize_address:
  1261. case lltok::kw_sanitize_memory:
  1262. case lltok::kw_sanitize_thread:
  1263. case lltok::kw_ssp:
  1264. case lltok::kw_sspreq:
  1265. case lltok::kw_sspstrong:
  1266. case lltok::kw_safestack:
  1267. case lltok::kw_uwtable:
  1268. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1269. break;
  1270. }
  1271. Lex.Lex();
  1272. }
  1273. }
  1274. /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
  1275. bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
  1276. bool HaveError = false;
  1277. B.clear();
  1278. while (true) {
  1279. lltok::Kind Token = Lex.getKind();
  1280. switch (Token) {
  1281. default: // End of attributes.
  1282. return HaveError;
  1283. case lltok::StringConstant: {
  1284. if (ParseStringAttribute(B))
  1285. return true;
  1286. continue;
  1287. }
  1288. case lltok::kw_dereferenceable: {
  1289. uint64_t Bytes;
  1290. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable, Bytes))
  1291. return true;
  1292. B.addDereferenceableAttr(Bytes);
  1293. continue;
  1294. }
  1295. case lltok::kw_dereferenceable_or_null: {
  1296. uint64_t Bytes;
  1297. if (ParseOptionalDerefAttrBytes(lltok::kw_dereferenceable_or_null, Bytes))
  1298. return true;
  1299. B.addDereferenceableOrNullAttr(Bytes);
  1300. continue;
  1301. }
  1302. case lltok::kw_align: {
  1303. unsigned Alignment;
  1304. if (ParseOptionalAlignment(Alignment))
  1305. return true;
  1306. B.addAlignmentAttr(Alignment);
  1307. continue;
  1308. }
  1309. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1310. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1311. case lltok::kw_nonnull: B.addAttribute(Attribute::NonNull); break;
  1312. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1313. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1314. // Error handling.
  1315. case lltok::kw_byval:
  1316. case lltok::kw_inalloca:
  1317. case lltok::kw_nest:
  1318. case lltok::kw_nocapture:
  1319. case lltok::kw_returned:
  1320. case lltok::kw_sret:
  1321. case lltok::kw_swifterror:
  1322. case lltok::kw_swiftself:
  1323. HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
  1324. break;
  1325. case lltok::kw_alignstack:
  1326. case lltok::kw_alwaysinline:
  1327. case lltok::kw_argmemonly:
  1328. case lltok::kw_builtin:
  1329. case lltok::kw_cold:
  1330. case lltok::kw_inlinehint:
  1331. case lltok::kw_jumptable:
  1332. case lltok::kw_minsize:
  1333. case lltok::kw_naked:
  1334. case lltok::kw_nobuiltin:
  1335. case lltok::kw_noduplicate:
  1336. case lltok::kw_noimplicitfloat:
  1337. case lltok::kw_noinline:
  1338. case lltok::kw_nonlazybind:
  1339. case lltok::kw_noredzone:
  1340. case lltok::kw_noreturn:
  1341. case lltok::kw_nounwind:
  1342. case lltok::kw_optnone:
  1343. case lltok::kw_optsize:
  1344. case lltok::kw_returns_twice:
  1345. case lltok::kw_sanitize_address:
  1346. case lltok::kw_sanitize_memory:
  1347. case lltok::kw_sanitize_thread:
  1348. case lltok::kw_ssp:
  1349. case lltok::kw_sspreq:
  1350. case lltok::kw_sspstrong:
  1351. case lltok::kw_safestack:
  1352. case lltok::kw_uwtable:
  1353. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1354. break;
  1355. case lltok::kw_readnone:
  1356. case lltok::kw_readonly:
  1357. HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
  1358. }
  1359. Lex.Lex();
  1360. }
  1361. }
  1362. static unsigned parseOptionalLinkageAux(lltok::Kind Kind, bool &HasLinkage) {
  1363. HasLinkage = true;
  1364. switch (Kind) {
  1365. default:
  1366. HasLinkage = false;
  1367. return GlobalValue::ExternalLinkage;
  1368. case lltok::kw_private:
  1369. return GlobalValue::PrivateLinkage;
  1370. case lltok::kw_internal:
  1371. return GlobalValue::InternalLinkage;
  1372. case lltok::kw_weak:
  1373. return GlobalValue::WeakAnyLinkage;
  1374. case lltok::kw_weak_odr:
  1375. return GlobalValue::WeakODRLinkage;
  1376. case lltok::kw_linkonce:
  1377. return GlobalValue::LinkOnceAnyLinkage;
  1378. case lltok::kw_linkonce_odr:
  1379. return GlobalValue::LinkOnceODRLinkage;
  1380. case lltok::kw_available_externally:
  1381. return GlobalValue::AvailableExternallyLinkage;
  1382. case lltok::kw_appending:
  1383. return GlobalValue::AppendingLinkage;
  1384. case lltok::kw_common:
  1385. return GlobalValue::CommonLinkage;
  1386. case lltok::kw_extern_weak:
  1387. return GlobalValue::ExternalWeakLinkage;
  1388. case lltok::kw_external:
  1389. return GlobalValue::ExternalLinkage;
  1390. }
  1391. }
  1392. /// ParseOptionalLinkage
  1393. /// ::= /*empty*/
  1394. /// ::= 'private'
  1395. /// ::= 'internal'
  1396. /// ::= 'weak'
  1397. /// ::= 'weak_odr'
  1398. /// ::= 'linkonce'
  1399. /// ::= 'linkonce_odr'
  1400. /// ::= 'available_externally'
  1401. /// ::= 'appending'
  1402. /// ::= 'common'
  1403. /// ::= 'extern_weak'
  1404. /// ::= 'external'
  1405. bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage,
  1406. unsigned &Visibility,
  1407. unsigned &DLLStorageClass) {
  1408. Res = parseOptionalLinkageAux(Lex.getKind(), HasLinkage);
  1409. if (HasLinkage)
  1410. Lex.Lex();
  1411. ParseOptionalVisibility(Visibility);
  1412. ParseOptionalDLLStorageClass(DLLStorageClass);
  1413. return false;
  1414. }
  1415. /// ParseOptionalVisibility
  1416. /// ::= /*empty*/
  1417. /// ::= 'default'
  1418. /// ::= 'hidden'
  1419. /// ::= 'protected'
  1420. ///
  1421. void LLParser::ParseOptionalVisibility(unsigned &Res) {
  1422. switch (Lex.getKind()) {
  1423. default:
  1424. Res = GlobalValue::DefaultVisibility;
  1425. return;
  1426. case lltok::kw_default:
  1427. Res = GlobalValue::DefaultVisibility;
  1428. break;
  1429. case lltok::kw_hidden:
  1430. Res = GlobalValue::HiddenVisibility;
  1431. break;
  1432. case lltok::kw_protected:
  1433. Res = GlobalValue::ProtectedVisibility;
  1434. break;
  1435. }
  1436. Lex.Lex();
  1437. }
  1438. /// ParseOptionalDLLStorageClass
  1439. /// ::= /*empty*/
  1440. /// ::= 'dllimport'
  1441. /// ::= 'dllexport'
  1442. ///
  1443. void LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
  1444. switch (Lex.getKind()) {
  1445. default:
  1446. Res = GlobalValue::DefaultStorageClass;
  1447. return;
  1448. case lltok::kw_dllimport:
  1449. Res = GlobalValue::DLLImportStorageClass;
  1450. break;
  1451. case lltok::kw_dllexport:
  1452. Res = GlobalValue::DLLExportStorageClass;
  1453. break;
  1454. }
  1455. Lex.Lex();
  1456. }
  1457. /// ParseOptionalCallingConv
  1458. /// ::= /*empty*/
  1459. /// ::= 'ccc'
  1460. /// ::= 'fastcc'
  1461. /// ::= 'intel_ocl_bicc'
  1462. /// ::= 'coldcc'
  1463. /// ::= 'x86_stdcallcc'
  1464. /// ::= 'x86_fastcallcc'
  1465. /// ::= 'x86_thiscallcc'
  1466. /// ::= 'x86_vectorcallcc'
  1467. /// ::= 'arm_apcscc'
  1468. /// ::= 'arm_aapcscc'
  1469. /// ::= 'arm_aapcs_vfpcc'
  1470. /// ::= 'msp430_intrcc'
  1471. /// ::= 'avr_intrcc'
  1472. /// ::= 'avr_signalcc'
  1473. /// ::= 'ptx_kernel'
  1474. /// ::= 'ptx_device'
  1475. /// ::= 'spir_func'
  1476. /// ::= 'spir_kernel'
  1477. /// ::= 'x86_64_sysvcc'
  1478. /// ::= 'x86_64_win64cc'
  1479. /// ::= 'webkit_jscc'
  1480. /// ::= 'anyregcc'
  1481. /// ::= 'preserve_mostcc'
  1482. /// ::= 'preserve_allcc'
  1483. /// ::= 'ghccc'
  1484. /// ::= 'swiftcc'
  1485. /// ::= 'x86_intrcc'
  1486. /// ::= 'hhvmcc'
  1487. /// ::= 'hhvm_ccc'
  1488. /// ::= 'cxx_fast_tlscc'
  1489. /// ::= 'amdgpu_vs'
  1490. /// ::= 'amdgpu_tcs'
  1491. /// ::= 'amdgpu_tes'
  1492. /// ::= 'amdgpu_gs'
  1493. /// ::= 'amdgpu_ps'
  1494. /// ::= 'amdgpu_cs'
  1495. /// ::= 'amdgpu_kernel'
  1496. /// ::= 'cc' UINT
  1497. ///
  1498. bool LLParser::ParseOptionalCallingConv(unsigned &CC) {
  1499. switch (Lex.getKind()) {
  1500. default: CC = CallingConv::C; return false;
  1501. case lltok::kw_ccc: CC = CallingConv::C; break;
  1502. case lltok::kw_fastcc: CC = CallingConv::Fast; break;
  1503. case lltok::kw_coldcc: CC = CallingConv::Cold; break;
  1504. case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
  1505. case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
  1506. case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
  1507. case lltok::kw_x86_vectorcallcc:CC = CallingConv::X86_VectorCall; break;
  1508. case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
  1509. case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
  1510. case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
  1511. case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
  1512. case lltok::kw_avr_intrcc: CC = CallingConv::AVR_INTR; break;
  1513. case lltok::kw_avr_signalcc: CC = CallingConv::AVR_SIGNAL; break;
  1514. case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
  1515. case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
  1516. case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
  1517. case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
  1518. case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
  1519. case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
  1520. case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
  1521. case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
  1522. case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
  1523. case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
  1524. case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
  1525. case lltok::kw_ghccc: CC = CallingConv::GHC; break;
  1526. case lltok::kw_swiftcc: CC = CallingConv::Swift; break;
  1527. case lltok::kw_x86_intrcc: CC = CallingConv::X86_INTR; break;
  1528. case lltok::kw_hhvmcc: CC = CallingConv::HHVM; break;
  1529. case lltok::kw_hhvm_ccc: CC = CallingConv::HHVM_C; break;
  1530. case lltok::kw_cxx_fast_tlscc: CC = CallingConv::CXX_FAST_TLS; break;
  1531. case lltok::kw_amdgpu_vs: CC = CallingConv::AMDGPU_VS; break;
  1532. case lltok::kw_amdgpu_gs: CC = CallingConv::AMDGPU_GS; break;
  1533. case lltok::kw_amdgpu_ps: CC = CallingConv::AMDGPU_PS; break;
  1534. case lltok::kw_amdgpu_cs: CC = CallingConv::AMDGPU_CS; break;
  1535. case lltok::kw_amdgpu_kernel: CC = CallingConv::AMDGPU_KERNEL; break;
  1536. case lltok::kw_cc: {
  1537. Lex.Lex();
  1538. return ParseUInt32(CC);
  1539. }
  1540. }
  1541. Lex.Lex();
  1542. return false;
  1543. }
  1544. /// ParseMetadataAttachment
  1545. /// ::= !dbg !42
  1546. bool LLParser::ParseMetadataAttachment(unsigned &Kind, MDNode *&MD) {
  1547. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata attachment");
  1548. std::string Name = Lex.getStrVal();
  1549. Kind = M->getMDKindID(Name);
  1550. Lex.Lex();
  1551. return ParseMDNode(MD);
  1552. }
  1553. /// ParseInstructionMetadata
  1554. /// ::= !dbg !42 (',' !dbg !57)*
  1555. bool LLParser::ParseInstructionMetadata(Instruction &Inst) {
  1556. do {
  1557. if (Lex.getKind() != lltok::MetadataVar)
  1558. return TokError("expected metadata after comma");
  1559. unsigned MDK;
  1560. MDNode *N;
  1561. if (ParseMetadataAttachment(MDK, N))
  1562. return true;
  1563. Inst.setMetadata(MDK, N);
  1564. if (MDK == LLVMContext::MD_tbaa)
  1565. InstsWithTBAATag.push_back(&Inst);
  1566. // If this is the end of the list, we're done.
  1567. } while (EatIfPresent(lltok::comma));
  1568. return false;
  1569. }
  1570. /// ParseGlobalObjectMetadataAttachment
  1571. /// ::= !dbg !57
  1572. bool LLParser::ParseGlobalObjectMetadataAttachment(GlobalObject &GO) {
  1573. unsigned MDK;
  1574. MDNode *N;
  1575. if (ParseMetadataAttachment(MDK, N))
  1576. return true;
  1577. GO.addMetadata(MDK, *N);
  1578. return false;
  1579. }
  1580. /// ParseOptionalFunctionMetadata
  1581. /// ::= (!dbg !57)*
  1582. bool LLParser::ParseOptionalFunctionMetadata(Function &F) {
  1583. while (Lex.getKind() == lltok::MetadataVar)
  1584. if (ParseGlobalObjectMetadataAttachment(F))
  1585. return true;
  1586. return false;
  1587. }
  1588. /// ParseOptionalAlignment
  1589. /// ::= /* empty */
  1590. /// ::= 'align' 4
  1591. bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
  1592. Alignment = 0;
  1593. if (!EatIfPresent(lltok::kw_align))
  1594. return false;
  1595. LocTy AlignLoc = Lex.getLoc();
  1596. if (ParseUInt32(Alignment)) return true;
  1597. if (!isPowerOf2_32(Alignment))
  1598. return Error(AlignLoc, "alignment is not a power of two");
  1599. if (Alignment > Value::MaximumAlignment)
  1600. return Error(AlignLoc, "huge alignments are not supported yet");
  1601. return false;
  1602. }
  1603. /// ParseOptionalDerefAttrBytes
  1604. /// ::= /* empty */
  1605. /// ::= AttrKind '(' 4 ')'
  1606. ///
  1607. /// where AttrKind is either 'dereferenceable' or 'dereferenceable_or_null'.
  1608. bool LLParser::ParseOptionalDerefAttrBytes(lltok::Kind AttrKind,
  1609. uint64_t &Bytes) {
  1610. assert((AttrKind == lltok::kw_dereferenceable ||
  1611. AttrKind == lltok::kw_dereferenceable_or_null) &&
  1612. "contract!");
  1613. Bytes = 0;
  1614. if (!EatIfPresent(AttrKind))
  1615. return false;
  1616. LocTy ParenLoc = Lex.getLoc();
  1617. if (!EatIfPresent(lltok::lparen))
  1618. return Error(ParenLoc, "expected '('");
  1619. LocTy DerefLoc = Lex.getLoc();
  1620. if (ParseUInt64(Bytes)) return true;
  1621. ParenLoc = Lex.getLoc();
  1622. if (!EatIfPresent(lltok::rparen))
  1623. return Error(ParenLoc, "expected ')'");
  1624. if (!Bytes)
  1625. return Error(DerefLoc, "dereferenceable bytes must be non-zero");
  1626. return false;
  1627. }
  1628. /// ParseOptionalCommaAlign
  1629. /// ::=
  1630. /// ::= ',' align 4
  1631. ///
  1632. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  1633. /// end.
  1634. bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
  1635. bool &AteExtraComma) {
  1636. AteExtraComma = false;
  1637. while (EatIfPresent(lltok::comma)) {
  1638. // Metadata at the end is an early exit.
  1639. if (Lex.getKind() == lltok::MetadataVar) {
  1640. AteExtraComma = true;
  1641. return false;
  1642. }
  1643. if (Lex.getKind() != lltok::kw_align)
  1644. return Error(Lex.getLoc(), "expected metadata or 'align'");
  1645. if (ParseOptionalAlignment(Alignment)) return true;
  1646. }
  1647. return false;
  1648. }
  1649. bool LLParser::parseAllocSizeArguments(unsigned &BaseSizeArg,
  1650. Optional<unsigned> &HowManyArg) {
  1651. Lex.Lex();
  1652. auto StartParen = Lex.getLoc();
  1653. if (!EatIfPresent(lltok::lparen))
  1654. return Error(StartParen, "expected '('");
  1655. if (ParseUInt32(BaseSizeArg))
  1656. return true;
  1657. if (EatIfPresent(lltok::comma)) {
  1658. auto HowManyAt = Lex.getLoc();
  1659. unsigned HowMany;
  1660. if (ParseUInt32(HowMany))
  1661. return true;
  1662. if (HowMany == BaseSizeArg)
  1663. return Error(HowManyAt,
  1664. "'allocsize' indices can't refer to the same parameter");
  1665. HowManyArg = HowMany;
  1666. } else
  1667. HowManyArg = None;
  1668. auto EndParen = Lex.getLoc();
  1669. if (!EatIfPresent(lltok::rparen))
  1670. return Error(EndParen, "expected ')'");
  1671. return false;
  1672. }
  1673. /// ParseScopeAndOrdering
  1674. /// if isAtomic: ::= 'singlethread'? AtomicOrdering
  1675. /// else: ::=
  1676. ///
  1677. /// This sets Scope and Ordering to the parsed values.
  1678. bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
  1679. AtomicOrdering &Ordering) {
  1680. if (!isAtomic)
  1681. return false;
  1682. Scope = CrossThread;
  1683. if (EatIfPresent(lltok::kw_singlethread))
  1684. Scope = SingleThread;
  1685. return ParseOrdering(Ordering);
  1686. }
  1687. /// ParseOrdering
  1688. /// ::= AtomicOrdering
  1689. ///
  1690. /// This sets Ordering to the parsed value.
  1691. bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
  1692. switch (Lex.getKind()) {
  1693. default: return TokError("Expected ordering on atomic instruction");
  1694. case lltok::kw_unordered: Ordering = AtomicOrdering::Unordered; break;
  1695. case lltok::kw_monotonic: Ordering = AtomicOrdering::Monotonic; break;
  1696. // Not specified yet:
  1697. // case lltok::kw_consume: Ordering = AtomicOrdering::Consume; break;
  1698. case lltok::kw_acquire: Ordering = AtomicOrdering::Acquire; break;
  1699. case lltok::kw_release: Ordering = AtomicOrdering::Release; break;
  1700. case lltok::kw_acq_rel: Ordering = AtomicOrdering::AcquireRelease; break;
  1701. case lltok::kw_seq_cst:
  1702. Ordering = AtomicOrdering::SequentiallyConsistent;
  1703. break;
  1704. }
  1705. Lex.Lex();
  1706. return false;
  1707. }
  1708. /// ParseOptionalStackAlignment
  1709. /// ::= /* empty */
  1710. /// ::= 'alignstack' '(' 4 ')'
  1711. bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
  1712. Alignment = 0;
  1713. if (!EatIfPresent(lltok::kw_alignstack))
  1714. return false;
  1715. LocTy ParenLoc = Lex.getLoc();
  1716. if (!EatIfPresent(lltok::lparen))
  1717. return Error(ParenLoc, "expected '('");
  1718. LocTy AlignLoc = Lex.getLoc();
  1719. if (ParseUInt32(Alignment)) return true;
  1720. ParenLoc = Lex.getLoc();
  1721. if (!EatIfPresent(lltok::rparen))
  1722. return Error(ParenLoc, "expected ')'");
  1723. if (!isPowerOf2_32(Alignment))
  1724. return Error(AlignLoc, "stack alignment is not a power of two");
  1725. return false;
  1726. }
  1727. /// ParseIndexList - This parses the index list for an insert/extractvalue
  1728. /// instruction. This sets AteExtraComma in the case where we eat an extra
  1729. /// comma at the end of the line and find that it is followed by metadata.
  1730. /// Clients that don't allow metadata can call the version of this function that
  1731. /// only takes one argument.
  1732. ///
  1733. /// ParseIndexList
  1734. /// ::= (',' uint32)+
  1735. ///
  1736. bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
  1737. bool &AteExtraComma) {
  1738. AteExtraComma = false;
  1739. if (Lex.getKind() != lltok::comma)
  1740. return TokError("expected ',' as start of index list");
  1741. while (EatIfPresent(lltok::comma)) {
  1742. if (Lex.getKind() == lltok::MetadataVar) {
  1743. if (Indices.empty()) return TokError("expected index");
  1744. AteExtraComma = true;
  1745. return false;
  1746. }
  1747. unsigned Idx = 0;
  1748. if (ParseUInt32(Idx)) return true;
  1749. Indices.push_back(Idx);
  1750. }
  1751. return false;
  1752. }
  1753. //===----------------------------------------------------------------------===//
  1754. // Type Parsing.
  1755. //===----------------------------------------------------------------------===//
  1756. /// ParseType - Parse a type.
  1757. bool LLParser::ParseType(Type *&Result, const Twine &Msg, bool AllowVoid) {
  1758. SMLoc TypeLoc = Lex.getLoc();
  1759. switch (Lex.getKind()) {
  1760. default:
  1761. return TokError(Msg);
  1762. case lltok::Type:
  1763. // Type ::= 'float' | 'void' (etc)
  1764. Result = Lex.getTyVal();
  1765. Lex.Lex();
  1766. break;
  1767. case lltok::lbrace:
  1768. // Type ::= StructType
  1769. if (ParseAnonStructType(Result, false))
  1770. return true;
  1771. break;
  1772. case lltok::lsquare:
  1773. // Type ::= '[' ... ']'
  1774. Lex.Lex(); // eat the lsquare.
  1775. if (ParseArrayVectorType(Result, false))
  1776. return true;
  1777. break;
  1778. case lltok::less: // Either vector or packed struct.
  1779. // Type ::= '<' ... '>'
  1780. Lex.Lex();
  1781. if (Lex.getKind() == lltok::lbrace) {
  1782. if (ParseAnonStructType(Result, true) ||
  1783. ParseToken(lltok::greater, "expected '>' at end of packed struct"))
  1784. return true;
  1785. } else if (ParseArrayVectorType(Result, true))
  1786. return true;
  1787. break;
  1788. case lltok::LocalVar: {
  1789. // Type ::= %foo
  1790. std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
  1791. // If the type hasn't been defined yet, create a forward definition and
  1792. // remember where that forward def'n was seen (in case it never is defined).
  1793. if (!Entry.first) {
  1794. Entry.first = StructType::create(Context, Lex.getStrVal());
  1795. Entry.second = Lex.getLoc();
  1796. }
  1797. Result = Entry.first;
  1798. Lex.Lex();
  1799. break;
  1800. }
  1801. case lltok::LocalVarID: {
  1802. // Type ::= %4
  1803. std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
  1804. // If the type hasn't been defined yet, create a forward definition and
  1805. // remember where that forward def'n was seen (in case it never is defined).
  1806. if (!Entry.first) {
  1807. Entry.first = StructType::create(Context);
  1808. Entry.second = Lex.getLoc();
  1809. }
  1810. Result = Entry.first;
  1811. Lex.Lex();
  1812. break;
  1813. }
  1814. }
  1815. // Parse the type suffixes.
  1816. while (true) {
  1817. switch (Lex.getKind()) {
  1818. // End of type.
  1819. default:
  1820. if (!AllowVoid && Result->isVoidTy())
  1821. return Error(TypeLoc, "void type only allowed for function results");
  1822. return false;
  1823. // Type ::= Type '*'
  1824. case lltok::star:
  1825. if (Result->isLabelTy())
  1826. return TokError("basic block pointers are invalid");
  1827. if (Result->isVoidTy())
  1828. return TokError("pointers to void are invalid - use i8* instead");
  1829. if (!PointerType::isValidElementType(Result))
  1830. return TokError("pointer to this type is invalid");
  1831. Result = PointerType::getUnqual(Result);
  1832. Lex.Lex();
  1833. break;
  1834. // Type ::= Type 'addrspace' '(' uint32 ')' '*'
  1835. case lltok::kw_addrspace: {
  1836. if (Result->isLabelTy())
  1837. return TokError("basic block pointers are invalid");
  1838. if (Result->isVoidTy())
  1839. return TokError("pointers to void are invalid; use i8* instead");
  1840. if (!PointerType::isValidElementType(Result))
  1841. return TokError("pointer to this type is invalid");
  1842. unsigned AddrSpace;
  1843. if (ParseOptionalAddrSpace(AddrSpace) ||
  1844. ParseToken(lltok::star, "expected '*' in address space"))
  1845. return true;
  1846. Result = PointerType::get(Result, AddrSpace);
  1847. break;
  1848. }
  1849. /// Types '(' ArgTypeListI ')' OptFuncAttrs
  1850. case lltok::lparen:
  1851. if (ParseFunctionType(Result))
  1852. return true;
  1853. break;
  1854. }
  1855. }
  1856. }
  1857. /// ParseParameterList
  1858. /// ::= '(' ')'
  1859. /// ::= '(' Arg (',' Arg)* ')'
  1860. /// Arg
  1861. /// ::= Type OptionalAttributes Value OptionalAttributes
  1862. bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
  1863. PerFunctionState &PFS, bool IsMustTailCall,
  1864. bool InVarArgsFunc) {
  1865. if (ParseToken(lltok::lparen, "expected '(' in call"))
  1866. return true;
  1867. unsigned AttrIndex = 1;
  1868. while (Lex.getKind() != lltok::rparen) {
  1869. // If this isn't the first argument, we need a comma.
  1870. if (!ArgList.empty() &&
  1871. ParseToken(lltok::comma, "expected ',' in argument list"))
  1872. return true;
  1873. // Parse an ellipsis if this is a musttail call in a variadic function.
  1874. if (Lex.getKind() == lltok::dotdotdot) {
  1875. const char *Msg = "unexpected ellipsis in argument list for ";
  1876. if (!IsMustTailCall)
  1877. return TokError(Twine(Msg) + "non-musttail call");
  1878. if (!InVarArgsFunc)
  1879. return TokError(Twine(Msg) + "musttail call in non-varargs function");
  1880. Lex.Lex(); // Lex the '...', it is purely for readability.
  1881. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  1882. }
  1883. // Parse the argument.
  1884. LocTy ArgLoc;
  1885. Type *ArgTy = nullptr;
  1886. AttrBuilder ArgAttrs;
  1887. Value *V;
  1888. if (ParseType(ArgTy, ArgLoc))
  1889. return true;
  1890. if (ArgTy->isMetadataTy()) {
  1891. if (ParseMetadataAsValue(V, PFS))
  1892. return true;
  1893. } else {
  1894. // Otherwise, handle normal operands.
  1895. if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
  1896. return true;
  1897. }
  1898. ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
  1899. AttrIndex++,
  1900. ArgAttrs)));
  1901. }
  1902. if (IsMustTailCall && InVarArgsFunc)
  1903. return TokError("expected '...' at end of argument list for musttail call "
  1904. "in varargs function");
  1905. Lex.Lex(); // Lex the ')'.
  1906. return false;
  1907. }
  1908. /// ParseOptionalOperandBundles
  1909. /// ::= /*empty*/
  1910. /// ::= '[' OperandBundle [, OperandBundle ]* ']'
  1911. ///
  1912. /// OperandBundle
  1913. /// ::= bundle-tag '(' ')'
  1914. /// ::= bundle-tag '(' Type Value [, Type Value ]* ')'
  1915. ///
  1916. /// bundle-tag ::= String Constant
  1917. bool LLParser::ParseOptionalOperandBundles(
  1918. SmallVectorImpl<OperandBundleDef> &BundleList, PerFunctionState &PFS) {
  1919. LocTy BeginLoc = Lex.getLoc();
  1920. if (!EatIfPresent(lltok::lsquare))
  1921. return false;
  1922. while (Lex.getKind() != lltok::rsquare) {
  1923. // If this isn't the first operand bundle, we need a comma.
  1924. if (!BundleList.empty() &&
  1925. ParseToken(lltok::comma, "expected ',' in input list"))
  1926. return true;
  1927. std::string Tag;
  1928. if (ParseStringConstant(Tag))
  1929. return true;
  1930. if (ParseToken(lltok::lparen, "expected '(' in operand bundle"))
  1931. return true;
  1932. std::vector<Value *> Inputs;
  1933. while (Lex.getKind() != lltok::rparen) {
  1934. // If this isn't the first input, we need a comma.
  1935. if (!Inputs.empty() &&
  1936. ParseToken(lltok::comma, "expected ',' in input list"))
  1937. return true;
  1938. Type *Ty = nullptr;
  1939. Value *Input = nullptr;
  1940. if (ParseType(Ty) || ParseValue(Ty, Input, PFS))
  1941. return true;
  1942. Inputs.push_back(Input);
  1943. }
  1944. BundleList.emplace_back(std::move(Tag), std::move(Inputs));
  1945. Lex.Lex(); // Lex the ')'.
  1946. }
  1947. if (BundleList.empty())
  1948. return Error(BeginLoc, "operand bundle set must not be empty");
  1949. Lex.Lex(); // Lex the ']'.
  1950. return false;
  1951. }
  1952. /// ParseArgumentList - Parse the argument list for a function type or function
  1953. /// prototype.
  1954. /// ::= '(' ArgTypeListI ')'
  1955. /// ArgTypeListI
  1956. /// ::= /*empty*/
  1957. /// ::= '...'
  1958. /// ::= ArgTypeList ',' '...'
  1959. /// ::= ArgType (',' ArgType)*
  1960. ///
  1961. bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
  1962. bool &isVarArg){
  1963. isVarArg = false;
  1964. assert(Lex.getKind() == lltok::lparen);
  1965. Lex.Lex(); // eat the (.
  1966. if (Lex.getKind() == lltok::rparen) {
  1967. // empty
  1968. } else if (Lex.getKind() == lltok::dotdotdot) {
  1969. isVarArg = true;
  1970. Lex.Lex();
  1971. } else {
  1972. LocTy TypeLoc = Lex.getLoc();
  1973. Type *ArgTy = nullptr;
  1974. AttrBuilder Attrs;
  1975. std::string Name;
  1976. if (ParseType(ArgTy) ||
  1977. ParseOptionalParamAttrs(Attrs)) return true;
  1978. if (ArgTy->isVoidTy())
  1979. return Error(TypeLoc, "argument can not have void type");
  1980. if (Lex.getKind() == lltok::LocalVar) {
  1981. Name = Lex.getStrVal();
  1982. Lex.Lex();
  1983. }
  1984. if (!FunctionType::isValidArgumentType(ArgTy))
  1985. return Error(TypeLoc, "invalid type for function argument");
  1986. unsigned AttrIndex = 1;
  1987. ArgList.emplace_back(TypeLoc, ArgTy, AttributeSet::get(ArgTy->getContext(),
  1988. AttrIndex++, Attrs),
  1989. std::move(Name));
  1990. while (EatIfPresent(lltok::comma)) {
  1991. // Handle ... at end of arg list.
  1992. if (EatIfPresent(lltok::dotdotdot)) {
  1993. isVarArg = true;
  1994. break;
  1995. }
  1996. // Otherwise must be an argument type.
  1997. TypeLoc = Lex.getLoc();
  1998. if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
  1999. if (ArgTy->isVoidTy())
  2000. return Error(TypeLoc, "argument can not have void type");
  2001. if (Lex.getKind() == lltok::LocalVar) {
  2002. Name = Lex.getStrVal();
  2003. Lex.Lex();
  2004. } else {
  2005. Name = "";
  2006. }
  2007. if (!ArgTy->isFirstClassType())
  2008. return Error(TypeLoc, "invalid type for function argument");
  2009. ArgList.emplace_back(
  2010. TypeLoc, ArgTy,
  2011. AttributeSet::get(ArgTy->getContext(), AttrIndex++, Attrs),
  2012. std::move(Name));
  2013. }
  2014. }
  2015. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  2016. }
  2017. /// ParseFunctionType
  2018. /// ::= Type ArgumentList OptionalAttrs
  2019. bool LLParser::ParseFunctionType(Type *&Result) {
  2020. assert(Lex.getKind() == lltok::lparen);
  2021. if (!FunctionType::isValidReturnType(Result))
  2022. return TokError("invalid function return type");
  2023. SmallVector<ArgInfo, 8> ArgList;
  2024. bool isVarArg;
  2025. if (ParseArgumentList(ArgList, isVarArg))
  2026. return true;
  2027. // Reject names on the arguments lists.
  2028. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2029. if (!ArgList[i].Name.empty())
  2030. return Error(ArgList[i].Loc, "argument name invalid in function type");
  2031. if (ArgList[i].Attrs.hasAttributes(i + 1))
  2032. return Error(ArgList[i].Loc,
  2033. "argument attributes invalid in function type");
  2034. }
  2035. SmallVector<Type*, 16> ArgListTy;
  2036. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  2037. ArgListTy.push_back(ArgList[i].Ty);
  2038. Result = FunctionType::get(Result, ArgListTy, isVarArg);
  2039. return false;
  2040. }
  2041. /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
  2042. /// other structs.
  2043. bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
  2044. SmallVector<Type*, 8> Elts;
  2045. if (ParseStructBody(Elts)) return true;
  2046. Result = StructType::get(Context, Elts, Packed);
  2047. return false;
  2048. }
  2049. /// ParseStructDefinition - Parse a struct in a 'type' definition.
  2050. bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
  2051. std::pair<Type*, LocTy> &Entry,
  2052. Type *&ResultTy) {
  2053. // If the type was already defined, diagnose the redefinition.
  2054. if (Entry.first && !Entry.second.isValid())
  2055. return Error(TypeLoc, "redefinition of type");
  2056. // If we have opaque, just return without filling in the definition for the
  2057. // struct. This counts as a definition as far as the .ll file goes.
  2058. if (EatIfPresent(lltok::kw_opaque)) {
  2059. // This type is being defined, so clear the location to indicate this.
  2060. Entry.second = SMLoc();
  2061. // If this type number has never been uttered, create it.
  2062. if (!Entry.first)
  2063. Entry.first = StructType::create(Context, Name);
  2064. ResultTy = Entry.first;
  2065. return false;
  2066. }
  2067. // If the type starts with '<', then it is either a packed struct or a vector.
  2068. bool isPacked = EatIfPresent(lltok::less);
  2069. // If we don't have a struct, then we have a random type alias, which we
  2070. // accept for compatibility with old files. These types are not allowed to be
  2071. // forward referenced and not allowed to be recursive.
  2072. if (Lex.getKind() != lltok::lbrace) {
  2073. if (Entry.first)
  2074. return Error(TypeLoc, "forward references to non-struct type");
  2075. ResultTy = nullptr;
  2076. if (isPacked)
  2077. return ParseArrayVectorType(ResultTy, true);
  2078. return ParseType(ResultTy);
  2079. }
  2080. // This type is being defined, so clear the location to indicate this.
  2081. Entry.second = SMLoc();
  2082. // If this type number has never been uttered, create it.
  2083. if (!Entry.first)
  2084. Entry.first = StructType::create(Context, Name);
  2085. StructType *STy = cast<StructType>(Entry.first);
  2086. SmallVector<Type*, 8> Body;
  2087. if (ParseStructBody(Body) ||
  2088. (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
  2089. return true;
  2090. STy->setBody(Body, isPacked);
  2091. ResultTy = STy;
  2092. return false;
  2093. }
  2094. /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
  2095. /// StructType
  2096. /// ::= '{' '}'
  2097. /// ::= '{' Type (',' Type)* '}'
  2098. /// ::= '<' '{' '}' '>'
  2099. /// ::= '<' '{' Type (',' Type)* '}' '>'
  2100. bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
  2101. assert(Lex.getKind() == lltok::lbrace);
  2102. Lex.Lex(); // Consume the '{'
  2103. // Handle the empty struct.
  2104. if (EatIfPresent(lltok::rbrace))
  2105. return false;
  2106. LocTy EltTyLoc = Lex.getLoc();
  2107. Type *Ty = nullptr;
  2108. if (ParseType(Ty)) return true;
  2109. Body.push_back(Ty);
  2110. if (!StructType::isValidElementType(Ty))
  2111. return Error(EltTyLoc, "invalid element type for struct");
  2112. while (EatIfPresent(lltok::comma)) {
  2113. EltTyLoc = Lex.getLoc();
  2114. if (ParseType(Ty)) return true;
  2115. if (!StructType::isValidElementType(Ty))
  2116. return Error(EltTyLoc, "invalid element type for struct");
  2117. Body.push_back(Ty);
  2118. }
  2119. return ParseToken(lltok::rbrace, "expected '}' at end of struct");
  2120. }
  2121. /// ParseArrayVectorType - Parse an array or vector type, assuming the first
  2122. /// token has already been consumed.
  2123. /// Type
  2124. /// ::= '[' APSINTVAL 'x' Types ']'
  2125. /// ::= '<' APSINTVAL 'x' Types '>'
  2126. bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
  2127. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
  2128. Lex.getAPSIntVal().getBitWidth() > 64)
  2129. return TokError("expected number in address space");
  2130. LocTy SizeLoc = Lex.getLoc();
  2131. uint64_t Size = Lex.getAPSIntVal().getZExtValue();
  2132. Lex.Lex();
  2133. if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
  2134. return true;
  2135. LocTy TypeLoc = Lex.getLoc();
  2136. Type *EltTy = nullptr;
  2137. if (ParseType(EltTy)) return true;
  2138. if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
  2139. "expected end of sequential type"))
  2140. return true;
  2141. if (isVector) {
  2142. if (Size == 0)
  2143. return Error(SizeLoc, "zero element vector is illegal");
  2144. if ((unsigned)Size != Size)
  2145. return Error(SizeLoc, "size too large for vector");
  2146. if (!VectorType::isValidElementType(EltTy))
  2147. return Error(TypeLoc, "invalid vector element type");
  2148. Result = VectorType::get(EltTy, unsigned(Size));
  2149. } else {
  2150. if (!ArrayType::isValidElementType(EltTy))
  2151. return Error(TypeLoc, "invalid array element type");
  2152. Result = ArrayType::get(EltTy, Size);
  2153. }
  2154. return false;
  2155. }
  2156. //===----------------------------------------------------------------------===//
  2157. // Function Semantic Analysis.
  2158. //===----------------------------------------------------------------------===//
  2159. LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
  2160. int functionNumber)
  2161. : P(p), F(f), FunctionNumber(functionNumber) {
  2162. // Insert unnamed arguments into the NumberedVals list.
  2163. for (Argument &A : F.args())
  2164. if (!A.hasName())
  2165. NumberedVals.push_back(&A);
  2166. }
  2167. LLParser::PerFunctionState::~PerFunctionState() {
  2168. // If there were any forward referenced non-basicblock values, delete them.
  2169. for (const auto &P : ForwardRefVals) {
  2170. if (isa<BasicBlock>(P.second.first))
  2171. continue;
  2172. P.second.first->replaceAllUsesWith(
  2173. UndefValue::get(P.second.first->getType()));
  2174. delete P.second.first;
  2175. }
  2176. for (const auto &P : ForwardRefValIDs) {
  2177. if (isa<BasicBlock>(P.second.first))
  2178. continue;
  2179. P.second.first->replaceAllUsesWith(
  2180. UndefValue::get(P.second.first->getType()));
  2181. delete P.second.first;
  2182. }
  2183. }
  2184. bool LLParser::PerFunctionState::FinishFunction() {
  2185. if (!ForwardRefVals.empty())
  2186. return P.Error(ForwardRefVals.begin()->second.second,
  2187. "use of undefined value '%" + ForwardRefVals.begin()->first +
  2188. "'");
  2189. if (!ForwardRefValIDs.empty())
  2190. return P.Error(ForwardRefValIDs.begin()->second.second,
  2191. "use of undefined value '%" +
  2192. Twine(ForwardRefValIDs.begin()->first) + "'");
  2193. return false;
  2194. }
  2195. /// GetVal - Get a value with the specified name or ID, creating a
  2196. /// forward reference record if needed. This can return null if the value
  2197. /// exists but does not have the right type.
  2198. Value *LLParser::PerFunctionState::GetVal(const std::string &Name, Type *Ty,
  2199. LocTy Loc) {
  2200. // Look this name up in the normal function symbol table.
  2201. Value *Val = F.getValueSymbolTable().lookup(Name);
  2202. // If this is a forward reference for the value, see if we already created a
  2203. // forward ref record.
  2204. if (!Val) {
  2205. auto I = ForwardRefVals.find(Name);
  2206. if (I != ForwardRefVals.end())
  2207. Val = I->second.first;
  2208. }
  2209. // If we have the value in the symbol table or fwd-ref table, return it.
  2210. if (Val) {
  2211. if (Val->getType() == Ty) return Val;
  2212. if (Ty->isLabelTy())
  2213. P.Error(Loc, "'%" + Name + "' is not a basic block");
  2214. else
  2215. P.Error(Loc, "'%" + Name + "' defined with type '" +
  2216. getTypeString(Val->getType()) + "'");
  2217. return nullptr;
  2218. }
  2219. // Don't make placeholders with invalid type.
  2220. if (!Ty->isFirstClassType()) {
  2221. P.Error(Loc, "invalid use of a non-first-class type");
  2222. return nullptr;
  2223. }
  2224. // Otherwise, create a new forward reference for this value and remember it.
  2225. Value *FwdVal;
  2226. if (Ty->isLabelTy()) {
  2227. FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
  2228. } else {
  2229. FwdVal = new Argument(Ty, Name);
  2230. }
  2231. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  2232. return FwdVal;
  2233. }
  2234. Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty, LocTy Loc) {
  2235. // Look this name up in the normal function symbol table.
  2236. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : nullptr;
  2237. // If this is a forward reference for the value, see if we already created a
  2238. // forward ref record.
  2239. if (!Val) {
  2240. auto I = ForwardRefValIDs.find(ID);
  2241. if (I != ForwardRefValIDs.end())
  2242. Val = I->second.first;
  2243. }
  2244. // If we have the value in the symbol table or fwd-ref table, return it.
  2245. if (Val) {
  2246. if (Val->getType() == Ty) return Val;
  2247. if (Ty->isLabelTy())
  2248. P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
  2249. else
  2250. P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
  2251. getTypeString(Val->getType()) + "'");
  2252. return nullptr;
  2253. }
  2254. if (!Ty->isFirstClassType()) {
  2255. P.Error(Loc, "invalid use of a non-first-class type");
  2256. return nullptr;
  2257. }
  2258. // Otherwise, create a new forward reference for this value and remember it.
  2259. Value *FwdVal;
  2260. if (Ty->isLabelTy()) {
  2261. FwdVal = BasicBlock::Create(F.getContext(), "", &F);
  2262. } else {
  2263. FwdVal = new Argument(Ty);
  2264. }
  2265. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  2266. return FwdVal;
  2267. }
  2268. /// SetInstName - After an instruction is parsed and inserted into its
  2269. /// basic block, this installs its name.
  2270. bool LLParser::PerFunctionState::SetInstName(int NameID,
  2271. const std::string &NameStr,
  2272. LocTy NameLoc, Instruction *Inst) {
  2273. // If this instruction has void type, it cannot have a name or ID specified.
  2274. if (Inst->getType()->isVoidTy()) {
  2275. if (NameID != -1 || !NameStr.empty())
  2276. return P.Error(NameLoc, "instructions returning void cannot have a name");
  2277. return false;
  2278. }
  2279. // If this was a numbered instruction, verify that the instruction is the
  2280. // expected value and resolve any forward references.
  2281. if (NameStr.empty()) {
  2282. // If neither a name nor an ID was specified, just use the next ID.
  2283. if (NameID == -1)
  2284. NameID = NumberedVals.size();
  2285. if (unsigned(NameID) != NumberedVals.size())
  2286. return P.Error(NameLoc, "instruction expected to be numbered '%" +
  2287. Twine(NumberedVals.size()) + "'");
  2288. auto FI = ForwardRefValIDs.find(NameID);
  2289. if (FI != ForwardRefValIDs.end()) {
  2290. Value *Sentinel = FI->second.first;
  2291. if (Sentinel->getType() != Inst->getType())
  2292. return P.Error(NameLoc, "instruction forward referenced with type '" +
  2293. getTypeString(FI->second.first->getType()) + "'");
  2294. Sentinel->replaceAllUsesWith(Inst);
  2295. delete Sentinel;
  2296. ForwardRefValIDs.erase(FI);
  2297. }
  2298. NumberedVals.push_back(Inst);
  2299. return false;
  2300. }
  2301. // Otherwise, the instruction had a name. Resolve forward refs and set it.
  2302. auto FI = ForwardRefVals.find(NameStr);
  2303. if (FI != ForwardRefVals.end()) {
  2304. Value *Sentinel = FI->second.first;
  2305. if (Sentinel->getType() != Inst->getType())
  2306. return P.Error(NameLoc, "instruction forward referenced with type '" +
  2307. getTypeString(FI->second.first->getType()) + "'");
  2308. Sentinel->replaceAllUsesWith(Inst);
  2309. delete Sentinel;
  2310. ForwardRefVals.erase(FI);
  2311. }
  2312. // Set the name on the instruction.
  2313. Inst->setName(NameStr);
  2314. if (Inst->getName() != NameStr)
  2315. return P.Error(NameLoc, "multiple definition of local value named '" +
  2316. NameStr + "'");
  2317. return false;
  2318. }
  2319. /// GetBB - Get a basic block with the specified name or ID, creating a
  2320. /// forward reference record if needed.
  2321. BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
  2322. LocTy Loc) {
  2323. return dyn_cast_or_null<BasicBlock>(GetVal(Name,
  2324. Type::getLabelTy(F.getContext()), Loc));
  2325. }
  2326. BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
  2327. return dyn_cast_or_null<BasicBlock>(GetVal(ID,
  2328. Type::getLabelTy(F.getContext()), Loc));
  2329. }
  2330. /// DefineBB - Define the specified basic block, which is either named or
  2331. /// unnamed. If there is an error, this returns null otherwise it returns
  2332. /// the block being defined.
  2333. BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
  2334. LocTy Loc) {
  2335. BasicBlock *BB;
  2336. if (Name.empty())
  2337. BB = GetBB(NumberedVals.size(), Loc);
  2338. else
  2339. BB = GetBB(Name, Loc);
  2340. if (!BB) return nullptr; // Already diagnosed error.
  2341. // Move the block to the end of the function. Forward ref'd blocks are
  2342. // inserted wherever they happen to be referenced.
  2343. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
  2344. // Remove the block from forward ref sets.
  2345. if (Name.empty()) {
  2346. ForwardRefValIDs.erase(NumberedVals.size());
  2347. NumberedVals.push_back(BB);
  2348. } else {
  2349. // BB forward references are already in the function symbol table.
  2350. ForwardRefVals.erase(Name);
  2351. }
  2352. return BB;
  2353. }
  2354. //===----------------------------------------------------------------------===//
  2355. // Constants.
  2356. //===----------------------------------------------------------------------===//
  2357. /// ParseValID - Parse an abstract value that doesn't necessarily have a
  2358. /// type implied. For example, if we parse "4" we don't know what integer type
  2359. /// it has. The value will later be combined with its type and checked for
  2360. /// sanity. PFS is used to convert function-local operands of metadata (since
  2361. /// metadata operands are not just parsed here but also converted to values).
  2362. /// PFS can be null when we are not parsing metadata values inside a function.
  2363. bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
  2364. ID.Loc = Lex.getLoc();
  2365. switch (Lex.getKind()) {
  2366. default: return TokError("expected value token");
  2367. case lltok::GlobalID: // @42
  2368. ID.UIntVal = Lex.getUIntVal();
  2369. ID.Kind = ValID::t_GlobalID;
  2370. break;
  2371. case lltok::GlobalVar: // @foo
  2372. ID.StrVal = Lex.getStrVal();
  2373. ID.Kind = ValID::t_GlobalName;
  2374. break;
  2375. case lltok::LocalVarID: // %42
  2376. ID.UIntVal = Lex.getUIntVal();
  2377. ID.Kind = ValID::t_LocalID;
  2378. break;
  2379. case lltok::LocalVar: // %foo
  2380. ID.StrVal = Lex.getStrVal();
  2381. ID.Kind = ValID::t_LocalName;
  2382. break;
  2383. case lltok::APSInt:
  2384. ID.APSIntVal = Lex.getAPSIntVal();
  2385. ID.Kind = ValID::t_APSInt;
  2386. break;
  2387. case lltok::APFloat:
  2388. ID.APFloatVal = Lex.getAPFloatVal();
  2389. ID.Kind = ValID::t_APFloat;
  2390. break;
  2391. case lltok::kw_true:
  2392. ID.ConstantVal = ConstantInt::getTrue(Context);
  2393. ID.Kind = ValID::t_Constant;
  2394. break;
  2395. case lltok::kw_false:
  2396. ID.ConstantVal = ConstantInt::getFalse(Context);
  2397. ID.Kind = ValID::t_Constant;
  2398. break;
  2399. case lltok::kw_null: ID.Kind = ValID::t_Null; break;
  2400. case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
  2401. case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
  2402. case lltok::kw_none: ID.Kind = ValID::t_None; break;
  2403. case lltok::lbrace: {
  2404. // ValID ::= '{' ConstVector '}'
  2405. Lex.Lex();
  2406. SmallVector<Constant*, 16> Elts;
  2407. if (ParseGlobalValueVector(Elts) ||
  2408. ParseToken(lltok::rbrace, "expected end of struct constant"))
  2409. return true;
  2410. ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
  2411. ID.UIntVal = Elts.size();
  2412. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  2413. Elts.size() * sizeof(Elts[0]));
  2414. ID.Kind = ValID::t_ConstantStruct;
  2415. return false;
  2416. }
  2417. case lltok::less: {
  2418. // ValID ::= '<' ConstVector '>' --> Vector.
  2419. // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
  2420. Lex.Lex();
  2421. bool isPackedStruct = EatIfPresent(lltok::lbrace);
  2422. SmallVector<Constant*, 16> Elts;
  2423. LocTy FirstEltLoc = Lex.getLoc();
  2424. if (ParseGlobalValueVector(Elts) ||
  2425. (isPackedStruct &&
  2426. ParseToken(lltok::rbrace, "expected end of packed struct")) ||
  2427. ParseToken(lltok::greater, "expected end of constant"))
  2428. return true;
  2429. if (isPackedStruct) {
  2430. ID.ConstantStructElts = make_unique<Constant *[]>(Elts.size());
  2431. memcpy(ID.ConstantStructElts.get(), Elts.data(),
  2432. Elts.size() * sizeof(Elts[0]));
  2433. ID.UIntVal = Elts.size();
  2434. ID.Kind = ValID::t_PackedConstantStruct;
  2435. return false;
  2436. }
  2437. if (Elts.empty())
  2438. return Error(ID.Loc, "constant vector must not be empty");
  2439. if (!Elts[0]->getType()->isIntegerTy() &&
  2440. !Elts[0]->getType()->isFloatingPointTy() &&
  2441. !Elts[0]->getType()->isPointerTy())
  2442. return Error(FirstEltLoc,
  2443. "vector elements must have integer, pointer or floating point type");
  2444. // Verify that all the vector elements have the same type.
  2445. for (unsigned i = 1, e = Elts.size(); i != e; ++i)
  2446. if (Elts[i]->getType() != Elts[0]->getType())
  2447. return Error(FirstEltLoc,
  2448. "vector element #" + Twine(i) +
  2449. " is not of type '" + getTypeString(Elts[0]->getType()));
  2450. ID.ConstantVal = ConstantVector::get(Elts);
  2451. ID.Kind = ValID::t_Constant;
  2452. return false;
  2453. }
  2454. case lltok::lsquare: { // Array Constant
  2455. Lex.Lex();
  2456. SmallVector<Constant*, 16> Elts;
  2457. LocTy FirstEltLoc = Lex.getLoc();
  2458. if (ParseGlobalValueVector(Elts) ||
  2459. ParseToken(lltok::rsquare, "expected end of array constant"))
  2460. return true;
  2461. // Handle empty element.
  2462. if (Elts.empty()) {
  2463. // Use undef instead of an array because it's inconvenient to determine
  2464. // the element type at this point, there being no elements to examine.
  2465. ID.Kind = ValID::t_EmptyArray;
  2466. return false;
  2467. }
  2468. if (!Elts[0]->getType()->isFirstClassType())
  2469. return Error(FirstEltLoc, "invalid array element type: " +
  2470. getTypeString(Elts[0]->getType()));
  2471. ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
  2472. // Verify all elements are correct type!
  2473. for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
  2474. if (Elts[i]->getType() != Elts[0]->getType())
  2475. return Error(FirstEltLoc,
  2476. "array element #" + Twine(i) +
  2477. " is not of type '" + getTypeString(Elts[0]->getType()));
  2478. }
  2479. ID.ConstantVal = ConstantArray::get(ATy, Elts);
  2480. ID.Kind = ValID::t_Constant;
  2481. return false;
  2482. }
  2483. case lltok::kw_c: // c "foo"
  2484. Lex.Lex();
  2485. ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
  2486. false);
  2487. if (ParseToken(lltok::StringConstant, "expected string")) return true;
  2488. ID.Kind = ValID::t_Constant;
  2489. return false;
  2490. case lltok::kw_asm: {
  2491. // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
  2492. // STRINGCONSTANT
  2493. bool HasSideEffect, AlignStack, AsmDialect;
  2494. Lex.Lex();
  2495. if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
  2496. ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
  2497. ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
  2498. ParseStringConstant(ID.StrVal) ||
  2499. ParseToken(lltok::comma, "expected comma in inline asm expression") ||
  2500. ParseToken(lltok::StringConstant, "expected constraint string"))
  2501. return true;
  2502. ID.StrVal2 = Lex.getStrVal();
  2503. ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
  2504. (unsigned(AsmDialect)<<2);
  2505. ID.Kind = ValID::t_InlineAsm;
  2506. return false;
  2507. }
  2508. case lltok::kw_blockaddress: {
  2509. // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
  2510. Lex.Lex();
  2511. ValID Fn, Label;
  2512. if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
  2513. ParseValID(Fn) ||
  2514. ParseToken(lltok::comma, "expected comma in block address expression")||
  2515. ParseValID(Label) ||
  2516. ParseToken(lltok::rparen, "expected ')' in block address expression"))
  2517. return true;
  2518. if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
  2519. return Error(Fn.Loc, "expected function name in blockaddress");
  2520. if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
  2521. return Error(Label.Loc, "expected basic block name in blockaddress");
  2522. // Try to find the function (but skip it if it's forward-referenced).
  2523. GlobalValue *GV = nullptr;
  2524. if (Fn.Kind == ValID::t_GlobalID) {
  2525. if (Fn.UIntVal < NumberedVals.size())
  2526. GV = NumberedVals[Fn.UIntVal];
  2527. } else if (!ForwardRefVals.count(Fn.StrVal)) {
  2528. GV = M->getNamedValue(Fn.StrVal);
  2529. }
  2530. Function *F = nullptr;
  2531. if (GV) {
  2532. // Confirm that it's actually a function with a definition.
  2533. if (!isa<Function>(GV))
  2534. return Error(Fn.Loc, "expected function name in blockaddress");
  2535. F = cast<Function>(GV);
  2536. if (F->isDeclaration())
  2537. return Error(Fn.Loc, "cannot take blockaddress inside a declaration");
  2538. }
  2539. if (!F) {
  2540. // Make a global variable as a placeholder for this reference.
  2541. GlobalValue *&FwdRef =
  2542. ForwardRefBlockAddresses.insert(std::make_pair(
  2543. std::move(Fn),
  2544. std::map<ValID, GlobalValue *>()))
  2545. .first->second.insert(std::make_pair(std::move(Label), nullptr))
  2546. .first->second;
  2547. if (!FwdRef)
  2548. FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context), false,
  2549. GlobalValue::InternalLinkage, nullptr, "");
  2550. ID.ConstantVal = FwdRef;
  2551. ID.Kind = ValID::t_Constant;
  2552. return false;
  2553. }
  2554. // We found the function; now find the basic block. Don't use PFS, since we
  2555. // might be inside a constant expression.
  2556. BasicBlock *BB;
  2557. if (BlockAddressPFS && F == &BlockAddressPFS->getFunction()) {
  2558. if (Label.Kind == ValID::t_LocalID)
  2559. BB = BlockAddressPFS->GetBB(Label.UIntVal, Label.Loc);
  2560. else
  2561. BB = BlockAddressPFS->GetBB(Label.StrVal, Label.Loc);
  2562. if (!BB)
  2563. return Error(Label.Loc, "referenced value is not a basic block");
  2564. } else {
  2565. if (Label.Kind == ValID::t_LocalID)
  2566. return Error(Label.Loc, "cannot take address of numeric label after "
  2567. "the function is defined");
  2568. BB = dyn_cast_or_null<BasicBlock>(
  2569. F->getValueSymbolTable().lookup(Label.StrVal));
  2570. if (!BB)
  2571. return Error(Label.Loc, "referenced value is not a basic block");
  2572. }
  2573. ID.ConstantVal = BlockAddress::get(F, BB);
  2574. ID.Kind = ValID::t_Constant;
  2575. return false;
  2576. }
  2577. case lltok::kw_trunc:
  2578. case lltok::kw_zext:
  2579. case lltok::kw_sext:
  2580. case lltok::kw_fptrunc:
  2581. case lltok::kw_fpext:
  2582. case lltok::kw_bitcast:
  2583. case lltok::kw_addrspacecast:
  2584. case lltok::kw_uitofp:
  2585. case lltok::kw_sitofp:
  2586. case lltok::kw_fptoui:
  2587. case lltok::kw_fptosi:
  2588. case lltok::kw_inttoptr:
  2589. case lltok::kw_ptrtoint: {
  2590. unsigned Opc = Lex.getUIntVal();
  2591. Type *DestTy = nullptr;
  2592. Constant *SrcVal;
  2593. Lex.Lex();
  2594. if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
  2595. ParseGlobalTypeAndValue(SrcVal) ||
  2596. ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
  2597. ParseType(DestTy) ||
  2598. ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
  2599. return true;
  2600. if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
  2601. return Error(ID.Loc, "invalid cast opcode for cast from '" +
  2602. getTypeString(SrcVal->getType()) + "' to '" +
  2603. getTypeString(DestTy) + "'");
  2604. ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
  2605. SrcVal, DestTy);
  2606. ID.Kind = ValID::t_Constant;
  2607. return false;
  2608. }
  2609. case lltok::kw_extractvalue: {
  2610. Lex.Lex();
  2611. Constant *Val;
  2612. SmallVector<unsigned, 4> Indices;
  2613. if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
  2614. ParseGlobalTypeAndValue(Val) ||
  2615. ParseIndexList(Indices) ||
  2616. ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
  2617. return true;
  2618. if (!Val->getType()->isAggregateType())
  2619. return Error(ID.Loc, "extractvalue operand must be aggregate type");
  2620. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  2621. return Error(ID.Loc, "invalid indices for extractvalue");
  2622. ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
  2623. ID.Kind = ValID::t_Constant;
  2624. return false;
  2625. }
  2626. case lltok::kw_insertvalue: {
  2627. Lex.Lex();
  2628. Constant *Val0, *Val1;
  2629. SmallVector<unsigned, 4> Indices;
  2630. if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
  2631. ParseGlobalTypeAndValue(Val0) ||
  2632. ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
  2633. ParseGlobalTypeAndValue(Val1) ||
  2634. ParseIndexList(Indices) ||
  2635. ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
  2636. return true;
  2637. if (!Val0->getType()->isAggregateType())
  2638. return Error(ID.Loc, "insertvalue operand must be aggregate type");
  2639. Type *IndexedType =
  2640. ExtractValueInst::getIndexedType(Val0->getType(), Indices);
  2641. if (!IndexedType)
  2642. return Error(ID.Loc, "invalid indices for insertvalue");
  2643. if (IndexedType != Val1->getType())
  2644. return Error(ID.Loc, "insertvalue operand and field disagree in type: '" +
  2645. getTypeString(Val1->getType()) +
  2646. "' instead of '" + getTypeString(IndexedType) +
  2647. "'");
  2648. ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
  2649. ID.Kind = ValID::t_Constant;
  2650. return false;
  2651. }
  2652. case lltok::kw_icmp:
  2653. case lltok::kw_fcmp: {
  2654. unsigned PredVal, Opc = Lex.getUIntVal();
  2655. Constant *Val0, *Val1;
  2656. Lex.Lex();
  2657. if (ParseCmpPredicate(PredVal, Opc) ||
  2658. ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
  2659. ParseGlobalTypeAndValue(Val0) ||
  2660. ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
  2661. ParseGlobalTypeAndValue(Val1) ||
  2662. ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
  2663. return true;
  2664. if (Val0->getType() != Val1->getType())
  2665. return Error(ID.Loc, "compare operands must have the same type");
  2666. CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
  2667. if (Opc == Instruction::FCmp) {
  2668. if (!Val0->getType()->isFPOrFPVectorTy())
  2669. return Error(ID.Loc, "fcmp requires floating point operands");
  2670. ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
  2671. } else {
  2672. assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
  2673. if (!Val0->getType()->isIntOrIntVectorTy() &&
  2674. !Val0->getType()->getScalarType()->isPointerTy())
  2675. return Error(ID.Loc, "icmp requires pointer or integer operands");
  2676. ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
  2677. }
  2678. ID.Kind = ValID::t_Constant;
  2679. return false;
  2680. }
  2681. // Binary Operators.
  2682. case lltok::kw_add:
  2683. case lltok::kw_fadd:
  2684. case lltok::kw_sub:
  2685. case lltok::kw_fsub:
  2686. case lltok::kw_mul:
  2687. case lltok::kw_fmul:
  2688. case lltok::kw_udiv:
  2689. case lltok::kw_sdiv:
  2690. case lltok::kw_fdiv:
  2691. case lltok::kw_urem:
  2692. case lltok::kw_srem:
  2693. case lltok::kw_frem:
  2694. case lltok::kw_shl:
  2695. case lltok::kw_lshr:
  2696. case lltok::kw_ashr: {
  2697. bool NUW = false;
  2698. bool NSW = false;
  2699. bool Exact = false;
  2700. unsigned Opc = Lex.getUIntVal();
  2701. Constant *Val0, *Val1;
  2702. Lex.Lex();
  2703. LocTy ModifierLoc = Lex.getLoc();
  2704. if (Opc == Instruction::Add || Opc == Instruction::Sub ||
  2705. Opc == Instruction::Mul || Opc == Instruction::Shl) {
  2706. if (EatIfPresent(lltok::kw_nuw))
  2707. NUW = true;
  2708. if (EatIfPresent(lltok::kw_nsw)) {
  2709. NSW = true;
  2710. if (EatIfPresent(lltok::kw_nuw))
  2711. NUW = true;
  2712. }
  2713. } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
  2714. Opc == Instruction::LShr || Opc == Instruction::AShr) {
  2715. if (EatIfPresent(lltok::kw_exact))
  2716. Exact = true;
  2717. }
  2718. if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
  2719. ParseGlobalTypeAndValue(Val0) ||
  2720. ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
  2721. ParseGlobalTypeAndValue(Val1) ||
  2722. ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
  2723. return true;
  2724. if (Val0->getType() != Val1->getType())
  2725. return Error(ID.Loc, "operands of constexpr must have same type");
  2726. if (!Val0->getType()->isIntOrIntVectorTy()) {
  2727. if (NUW)
  2728. return Error(ModifierLoc, "nuw only applies to integer operations");
  2729. if (NSW)
  2730. return Error(ModifierLoc, "nsw only applies to integer operations");
  2731. }
  2732. // Check that the type is valid for the operator.
  2733. switch (Opc) {
  2734. case Instruction::Add:
  2735. case Instruction::Sub:
  2736. case Instruction::Mul:
  2737. case Instruction::UDiv:
  2738. case Instruction::SDiv:
  2739. case Instruction::URem:
  2740. case Instruction::SRem:
  2741. case Instruction::Shl:
  2742. case Instruction::AShr:
  2743. case Instruction::LShr:
  2744. if (!Val0->getType()->isIntOrIntVectorTy())
  2745. return Error(ID.Loc, "constexpr requires integer operands");
  2746. break;
  2747. case Instruction::FAdd:
  2748. case Instruction::FSub:
  2749. case Instruction::FMul:
  2750. case Instruction::FDiv:
  2751. case Instruction::FRem:
  2752. if (!Val0->getType()->isFPOrFPVectorTy())
  2753. return Error(ID.Loc, "constexpr requires fp operands");
  2754. break;
  2755. default: llvm_unreachable("Unknown binary operator!");
  2756. }
  2757. unsigned Flags = 0;
  2758. if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2759. if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2760. if (Exact) Flags |= PossiblyExactOperator::IsExact;
  2761. Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
  2762. ID.ConstantVal = C;
  2763. ID.Kind = ValID::t_Constant;
  2764. return false;
  2765. }
  2766. // Logical Operations
  2767. case lltok::kw_and:
  2768. case lltok::kw_or:
  2769. case lltok::kw_xor: {
  2770. unsigned Opc = Lex.getUIntVal();
  2771. Constant *Val0, *Val1;
  2772. Lex.Lex();
  2773. if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
  2774. ParseGlobalTypeAndValue(Val0) ||
  2775. ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
  2776. ParseGlobalTypeAndValue(Val1) ||
  2777. ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
  2778. return true;
  2779. if (Val0->getType() != Val1->getType())
  2780. return Error(ID.Loc, "operands of constexpr must have same type");
  2781. if (!Val0->getType()->isIntOrIntVectorTy())
  2782. return Error(ID.Loc,
  2783. "constexpr requires integer or integer vector operands");
  2784. ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
  2785. ID.Kind = ValID::t_Constant;
  2786. return false;
  2787. }
  2788. case lltok::kw_getelementptr:
  2789. case lltok::kw_shufflevector:
  2790. case lltok::kw_insertelement:
  2791. case lltok::kw_extractelement:
  2792. case lltok::kw_select: {
  2793. unsigned Opc = Lex.getUIntVal();
  2794. SmallVector<Constant*, 16> Elts;
  2795. bool InBounds = false;
  2796. Type *Ty;
  2797. Lex.Lex();
  2798. if (Opc == Instruction::GetElementPtr)
  2799. InBounds = EatIfPresent(lltok::kw_inbounds);
  2800. if (ParseToken(lltok::lparen, "expected '(' in constantexpr"))
  2801. return true;
  2802. LocTy ExplicitTypeLoc = Lex.getLoc();
  2803. if (Opc == Instruction::GetElementPtr) {
  2804. if (ParseType(Ty) ||
  2805. ParseToken(lltok::comma, "expected comma after getelementptr's type"))
  2806. return true;
  2807. }
  2808. if (ParseGlobalValueVector(Elts) ||
  2809. ParseToken(lltok::rparen, "expected ')' in constantexpr"))
  2810. return true;
  2811. if (Opc == Instruction::GetElementPtr) {
  2812. if (Elts.size() == 0 ||
  2813. !Elts[0]->getType()->getScalarType()->isPointerTy())
  2814. return Error(ID.Loc, "base of getelementptr must be a pointer");
  2815. Type *BaseType = Elts[0]->getType();
  2816. auto *BasePointerType = cast<PointerType>(BaseType->getScalarType());
  2817. if (Ty != BasePointerType->getElementType())
  2818. return Error(
  2819. ExplicitTypeLoc,
  2820. "explicit pointee type doesn't match operand's pointee type");
  2821. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2822. for (Constant *Val : Indices) {
  2823. Type *ValTy = Val->getType();
  2824. if (!ValTy->getScalarType()->isIntegerTy())
  2825. return Error(ID.Loc, "getelementptr index must be an integer");
  2826. if (ValTy->isVectorTy() != BaseType->isVectorTy())
  2827. return Error(ID.Loc, "getelementptr index type missmatch");
  2828. if (ValTy->isVectorTy()) {
  2829. unsigned ValNumEl = ValTy->getVectorNumElements();
  2830. unsigned PtrNumEl = BaseType->getVectorNumElements();
  2831. if (ValNumEl != PtrNumEl)
  2832. return Error(
  2833. ID.Loc,
  2834. "getelementptr vector index has a wrong number of elements");
  2835. }
  2836. }
  2837. SmallPtrSet<Type*, 4> Visited;
  2838. if (!Indices.empty() && !Ty->isSized(&Visited))
  2839. return Error(ID.Loc, "base element of getelementptr must be sized");
  2840. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  2841. return Error(ID.Loc, "invalid getelementptr indices");
  2842. ID.ConstantVal =
  2843. ConstantExpr::getGetElementPtr(Ty, Elts[0], Indices, InBounds);
  2844. } else if (Opc == Instruction::Select) {
  2845. if (Elts.size() != 3)
  2846. return Error(ID.Loc, "expected three operands to select");
  2847. if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
  2848. Elts[2]))
  2849. return Error(ID.Loc, Reason);
  2850. ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
  2851. } else if (Opc == Instruction::ShuffleVector) {
  2852. if (Elts.size() != 3)
  2853. return Error(ID.Loc, "expected three operands to shufflevector");
  2854. if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  2855. return Error(ID.Loc, "invalid operands to shufflevector");
  2856. ID.ConstantVal =
  2857. ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
  2858. } else if (Opc == Instruction::ExtractElement) {
  2859. if (Elts.size() != 2)
  2860. return Error(ID.Loc, "expected two operands to extractelement");
  2861. if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
  2862. return Error(ID.Loc, "invalid extractelement operands");
  2863. ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
  2864. } else {
  2865. assert(Opc == Instruction::InsertElement && "Unknown opcode");
  2866. if (Elts.size() != 3)
  2867. return Error(ID.Loc, "expected three operands to insertelement");
  2868. if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  2869. return Error(ID.Loc, "invalid insertelement operands");
  2870. ID.ConstantVal =
  2871. ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
  2872. }
  2873. ID.Kind = ValID::t_Constant;
  2874. return false;
  2875. }
  2876. }
  2877. Lex.Lex();
  2878. return false;
  2879. }
  2880. /// ParseGlobalValue - Parse a global value with the specified type.
  2881. bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
  2882. C = nullptr;
  2883. ValID ID;
  2884. Value *V = nullptr;
  2885. bool Parsed = ParseValID(ID) ||
  2886. ConvertValIDToValue(Ty, ID, V, nullptr);
  2887. if (V && !(C = dyn_cast<Constant>(V)))
  2888. return Error(ID.Loc, "global values must be constants");
  2889. return Parsed;
  2890. }
  2891. bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
  2892. Type *Ty = nullptr;
  2893. return ParseType(Ty) ||
  2894. ParseGlobalValue(Ty, V);
  2895. }
  2896. bool LLParser::parseOptionalComdat(StringRef GlobalName, Comdat *&C) {
  2897. C = nullptr;
  2898. LocTy KwLoc = Lex.getLoc();
  2899. if (!EatIfPresent(lltok::kw_comdat))
  2900. return false;
  2901. if (EatIfPresent(lltok::lparen)) {
  2902. if (Lex.getKind() != lltok::ComdatVar)
  2903. return TokError("expected comdat variable");
  2904. C = getComdat(Lex.getStrVal(), Lex.getLoc());
  2905. Lex.Lex();
  2906. if (ParseToken(lltok::rparen, "expected ')' after comdat var"))
  2907. return true;
  2908. } else {
  2909. if (GlobalName.empty())
  2910. return TokError("comdat cannot be unnamed");
  2911. C = getComdat(GlobalName, KwLoc);
  2912. }
  2913. return false;
  2914. }
  2915. /// ParseGlobalValueVector
  2916. /// ::= /*empty*/
  2917. /// ::= TypeAndValue (',' TypeAndValue)*
  2918. bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant *> &Elts) {
  2919. // Empty list.
  2920. if (Lex.getKind() == lltok::rbrace ||
  2921. Lex.getKind() == lltok::rsquare ||
  2922. Lex.getKind() == lltok::greater ||
  2923. Lex.getKind() == lltok::rparen)
  2924. return false;
  2925. Constant *C;
  2926. if (ParseGlobalTypeAndValue(C)) return true;
  2927. Elts.push_back(C);
  2928. while (EatIfPresent(lltok::comma)) {
  2929. if (ParseGlobalTypeAndValue(C)) return true;
  2930. Elts.push_back(C);
  2931. }
  2932. return false;
  2933. }
  2934. bool LLParser::ParseMDTuple(MDNode *&MD, bool IsDistinct) {
  2935. SmallVector<Metadata *, 16> Elts;
  2936. if (ParseMDNodeVector(Elts))
  2937. return true;
  2938. MD = (IsDistinct ? MDTuple::getDistinct : MDTuple::get)(Context, Elts);
  2939. return false;
  2940. }
  2941. /// MDNode:
  2942. /// ::= !{ ... }
  2943. /// ::= !7
  2944. /// ::= !DILocation(...)
  2945. bool LLParser::ParseMDNode(MDNode *&N) {
  2946. if (Lex.getKind() == lltok::MetadataVar)
  2947. return ParseSpecializedMDNode(N);
  2948. return ParseToken(lltok::exclaim, "expected '!' here") ||
  2949. ParseMDNodeTail(N);
  2950. }
  2951. bool LLParser::ParseMDNodeTail(MDNode *&N) {
  2952. // !{ ... }
  2953. if (Lex.getKind() == lltok::lbrace)
  2954. return ParseMDTuple(N);
  2955. // !42
  2956. return ParseMDNodeID(N);
  2957. }
  2958. namespace {
  2959. /// Structure to represent an optional metadata field.
  2960. template <class FieldTy> struct MDFieldImpl {
  2961. typedef MDFieldImpl ImplTy;
  2962. FieldTy Val;
  2963. bool Seen;
  2964. void assign(FieldTy Val) {
  2965. Seen = true;
  2966. this->Val = std::move(Val);
  2967. }
  2968. explicit MDFieldImpl(FieldTy Default)
  2969. : Val(std::move(Default)), Seen(false) {}
  2970. };
  2971. struct MDUnsignedField : public MDFieldImpl<uint64_t> {
  2972. uint64_t Max;
  2973. MDUnsignedField(uint64_t Default = 0, uint64_t Max = UINT64_MAX)
  2974. : ImplTy(Default), Max(Max) {}
  2975. };
  2976. struct LineField : public MDUnsignedField {
  2977. LineField() : MDUnsignedField(0, UINT32_MAX) {}
  2978. };
  2979. struct ColumnField : public MDUnsignedField {
  2980. ColumnField() : MDUnsignedField(0, UINT16_MAX) {}
  2981. };
  2982. struct DwarfTagField : public MDUnsignedField {
  2983. DwarfTagField() : MDUnsignedField(0, dwarf::DW_TAG_hi_user) {}
  2984. DwarfTagField(dwarf::Tag DefaultTag)
  2985. : MDUnsignedField(DefaultTag, dwarf::DW_TAG_hi_user) {}
  2986. };
  2987. struct DwarfMacinfoTypeField : public MDUnsignedField {
  2988. DwarfMacinfoTypeField() : MDUnsignedField(0, dwarf::DW_MACINFO_vendor_ext) {}
  2989. DwarfMacinfoTypeField(dwarf::MacinfoRecordType DefaultType)
  2990. : MDUnsignedField(DefaultType, dwarf::DW_MACINFO_vendor_ext) {}
  2991. };
  2992. struct DwarfAttEncodingField : public MDUnsignedField {
  2993. DwarfAttEncodingField() : MDUnsignedField(0, dwarf::DW_ATE_hi_user) {}
  2994. };
  2995. struct DwarfVirtualityField : public MDUnsignedField {
  2996. DwarfVirtualityField() : MDUnsignedField(0, dwarf::DW_VIRTUALITY_max) {}
  2997. };
  2998. struct DwarfLangField : public MDUnsignedField {
  2999. DwarfLangField() : MDUnsignedField(0, dwarf::DW_LANG_hi_user) {}
  3000. };
  3001. struct DwarfCCField : public MDUnsignedField {
  3002. DwarfCCField() : MDUnsignedField(0, dwarf::DW_CC_hi_user) {}
  3003. };
  3004. struct EmissionKindField : public MDUnsignedField {
  3005. EmissionKindField() : MDUnsignedField(0, DICompileUnit::LastEmissionKind) {}
  3006. };
  3007. struct DIFlagField : public MDFieldImpl<DINode::DIFlags> {
  3008. DIFlagField() : MDFieldImpl(DINode::FlagZero) {}
  3009. };
  3010. struct MDSignedField : public MDFieldImpl<int64_t> {
  3011. int64_t Min;
  3012. int64_t Max;
  3013. MDSignedField(int64_t Default = 0)
  3014. : ImplTy(Default), Min(INT64_MIN), Max(INT64_MAX) {}
  3015. MDSignedField(int64_t Default, int64_t Min, int64_t Max)
  3016. : ImplTy(Default), Min(Min), Max(Max) {}
  3017. };
  3018. struct MDBoolField : public MDFieldImpl<bool> {
  3019. MDBoolField(bool Default = false) : ImplTy(Default) {}
  3020. };
  3021. struct MDField : public MDFieldImpl<Metadata *> {
  3022. bool AllowNull;
  3023. MDField(bool AllowNull = true) : ImplTy(nullptr), AllowNull(AllowNull) {}
  3024. };
  3025. struct MDConstant : public MDFieldImpl<ConstantAsMetadata *> {
  3026. MDConstant() : ImplTy(nullptr) {}
  3027. };
  3028. struct MDStringField : public MDFieldImpl<MDString *> {
  3029. bool AllowEmpty;
  3030. MDStringField(bool AllowEmpty = true)
  3031. : ImplTy(nullptr), AllowEmpty(AllowEmpty) {}
  3032. };
  3033. struct MDFieldList : public MDFieldImpl<SmallVector<Metadata *, 4>> {
  3034. MDFieldList() : ImplTy(SmallVector<Metadata *, 4>()) {}
  3035. };
  3036. } // end anonymous namespace
  3037. namespace llvm {
  3038. template <>
  3039. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3040. MDUnsignedField &Result) {
  3041. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  3042. return TokError("expected unsigned integer");
  3043. auto &U = Lex.getAPSIntVal();
  3044. if (U.ugt(Result.Max))
  3045. return TokError("value for '" + Name + "' too large, limit is " +
  3046. Twine(Result.Max));
  3047. Result.assign(U.getZExtValue());
  3048. assert(Result.Val <= Result.Max && "Expected value in range");
  3049. Lex.Lex();
  3050. return false;
  3051. }
  3052. template <>
  3053. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, LineField &Result) {
  3054. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3055. }
  3056. template <>
  3057. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, ColumnField &Result) {
  3058. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3059. }
  3060. template <>
  3061. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfTagField &Result) {
  3062. if (Lex.getKind() == lltok::APSInt)
  3063. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3064. if (Lex.getKind() != lltok::DwarfTag)
  3065. return TokError("expected DWARF tag");
  3066. unsigned Tag = dwarf::getTag(Lex.getStrVal());
  3067. if (Tag == dwarf::DW_TAG_invalid)
  3068. return TokError("invalid DWARF tag" + Twine(" '") + Lex.getStrVal() + "'");
  3069. assert(Tag <= Result.Max && "Expected valid DWARF tag");
  3070. Result.assign(Tag);
  3071. Lex.Lex();
  3072. return false;
  3073. }
  3074. template <>
  3075. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3076. DwarfMacinfoTypeField &Result) {
  3077. if (Lex.getKind() == lltok::APSInt)
  3078. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3079. if (Lex.getKind() != lltok::DwarfMacinfo)
  3080. return TokError("expected DWARF macinfo type");
  3081. unsigned Macinfo = dwarf::getMacinfo(Lex.getStrVal());
  3082. if (Macinfo == dwarf::DW_MACINFO_invalid)
  3083. return TokError(
  3084. "invalid DWARF macinfo type" + Twine(" '") + Lex.getStrVal() + "'");
  3085. assert(Macinfo <= Result.Max && "Expected valid DWARF macinfo type");
  3086. Result.assign(Macinfo);
  3087. Lex.Lex();
  3088. return false;
  3089. }
  3090. template <>
  3091. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3092. DwarfVirtualityField &Result) {
  3093. if (Lex.getKind() == lltok::APSInt)
  3094. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3095. if (Lex.getKind() != lltok::DwarfVirtuality)
  3096. return TokError("expected DWARF virtuality code");
  3097. unsigned Virtuality = dwarf::getVirtuality(Lex.getStrVal());
  3098. if (Virtuality == dwarf::DW_VIRTUALITY_invalid)
  3099. return TokError("invalid DWARF virtuality code" + Twine(" '") +
  3100. Lex.getStrVal() + "'");
  3101. assert(Virtuality <= Result.Max && "Expected valid DWARF virtuality code");
  3102. Result.assign(Virtuality);
  3103. Lex.Lex();
  3104. return false;
  3105. }
  3106. template <>
  3107. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfLangField &Result) {
  3108. if (Lex.getKind() == lltok::APSInt)
  3109. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3110. if (Lex.getKind() != lltok::DwarfLang)
  3111. return TokError("expected DWARF language");
  3112. unsigned Lang = dwarf::getLanguage(Lex.getStrVal());
  3113. if (!Lang)
  3114. return TokError("invalid DWARF language" + Twine(" '") + Lex.getStrVal() +
  3115. "'");
  3116. assert(Lang <= Result.Max && "Expected valid DWARF language");
  3117. Result.assign(Lang);
  3118. Lex.Lex();
  3119. return false;
  3120. }
  3121. template <>
  3122. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DwarfCCField &Result) {
  3123. if (Lex.getKind() == lltok::APSInt)
  3124. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3125. if (Lex.getKind() != lltok::DwarfCC)
  3126. return TokError("expected DWARF calling convention");
  3127. unsigned CC = dwarf::getCallingConvention(Lex.getStrVal());
  3128. if (!CC)
  3129. return TokError("invalid DWARF calling convention" + Twine(" '") + Lex.getStrVal() +
  3130. "'");
  3131. assert(CC <= Result.Max && "Expected valid DWARF calling convention");
  3132. Result.assign(CC);
  3133. Lex.Lex();
  3134. return false;
  3135. }
  3136. template <>
  3137. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, EmissionKindField &Result) {
  3138. if (Lex.getKind() == lltok::APSInt)
  3139. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3140. if (Lex.getKind() != lltok::EmissionKind)
  3141. return TokError("expected emission kind");
  3142. auto Kind = DICompileUnit::getEmissionKind(Lex.getStrVal());
  3143. if (!Kind)
  3144. return TokError("invalid emission kind" + Twine(" '") + Lex.getStrVal() +
  3145. "'");
  3146. assert(*Kind <= Result.Max && "Expected valid emission kind");
  3147. Result.assign(*Kind);
  3148. Lex.Lex();
  3149. return false;
  3150. }
  3151. template <>
  3152. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3153. DwarfAttEncodingField &Result) {
  3154. if (Lex.getKind() == lltok::APSInt)
  3155. return ParseMDField(Loc, Name, static_cast<MDUnsignedField &>(Result));
  3156. if (Lex.getKind() != lltok::DwarfAttEncoding)
  3157. return TokError("expected DWARF type attribute encoding");
  3158. unsigned Encoding = dwarf::getAttributeEncoding(Lex.getStrVal());
  3159. if (!Encoding)
  3160. return TokError("invalid DWARF type attribute encoding" + Twine(" '") +
  3161. Lex.getStrVal() + "'");
  3162. assert(Encoding <= Result.Max && "Expected valid DWARF language");
  3163. Result.assign(Encoding);
  3164. Lex.Lex();
  3165. return false;
  3166. }
  3167. /// DIFlagField
  3168. /// ::= uint32
  3169. /// ::= DIFlagVector
  3170. /// ::= DIFlagVector '|' DIFlagFwdDecl '|' uint32 '|' DIFlagPublic
  3171. template <>
  3172. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, DIFlagField &Result) {
  3173. // Parser for a single flag.
  3174. auto parseFlag = [&](DINode::DIFlags &Val) {
  3175. if (Lex.getKind() == lltok::APSInt && !Lex.getAPSIntVal().isSigned()) {
  3176. uint32_t TempVal = static_cast<uint32_t>(Val);
  3177. bool Res = ParseUInt32(TempVal);
  3178. Val = static_cast<DINode::DIFlags>(TempVal);
  3179. return Res;
  3180. }
  3181. if (Lex.getKind() != lltok::DIFlag)
  3182. return TokError("expected debug info flag");
  3183. Val = DINode::getFlag(Lex.getStrVal());
  3184. if (!Val)
  3185. return TokError(Twine("invalid debug info flag flag '") +
  3186. Lex.getStrVal() + "'");
  3187. Lex.Lex();
  3188. return false;
  3189. };
  3190. // Parse the flags and combine them together.
  3191. DINode::DIFlags Combined = DINode::FlagZero;
  3192. do {
  3193. DINode::DIFlags Val;
  3194. if (parseFlag(Val))
  3195. return true;
  3196. Combined |= Val;
  3197. } while (EatIfPresent(lltok::bar));
  3198. Result.assign(Combined);
  3199. return false;
  3200. }
  3201. template <>
  3202. bool LLParser::ParseMDField(LocTy Loc, StringRef Name,
  3203. MDSignedField &Result) {
  3204. if (Lex.getKind() != lltok::APSInt)
  3205. return TokError("expected signed integer");
  3206. auto &S = Lex.getAPSIntVal();
  3207. if (S < Result.Min)
  3208. return TokError("value for '" + Name + "' too small, limit is " +
  3209. Twine(Result.Min));
  3210. if (S > Result.Max)
  3211. return TokError("value for '" + Name + "' too large, limit is " +
  3212. Twine(Result.Max));
  3213. Result.assign(S.getExtValue());
  3214. assert(Result.Val >= Result.Min && "Expected value in range");
  3215. assert(Result.Val <= Result.Max && "Expected value in range");
  3216. Lex.Lex();
  3217. return false;
  3218. }
  3219. template <>
  3220. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDBoolField &Result) {
  3221. switch (Lex.getKind()) {
  3222. default:
  3223. return TokError("expected 'true' or 'false'");
  3224. case lltok::kw_true:
  3225. Result.assign(true);
  3226. break;
  3227. case lltok::kw_false:
  3228. Result.assign(false);
  3229. break;
  3230. }
  3231. Lex.Lex();
  3232. return false;
  3233. }
  3234. template <>
  3235. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDField &Result) {
  3236. if (Lex.getKind() == lltok::kw_null) {
  3237. if (!Result.AllowNull)
  3238. return TokError("'" + Name + "' cannot be null");
  3239. Lex.Lex();
  3240. Result.assign(nullptr);
  3241. return false;
  3242. }
  3243. Metadata *MD;
  3244. if (ParseMetadata(MD, nullptr))
  3245. return true;
  3246. Result.assign(MD);
  3247. return false;
  3248. }
  3249. template <>
  3250. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDConstant &Result) {
  3251. Metadata *MD;
  3252. if (ParseValueAsMetadata(MD, "expected constant", nullptr))
  3253. return true;
  3254. Result.assign(cast<ConstantAsMetadata>(MD));
  3255. return false;
  3256. }
  3257. template <>
  3258. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDStringField &Result) {
  3259. LocTy ValueLoc = Lex.getLoc();
  3260. std::string S;
  3261. if (ParseStringConstant(S))
  3262. return true;
  3263. if (!Result.AllowEmpty && S.empty())
  3264. return Error(ValueLoc, "'" + Name + "' cannot be empty");
  3265. Result.assign(S.empty() ? nullptr : MDString::get(Context, S));
  3266. return false;
  3267. }
  3268. template <>
  3269. bool LLParser::ParseMDField(LocTy Loc, StringRef Name, MDFieldList &Result) {
  3270. SmallVector<Metadata *, 4> MDs;
  3271. if (ParseMDNodeVector(MDs))
  3272. return true;
  3273. Result.assign(std::move(MDs));
  3274. return false;
  3275. }
  3276. } // end namespace llvm
  3277. template <class ParserTy>
  3278. bool LLParser::ParseMDFieldsImplBody(ParserTy parseField) {
  3279. do {
  3280. if (Lex.getKind() != lltok::LabelStr)
  3281. return TokError("expected field label here");
  3282. if (parseField())
  3283. return true;
  3284. } while (EatIfPresent(lltok::comma));
  3285. return false;
  3286. }
  3287. template <class ParserTy>
  3288. bool LLParser::ParseMDFieldsImpl(ParserTy parseField, LocTy &ClosingLoc) {
  3289. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  3290. Lex.Lex();
  3291. if (ParseToken(lltok::lparen, "expected '(' here"))
  3292. return true;
  3293. if (Lex.getKind() != lltok::rparen)
  3294. if (ParseMDFieldsImplBody(parseField))
  3295. return true;
  3296. ClosingLoc = Lex.getLoc();
  3297. return ParseToken(lltok::rparen, "expected ')' here");
  3298. }
  3299. template <class FieldTy>
  3300. bool LLParser::ParseMDField(StringRef Name, FieldTy &Result) {
  3301. if (Result.Seen)
  3302. return TokError("field '" + Name + "' cannot be specified more than once");
  3303. LocTy Loc = Lex.getLoc();
  3304. Lex.Lex();
  3305. return ParseMDField(Loc, Name, Result);
  3306. }
  3307. bool LLParser::ParseSpecializedMDNode(MDNode *&N, bool IsDistinct) {
  3308. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  3309. #define HANDLE_SPECIALIZED_MDNODE_LEAF(CLASS) \
  3310. if (Lex.getStrVal() == #CLASS) \
  3311. return Parse##CLASS(N, IsDistinct);
  3312. #include "llvm/IR/Metadata.def"
  3313. return TokError("expected metadata type");
  3314. }
  3315. #define DECLARE_FIELD(NAME, TYPE, INIT) TYPE NAME INIT
  3316. #define NOP_FIELD(NAME, TYPE, INIT)
  3317. #define REQUIRE_FIELD(NAME, TYPE, INIT) \
  3318. if (!NAME.Seen) \
  3319. return Error(ClosingLoc, "missing required field '" #NAME "'");
  3320. #define PARSE_MD_FIELD(NAME, TYPE, DEFAULT) \
  3321. if (Lex.getStrVal() == #NAME) \
  3322. return ParseMDField(#NAME, NAME);
  3323. #define PARSE_MD_FIELDS() \
  3324. VISIT_MD_FIELDS(DECLARE_FIELD, DECLARE_FIELD) \
  3325. do { \
  3326. LocTy ClosingLoc; \
  3327. if (ParseMDFieldsImpl([&]() -> bool { \
  3328. VISIT_MD_FIELDS(PARSE_MD_FIELD, PARSE_MD_FIELD) \
  3329. return TokError(Twine("invalid field '") + Lex.getStrVal() + "'"); \
  3330. }, ClosingLoc)) \
  3331. return true; \
  3332. VISIT_MD_FIELDS(NOP_FIELD, REQUIRE_FIELD) \
  3333. } while (false)
  3334. #define GET_OR_DISTINCT(CLASS, ARGS) \
  3335. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  3336. /// ParseDILocationFields:
  3337. /// ::= !DILocation(line: 43, column: 8, scope: !5, inlinedAt: !6)
  3338. bool LLParser::ParseDILocation(MDNode *&Result, bool IsDistinct) {
  3339. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3340. OPTIONAL(line, LineField, ); \
  3341. OPTIONAL(column, ColumnField, ); \
  3342. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3343. OPTIONAL(inlinedAt, MDField, );
  3344. PARSE_MD_FIELDS();
  3345. #undef VISIT_MD_FIELDS
  3346. Result = GET_OR_DISTINCT(
  3347. DILocation, (Context, line.Val, column.Val, scope.Val, inlinedAt.Val));
  3348. return false;
  3349. }
  3350. /// ParseGenericDINode:
  3351. /// ::= !GenericDINode(tag: 15, header: "...", operands: {...})
  3352. bool LLParser::ParseGenericDINode(MDNode *&Result, bool IsDistinct) {
  3353. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3354. REQUIRED(tag, DwarfTagField, ); \
  3355. OPTIONAL(header, MDStringField, ); \
  3356. OPTIONAL(operands, MDFieldList, );
  3357. PARSE_MD_FIELDS();
  3358. #undef VISIT_MD_FIELDS
  3359. Result = GET_OR_DISTINCT(GenericDINode,
  3360. (Context, tag.Val, header.Val, operands.Val));
  3361. return false;
  3362. }
  3363. /// ParseDISubrange:
  3364. /// ::= !DISubrange(count: 30, lowerBound: 2)
  3365. bool LLParser::ParseDISubrange(MDNode *&Result, bool IsDistinct) {
  3366. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3367. REQUIRED(count, MDSignedField, (-1, -1, INT64_MAX)); \
  3368. OPTIONAL(lowerBound, MDSignedField, );
  3369. PARSE_MD_FIELDS();
  3370. #undef VISIT_MD_FIELDS
  3371. Result = GET_OR_DISTINCT(DISubrange, (Context, count.Val, lowerBound.Val));
  3372. return false;
  3373. }
  3374. /// ParseDIEnumerator:
  3375. /// ::= !DIEnumerator(value: 30, name: "SomeKind")
  3376. bool LLParser::ParseDIEnumerator(MDNode *&Result, bool IsDistinct) {
  3377. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3378. REQUIRED(name, MDStringField, ); \
  3379. REQUIRED(value, MDSignedField, );
  3380. PARSE_MD_FIELDS();
  3381. #undef VISIT_MD_FIELDS
  3382. Result = GET_OR_DISTINCT(DIEnumerator, (Context, value.Val, name.Val));
  3383. return false;
  3384. }
  3385. /// ParseDIBasicType:
  3386. /// ::= !DIBasicType(tag: DW_TAG_base_type, name: "int", size: 32, align: 32)
  3387. bool LLParser::ParseDIBasicType(MDNode *&Result, bool IsDistinct) {
  3388. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3389. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_base_type)); \
  3390. OPTIONAL(name, MDStringField, ); \
  3391. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3392. OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
  3393. OPTIONAL(encoding, DwarfAttEncodingField, );
  3394. PARSE_MD_FIELDS();
  3395. #undef VISIT_MD_FIELDS
  3396. Result = GET_OR_DISTINCT(DIBasicType, (Context, tag.Val, name.Val, size.Val,
  3397. align.Val, encoding.Val));
  3398. return false;
  3399. }
  3400. /// ParseDIDerivedType:
  3401. /// ::= !DIDerivedType(tag: DW_TAG_pointer_type, name: "int", file: !0,
  3402. /// line: 7, scope: !1, baseType: !2, size: 32,
  3403. /// align: 32, offset: 0, flags: 0, extraData: !3)
  3404. bool LLParser::ParseDIDerivedType(MDNode *&Result, bool IsDistinct) {
  3405. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3406. REQUIRED(tag, DwarfTagField, ); \
  3407. OPTIONAL(name, MDStringField, ); \
  3408. OPTIONAL(file, MDField, ); \
  3409. OPTIONAL(line, LineField, ); \
  3410. OPTIONAL(scope, MDField, ); \
  3411. REQUIRED(baseType, MDField, ); \
  3412. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3413. OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
  3414. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  3415. OPTIONAL(flags, DIFlagField, ); \
  3416. OPTIONAL(extraData, MDField, );
  3417. PARSE_MD_FIELDS();
  3418. #undef VISIT_MD_FIELDS
  3419. Result = GET_OR_DISTINCT(DIDerivedType,
  3420. (Context, tag.Val, name.Val, file.Val, line.Val,
  3421. scope.Val, baseType.Val, size.Val, align.Val,
  3422. offset.Val, flags.Val, extraData.Val));
  3423. return false;
  3424. }
  3425. bool LLParser::ParseDICompositeType(MDNode *&Result, bool IsDistinct) {
  3426. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3427. REQUIRED(tag, DwarfTagField, ); \
  3428. OPTIONAL(name, MDStringField, ); \
  3429. OPTIONAL(file, MDField, ); \
  3430. OPTIONAL(line, LineField, ); \
  3431. OPTIONAL(scope, MDField, ); \
  3432. OPTIONAL(baseType, MDField, ); \
  3433. OPTIONAL(size, MDUnsignedField, (0, UINT64_MAX)); \
  3434. OPTIONAL(align, MDUnsignedField, (0, UINT64_MAX)); \
  3435. OPTIONAL(offset, MDUnsignedField, (0, UINT64_MAX)); \
  3436. OPTIONAL(flags, DIFlagField, ); \
  3437. OPTIONAL(elements, MDField, ); \
  3438. OPTIONAL(runtimeLang, DwarfLangField, ); \
  3439. OPTIONAL(vtableHolder, MDField, ); \
  3440. OPTIONAL(templateParams, MDField, ); \
  3441. OPTIONAL(identifier, MDStringField, );
  3442. PARSE_MD_FIELDS();
  3443. #undef VISIT_MD_FIELDS
  3444. // If this has an identifier try to build an ODR type.
  3445. if (identifier.Val)
  3446. if (auto *CT = DICompositeType::buildODRType(
  3447. Context, *identifier.Val, tag.Val, name.Val, file.Val, line.Val,
  3448. scope.Val, baseType.Val, size.Val, align.Val, offset.Val, flags.Val,
  3449. elements.Val, runtimeLang.Val, vtableHolder.Val,
  3450. templateParams.Val)) {
  3451. Result = CT;
  3452. return false;
  3453. }
  3454. // Create a new node, and save it in the context if it belongs in the type
  3455. // map.
  3456. Result = GET_OR_DISTINCT(
  3457. DICompositeType,
  3458. (Context, tag.Val, name.Val, file.Val, line.Val, scope.Val, baseType.Val,
  3459. size.Val, align.Val, offset.Val, flags.Val, elements.Val,
  3460. runtimeLang.Val, vtableHolder.Val, templateParams.Val, identifier.Val));
  3461. return false;
  3462. }
  3463. bool LLParser::ParseDISubroutineType(MDNode *&Result, bool IsDistinct) {
  3464. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3465. OPTIONAL(flags, DIFlagField, ); \
  3466. OPTIONAL(cc, DwarfCCField, ); \
  3467. REQUIRED(types, MDField, );
  3468. PARSE_MD_FIELDS();
  3469. #undef VISIT_MD_FIELDS
  3470. Result = GET_OR_DISTINCT(DISubroutineType,
  3471. (Context, flags.Val, cc.Val, types.Val));
  3472. return false;
  3473. }
  3474. /// ParseDIFileType:
  3475. /// ::= !DIFileType(filename: "path/to/file", directory: "/path/to/dir")
  3476. bool LLParser::ParseDIFile(MDNode *&Result, bool IsDistinct) {
  3477. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3478. REQUIRED(filename, MDStringField, ); \
  3479. REQUIRED(directory, MDStringField, );
  3480. PARSE_MD_FIELDS();
  3481. #undef VISIT_MD_FIELDS
  3482. Result = GET_OR_DISTINCT(DIFile, (Context, filename.Val, directory.Val));
  3483. return false;
  3484. }
  3485. /// ParseDICompileUnit:
  3486. /// ::= !DICompileUnit(language: DW_LANG_C99, file: !0, producer: "clang",
  3487. /// isOptimized: true, flags: "-O2", runtimeVersion: 1,
  3488. /// splitDebugFilename: "abc.debug",
  3489. /// emissionKind: FullDebug, enums: !1, retainedTypes: !2,
  3490. /// globals: !4, imports: !5, macros: !6, dwoId: 0x0abcd)
  3491. bool LLParser::ParseDICompileUnit(MDNode *&Result, bool IsDistinct) {
  3492. if (!IsDistinct)
  3493. return Lex.Error("missing 'distinct', required for !DICompileUnit");
  3494. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3495. REQUIRED(language, DwarfLangField, ); \
  3496. REQUIRED(file, MDField, (/* AllowNull */ false)); \
  3497. OPTIONAL(producer, MDStringField, ); \
  3498. OPTIONAL(isOptimized, MDBoolField, ); \
  3499. OPTIONAL(flags, MDStringField, ); \
  3500. OPTIONAL(runtimeVersion, MDUnsignedField, (0, UINT32_MAX)); \
  3501. OPTIONAL(splitDebugFilename, MDStringField, ); \
  3502. OPTIONAL(emissionKind, EmissionKindField, ); \
  3503. OPTIONAL(enums, MDField, ); \
  3504. OPTIONAL(retainedTypes, MDField, ); \
  3505. OPTIONAL(globals, MDField, ); \
  3506. OPTIONAL(imports, MDField, ); \
  3507. OPTIONAL(macros, MDField, ); \
  3508. OPTIONAL(dwoId, MDUnsignedField, ); \
  3509. OPTIONAL(splitDebugInlining, MDBoolField, = true);
  3510. PARSE_MD_FIELDS();
  3511. #undef VISIT_MD_FIELDS
  3512. Result = DICompileUnit::getDistinct(
  3513. Context, language.Val, file.Val, producer.Val, isOptimized.Val, flags.Val,
  3514. runtimeVersion.Val, splitDebugFilename.Val, emissionKind.Val, enums.Val,
  3515. retainedTypes.Val, globals.Val, imports.Val, macros.Val, dwoId.Val,
  3516. splitDebugInlining.Val);
  3517. return false;
  3518. }
  3519. /// ParseDISubprogram:
  3520. /// ::= !DISubprogram(scope: !0, name: "foo", linkageName: "_Zfoo",
  3521. /// file: !1, line: 7, type: !2, isLocal: false,
  3522. /// isDefinition: true, scopeLine: 8, containingType: !3,
  3523. /// virtuality: DW_VIRTUALTIY_pure_virtual,
  3524. /// virtualIndex: 10, thisAdjustment: 4, flags: 11,
  3525. /// isOptimized: false, templateParams: !4, declaration: !5,
  3526. /// variables: !6)
  3527. bool LLParser::ParseDISubprogram(MDNode *&Result, bool IsDistinct) {
  3528. auto Loc = Lex.getLoc();
  3529. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3530. OPTIONAL(scope, MDField, ); \
  3531. OPTIONAL(name, MDStringField, ); \
  3532. OPTIONAL(linkageName, MDStringField, ); \
  3533. OPTIONAL(file, MDField, ); \
  3534. OPTIONAL(line, LineField, ); \
  3535. OPTIONAL(type, MDField, ); \
  3536. OPTIONAL(isLocal, MDBoolField, ); \
  3537. OPTIONAL(isDefinition, MDBoolField, (true)); \
  3538. OPTIONAL(scopeLine, LineField, ); \
  3539. OPTIONAL(containingType, MDField, ); \
  3540. OPTIONAL(virtuality, DwarfVirtualityField, ); \
  3541. OPTIONAL(virtualIndex, MDUnsignedField, (0, UINT32_MAX)); \
  3542. OPTIONAL(thisAdjustment, MDSignedField, (0, INT32_MIN, INT32_MAX)); \
  3543. OPTIONAL(flags, DIFlagField, ); \
  3544. OPTIONAL(isOptimized, MDBoolField, ); \
  3545. OPTIONAL(unit, MDField, ); \
  3546. OPTIONAL(templateParams, MDField, ); \
  3547. OPTIONAL(declaration, MDField, ); \
  3548. OPTIONAL(variables, MDField, );
  3549. PARSE_MD_FIELDS();
  3550. #undef VISIT_MD_FIELDS
  3551. if (isDefinition.Val && !IsDistinct)
  3552. return Lex.Error(
  3553. Loc,
  3554. "missing 'distinct', required for !DISubprogram when 'isDefinition'");
  3555. Result = GET_OR_DISTINCT(
  3556. DISubprogram, (Context, scope.Val, name.Val, linkageName.Val, file.Val,
  3557. line.Val, type.Val, isLocal.Val, isDefinition.Val,
  3558. scopeLine.Val, containingType.Val, virtuality.Val,
  3559. virtualIndex.Val, thisAdjustment.Val, flags.Val,
  3560. isOptimized.Val, unit.Val, templateParams.Val,
  3561. declaration.Val, variables.Val));
  3562. return false;
  3563. }
  3564. /// ParseDILexicalBlock:
  3565. /// ::= !DILexicalBlock(scope: !0, file: !2, line: 7, column: 9)
  3566. bool LLParser::ParseDILexicalBlock(MDNode *&Result, bool IsDistinct) {
  3567. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3568. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3569. OPTIONAL(file, MDField, ); \
  3570. OPTIONAL(line, LineField, ); \
  3571. OPTIONAL(column, ColumnField, );
  3572. PARSE_MD_FIELDS();
  3573. #undef VISIT_MD_FIELDS
  3574. Result = GET_OR_DISTINCT(
  3575. DILexicalBlock, (Context, scope.Val, file.Val, line.Val, column.Val));
  3576. return false;
  3577. }
  3578. /// ParseDILexicalBlockFile:
  3579. /// ::= !DILexicalBlockFile(scope: !0, file: !2, discriminator: 9)
  3580. bool LLParser::ParseDILexicalBlockFile(MDNode *&Result, bool IsDistinct) {
  3581. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3582. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3583. OPTIONAL(file, MDField, ); \
  3584. REQUIRED(discriminator, MDUnsignedField, (0, UINT32_MAX));
  3585. PARSE_MD_FIELDS();
  3586. #undef VISIT_MD_FIELDS
  3587. Result = GET_OR_DISTINCT(DILexicalBlockFile,
  3588. (Context, scope.Val, file.Val, discriminator.Val));
  3589. return false;
  3590. }
  3591. /// ParseDINamespace:
  3592. /// ::= !DINamespace(scope: !0, file: !2, name: "SomeNamespace", line: 9)
  3593. bool LLParser::ParseDINamespace(MDNode *&Result, bool IsDistinct) {
  3594. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3595. REQUIRED(scope, MDField, ); \
  3596. OPTIONAL(file, MDField, ); \
  3597. OPTIONAL(name, MDStringField, ); \
  3598. OPTIONAL(line, LineField, );
  3599. PARSE_MD_FIELDS();
  3600. #undef VISIT_MD_FIELDS
  3601. Result = GET_OR_DISTINCT(DINamespace,
  3602. (Context, scope.Val, file.Val, name.Val, line.Val));
  3603. return false;
  3604. }
  3605. /// ParseDIMacro:
  3606. /// ::= !DIMacro(macinfo: type, line: 9, name: "SomeMacro", value: "SomeValue")
  3607. bool LLParser::ParseDIMacro(MDNode *&Result, bool IsDistinct) {
  3608. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3609. REQUIRED(type, DwarfMacinfoTypeField, ); \
  3610. REQUIRED(line, LineField, ); \
  3611. REQUIRED(name, MDStringField, ); \
  3612. OPTIONAL(value, MDStringField, );
  3613. PARSE_MD_FIELDS();
  3614. #undef VISIT_MD_FIELDS
  3615. Result = GET_OR_DISTINCT(DIMacro,
  3616. (Context, type.Val, line.Val, name.Val, value.Val));
  3617. return false;
  3618. }
  3619. /// ParseDIMacroFile:
  3620. /// ::= !DIMacroFile(line: 9, file: !2, nodes: !3)
  3621. bool LLParser::ParseDIMacroFile(MDNode *&Result, bool IsDistinct) {
  3622. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3623. OPTIONAL(type, DwarfMacinfoTypeField, (dwarf::DW_MACINFO_start_file)); \
  3624. REQUIRED(line, LineField, ); \
  3625. REQUIRED(file, MDField, ); \
  3626. OPTIONAL(nodes, MDField, );
  3627. PARSE_MD_FIELDS();
  3628. #undef VISIT_MD_FIELDS
  3629. Result = GET_OR_DISTINCT(DIMacroFile,
  3630. (Context, type.Val, line.Val, file.Val, nodes.Val));
  3631. return false;
  3632. }
  3633. /// ParseDIModule:
  3634. /// ::= !DIModule(scope: !0, name: "SomeModule", configMacros: "-DNDEBUG",
  3635. /// includePath: "/usr/include", isysroot: "/")
  3636. bool LLParser::ParseDIModule(MDNode *&Result, bool IsDistinct) {
  3637. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3638. REQUIRED(scope, MDField, ); \
  3639. REQUIRED(name, MDStringField, ); \
  3640. OPTIONAL(configMacros, MDStringField, ); \
  3641. OPTIONAL(includePath, MDStringField, ); \
  3642. OPTIONAL(isysroot, MDStringField, );
  3643. PARSE_MD_FIELDS();
  3644. #undef VISIT_MD_FIELDS
  3645. Result = GET_OR_DISTINCT(DIModule, (Context, scope.Val, name.Val,
  3646. configMacros.Val, includePath.Val, isysroot.Val));
  3647. return false;
  3648. }
  3649. /// ParseDITemplateTypeParameter:
  3650. /// ::= !DITemplateTypeParameter(name: "Ty", type: !1)
  3651. bool LLParser::ParseDITemplateTypeParameter(MDNode *&Result, bool IsDistinct) {
  3652. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3653. OPTIONAL(name, MDStringField, ); \
  3654. REQUIRED(type, MDField, );
  3655. PARSE_MD_FIELDS();
  3656. #undef VISIT_MD_FIELDS
  3657. Result =
  3658. GET_OR_DISTINCT(DITemplateTypeParameter, (Context, name.Val, type.Val));
  3659. return false;
  3660. }
  3661. /// ParseDITemplateValueParameter:
  3662. /// ::= !DITemplateValueParameter(tag: DW_TAG_template_value_parameter,
  3663. /// name: "V", type: !1, value: i32 7)
  3664. bool LLParser::ParseDITemplateValueParameter(MDNode *&Result, bool IsDistinct) {
  3665. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3666. OPTIONAL(tag, DwarfTagField, (dwarf::DW_TAG_template_value_parameter)); \
  3667. OPTIONAL(name, MDStringField, ); \
  3668. OPTIONAL(type, MDField, ); \
  3669. REQUIRED(value, MDField, );
  3670. PARSE_MD_FIELDS();
  3671. #undef VISIT_MD_FIELDS
  3672. Result = GET_OR_DISTINCT(DITemplateValueParameter,
  3673. (Context, tag.Val, name.Val, type.Val, value.Val));
  3674. return false;
  3675. }
  3676. /// ParseDIGlobalVariable:
  3677. /// ::= !DIGlobalVariable(scope: !0, name: "foo", linkageName: "foo",
  3678. /// file: !1, line: 7, type: !2, isLocal: false,
  3679. /// isDefinition: true, variable: i32* @foo,
  3680. /// declaration: !3)
  3681. bool LLParser::ParseDIGlobalVariable(MDNode *&Result, bool IsDistinct) {
  3682. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3683. REQUIRED(name, MDStringField, (/* AllowEmpty */ false)); \
  3684. OPTIONAL(scope, MDField, ); \
  3685. OPTIONAL(linkageName, MDStringField, ); \
  3686. OPTIONAL(file, MDField, ); \
  3687. OPTIONAL(line, LineField, ); \
  3688. OPTIONAL(type, MDField, ); \
  3689. OPTIONAL(isLocal, MDBoolField, ); \
  3690. OPTIONAL(isDefinition, MDBoolField, (true)); \
  3691. OPTIONAL(expr, MDField, ); \
  3692. OPTIONAL(declaration, MDField, );
  3693. PARSE_MD_FIELDS();
  3694. #undef VISIT_MD_FIELDS
  3695. Result = GET_OR_DISTINCT(DIGlobalVariable,
  3696. (Context, scope.Val, name.Val, linkageName.Val,
  3697. file.Val, line.Val, type.Val, isLocal.Val,
  3698. isDefinition.Val, expr.Val, declaration.Val));
  3699. return false;
  3700. }
  3701. /// ParseDILocalVariable:
  3702. /// ::= !DILocalVariable(arg: 7, scope: !0, name: "foo",
  3703. /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
  3704. /// ::= !DILocalVariable(scope: !0, name: "foo",
  3705. /// file: !1, line: 7, type: !2, arg: 2, flags: 7)
  3706. bool LLParser::ParseDILocalVariable(MDNode *&Result, bool IsDistinct) {
  3707. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3708. REQUIRED(scope, MDField, (/* AllowNull */ false)); \
  3709. OPTIONAL(name, MDStringField, ); \
  3710. OPTIONAL(arg, MDUnsignedField, (0, UINT16_MAX)); \
  3711. OPTIONAL(file, MDField, ); \
  3712. OPTIONAL(line, LineField, ); \
  3713. OPTIONAL(type, MDField, ); \
  3714. OPTIONAL(flags, DIFlagField, );
  3715. PARSE_MD_FIELDS();
  3716. #undef VISIT_MD_FIELDS
  3717. Result = GET_OR_DISTINCT(DILocalVariable,
  3718. (Context, scope.Val, name.Val, file.Val, line.Val,
  3719. type.Val, arg.Val, flags.Val));
  3720. return false;
  3721. }
  3722. /// ParseDIExpression:
  3723. /// ::= !DIExpression(0, 7, -1)
  3724. bool LLParser::ParseDIExpression(MDNode *&Result, bool IsDistinct) {
  3725. assert(Lex.getKind() == lltok::MetadataVar && "Expected metadata type name");
  3726. Lex.Lex();
  3727. if (ParseToken(lltok::lparen, "expected '(' here"))
  3728. return true;
  3729. SmallVector<uint64_t, 8> Elements;
  3730. if (Lex.getKind() != lltok::rparen)
  3731. do {
  3732. if (Lex.getKind() == lltok::DwarfOp) {
  3733. if (unsigned Op = dwarf::getOperationEncoding(Lex.getStrVal())) {
  3734. Lex.Lex();
  3735. Elements.push_back(Op);
  3736. continue;
  3737. }
  3738. return TokError(Twine("invalid DWARF op '") + Lex.getStrVal() + "'");
  3739. }
  3740. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  3741. return TokError("expected unsigned integer");
  3742. auto &U = Lex.getAPSIntVal();
  3743. if (U.ugt(UINT64_MAX))
  3744. return TokError("element too large, limit is " + Twine(UINT64_MAX));
  3745. Elements.push_back(U.getZExtValue());
  3746. Lex.Lex();
  3747. } while (EatIfPresent(lltok::comma));
  3748. if (ParseToken(lltok::rparen, "expected ')' here"))
  3749. return true;
  3750. Result = GET_OR_DISTINCT(DIExpression, (Context, Elements));
  3751. return false;
  3752. }
  3753. /// ParseDIObjCProperty:
  3754. /// ::= !DIObjCProperty(name: "foo", file: !1, line: 7, setter: "setFoo",
  3755. /// getter: "getFoo", attributes: 7, type: !2)
  3756. bool LLParser::ParseDIObjCProperty(MDNode *&Result, bool IsDistinct) {
  3757. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3758. OPTIONAL(name, MDStringField, ); \
  3759. OPTIONAL(file, MDField, ); \
  3760. OPTIONAL(line, LineField, ); \
  3761. OPTIONAL(setter, MDStringField, ); \
  3762. OPTIONAL(getter, MDStringField, ); \
  3763. OPTIONAL(attributes, MDUnsignedField, (0, UINT32_MAX)); \
  3764. OPTIONAL(type, MDField, );
  3765. PARSE_MD_FIELDS();
  3766. #undef VISIT_MD_FIELDS
  3767. Result = GET_OR_DISTINCT(DIObjCProperty,
  3768. (Context, name.Val, file.Val, line.Val, setter.Val,
  3769. getter.Val, attributes.Val, type.Val));
  3770. return false;
  3771. }
  3772. /// ParseDIImportedEntity:
  3773. /// ::= !DIImportedEntity(tag: DW_TAG_imported_module, scope: !0, entity: !1,
  3774. /// line: 7, name: "foo")
  3775. bool LLParser::ParseDIImportedEntity(MDNode *&Result, bool IsDistinct) {
  3776. #define VISIT_MD_FIELDS(OPTIONAL, REQUIRED) \
  3777. REQUIRED(tag, DwarfTagField, ); \
  3778. REQUIRED(scope, MDField, ); \
  3779. OPTIONAL(entity, MDField, ); \
  3780. OPTIONAL(line, LineField, ); \
  3781. OPTIONAL(name, MDStringField, );
  3782. PARSE_MD_FIELDS();
  3783. #undef VISIT_MD_FIELDS
  3784. Result = GET_OR_DISTINCT(DIImportedEntity, (Context, tag.Val, scope.Val,
  3785. entity.Val, line.Val, name.Val));
  3786. return false;
  3787. }
  3788. #undef PARSE_MD_FIELD
  3789. #undef NOP_FIELD
  3790. #undef REQUIRE_FIELD
  3791. #undef DECLARE_FIELD
  3792. /// ParseMetadataAsValue
  3793. /// ::= metadata i32 %local
  3794. /// ::= metadata i32 @global
  3795. /// ::= metadata i32 7
  3796. /// ::= metadata !0
  3797. /// ::= metadata !{...}
  3798. /// ::= metadata !"string"
  3799. bool LLParser::ParseMetadataAsValue(Value *&V, PerFunctionState &PFS) {
  3800. // Note: the type 'metadata' has already been parsed.
  3801. Metadata *MD;
  3802. if (ParseMetadata(MD, &PFS))
  3803. return true;
  3804. V = MetadataAsValue::get(Context, MD);
  3805. return false;
  3806. }
  3807. /// ParseValueAsMetadata
  3808. /// ::= i32 %local
  3809. /// ::= i32 @global
  3810. /// ::= i32 7
  3811. bool LLParser::ParseValueAsMetadata(Metadata *&MD, const Twine &TypeMsg,
  3812. PerFunctionState *PFS) {
  3813. Type *Ty;
  3814. LocTy Loc;
  3815. if (ParseType(Ty, TypeMsg, Loc))
  3816. return true;
  3817. if (Ty->isMetadataTy())
  3818. return Error(Loc, "invalid metadata-value-metadata roundtrip");
  3819. Value *V;
  3820. if (ParseValue(Ty, V, PFS))
  3821. return true;
  3822. MD = ValueAsMetadata::get(V);
  3823. return false;
  3824. }
  3825. /// ParseMetadata
  3826. /// ::= i32 %local
  3827. /// ::= i32 @global
  3828. /// ::= i32 7
  3829. /// ::= !42
  3830. /// ::= !{...}
  3831. /// ::= !"string"
  3832. /// ::= !DILocation(...)
  3833. bool LLParser::ParseMetadata(Metadata *&MD, PerFunctionState *PFS) {
  3834. if (Lex.getKind() == lltok::MetadataVar) {
  3835. MDNode *N;
  3836. if (ParseSpecializedMDNode(N))
  3837. return true;
  3838. MD = N;
  3839. return false;
  3840. }
  3841. // ValueAsMetadata:
  3842. // <type> <value>
  3843. if (Lex.getKind() != lltok::exclaim)
  3844. return ParseValueAsMetadata(MD, "expected metadata operand", PFS);
  3845. // '!'.
  3846. assert(Lex.getKind() == lltok::exclaim && "Expected '!' here");
  3847. Lex.Lex();
  3848. // MDString:
  3849. // ::= '!' STRINGCONSTANT
  3850. if (Lex.getKind() == lltok::StringConstant) {
  3851. MDString *S;
  3852. if (ParseMDString(S))
  3853. return true;
  3854. MD = S;
  3855. return false;
  3856. }
  3857. // MDNode:
  3858. // !{ ... }
  3859. // !7
  3860. MDNode *N;
  3861. if (ParseMDNodeTail(N))
  3862. return true;
  3863. MD = N;
  3864. return false;
  3865. }
  3866. //===----------------------------------------------------------------------===//
  3867. // Function Parsing.
  3868. //===----------------------------------------------------------------------===//
  3869. bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
  3870. PerFunctionState *PFS) {
  3871. if (Ty->isFunctionTy())
  3872. return Error(ID.Loc, "functions are not values, refer to them as pointers");
  3873. switch (ID.Kind) {
  3874. case ValID::t_LocalID:
  3875. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  3876. V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
  3877. return V == nullptr;
  3878. case ValID::t_LocalName:
  3879. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  3880. V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
  3881. return V == nullptr;
  3882. case ValID::t_InlineAsm: {
  3883. if (!ID.FTy || !InlineAsm::Verify(ID.FTy, ID.StrVal2))
  3884. return Error(ID.Loc, "invalid type for inline asm constraint string");
  3885. V = InlineAsm::get(ID.FTy, ID.StrVal, ID.StrVal2, ID.UIntVal & 1,
  3886. (ID.UIntVal >> 1) & 1,
  3887. (InlineAsm::AsmDialect(ID.UIntVal >> 2)));
  3888. return false;
  3889. }
  3890. case ValID::t_GlobalName:
  3891. V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
  3892. return V == nullptr;
  3893. case ValID::t_GlobalID:
  3894. V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
  3895. return V == nullptr;
  3896. case ValID::t_APSInt:
  3897. if (!Ty->isIntegerTy())
  3898. return Error(ID.Loc, "integer constant must have integer type");
  3899. ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
  3900. V = ConstantInt::get(Context, ID.APSIntVal);
  3901. return false;
  3902. case ValID::t_APFloat:
  3903. if (!Ty->isFloatingPointTy() ||
  3904. !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
  3905. return Error(ID.Loc, "floating point constant invalid for type");
  3906. // The lexer has no type info, so builds all half, float, and double FP
  3907. // constants as double. Fix this here. Long double does not need this.
  3908. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
  3909. bool Ignored;
  3910. if (Ty->isHalfTy())
  3911. ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
  3912. &Ignored);
  3913. else if (Ty->isFloatTy())
  3914. ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
  3915. &Ignored);
  3916. }
  3917. V = ConstantFP::get(Context, ID.APFloatVal);
  3918. if (V->getType() != Ty)
  3919. return Error(ID.Loc, "floating point constant does not have type '" +
  3920. getTypeString(Ty) + "'");
  3921. return false;
  3922. case ValID::t_Null:
  3923. if (!Ty->isPointerTy())
  3924. return Error(ID.Loc, "null must be a pointer type");
  3925. V = ConstantPointerNull::get(cast<PointerType>(Ty));
  3926. return false;
  3927. case ValID::t_Undef:
  3928. // FIXME: LabelTy should not be a first-class type.
  3929. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  3930. return Error(ID.Loc, "invalid type for undef constant");
  3931. V = UndefValue::get(Ty);
  3932. return false;
  3933. case ValID::t_EmptyArray:
  3934. if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
  3935. return Error(ID.Loc, "invalid empty array initializer");
  3936. V = UndefValue::get(Ty);
  3937. return false;
  3938. case ValID::t_Zero:
  3939. // FIXME: LabelTy should not be a first-class type.
  3940. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  3941. return Error(ID.Loc, "invalid type for null constant");
  3942. V = Constant::getNullValue(Ty);
  3943. return false;
  3944. case ValID::t_None:
  3945. if (!Ty->isTokenTy())
  3946. return Error(ID.Loc, "invalid type for none constant");
  3947. V = Constant::getNullValue(Ty);
  3948. return false;
  3949. case ValID::t_Constant:
  3950. if (ID.ConstantVal->getType() != Ty)
  3951. return Error(ID.Loc, "constant expression type mismatch");
  3952. V = ID.ConstantVal;
  3953. return false;
  3954. case ValID::t_ConstantStruct:
  3955. case ValID::t_PackedConstantStruct:
  3956. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3957. if (ST->getNumElements() != ID.UIntVal)
  3958. return Error(ID.Loc,
  3959. "initializer with struct type has wrong # elements");
  3960. if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
  3961. return Error(ID.Loc, "packed'ness of initializer and type don't match");
  3962. // Verify that the elements are compatible with the structtype.
  3963. for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
  3964. if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
  3965. return Error(ID.Loc, "element " + Twine(i) +
  3966. " of struct initializer doesn't match struct element type");
  3967. V = ConstantStruct::get(
  3968. ST, makeArrayRef(ID.ConstantStructElts.get(), ID.UIntVal));
  3969. } else
  3970. return Error(ID.Loc, "constant expression type mismatch");
  3971. return false;
  3972. }
  3973. llvm_unreachable("Invalid ValID");
  3974. }
  3975. bool LLParser::parseConstantValue(Type *Ty, Constant *&C) {
  3976. C = nullptr;
  3977. ValID ID;
  3978. auto Loc = Lex.getLoc();
  3979. if (ParseValID(ID, /*PFS=*/nullptr))
  3980. return true;
  3981. switch (ID.Kind) {
  3982. case ValID::t_APSInt:
  3983. case ValID::t_APFloat:
  3984. case ValID::t_Undef:
  3985. case ValID::t_Constant:
  3986. case ValID::t_ConstantStruct:
  3987. case ValID::t_PackedConstantStruct: {
  3988. Value *V;
  3989. if (ConvertValIDToValue(Ty, ID, V, /*PFS=*/nullptr))
  3990. return true;
  3991. assert(isa<Constant>(V) && "Expected a constant value");
  3992. C = cast<Constant>(V);
  3993. return false;
  3994. }
  3995. default:
  3996. return Error(Loc, "expected a constant value");
  3997. }
  3998. }
  3999. bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
  4000. V = nullptr;
  4001. ValID ID;
  4002. return ParseValID(ID, PFS) || ConvertValIDToValue(Ty, ID, V, PFS);
  4003. }
  4004. bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
  4005. Type *Ty = nullptr;
  4006. return ParseType(Ty) ||
  4007. ParseValue(Ty, V, PFS);
  4008. }
  4009. bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
  4010. PerFunctionState &PFS) {
  4011. Value *V;
  4012. Loc = Lex.getLoc();
  4013. if (ParseTypeAndValue(V, PFS)) return true;
  4014. if (!isa<BasicBlock>(V))
  4015. return Error(Loc, "expected a basic block");
  4016. BB = cast<BasicBlock>(V);
  4017. return false;
  4018. }
  4019. /// FunctionHeader
  4020. /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
  4021. /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
  4022. /// OptionalAlign OptGC OptionalPrefix OptionalPrologue OptPersonalityFn
  4023. bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
  4024. // Parse the linkage.
  4025. LocTy LinkageLoc = Lex.getLoc();
  4026. unsigned Linkage;
  4027. unsigned Visibility;
  4028. unsigned DLLStorageClass;
  4029. AttrBuilder RetAttrs;
  4030. unsigned CC;
  4031. bool HasLinkage;
  4032. Type *RetType = nullptr;
  4033. LocTy RetTypeLoc = Lex.getLoc();
  4034. if (ParseOptionalLinkage(Linkage, HasLinkage, Visibility, DLLStorageClass) ||
  4035. ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  4036. ParseType(RetType, RetTypeLoc, true /*void allowed*/))
  4037. return true;
  4038. // Verify that the linkage is ok.
  4039. switch ((GlobalValue::LinkageTypes)Linkage) {
  4040. case GlobalValue::ExternalLinkage:
  4041. break; // always ok.
  4042. case GlobalValue::ExternalWeakLinkage:
  4043. if (isDefine)
  4044. return Error(LinkageLoc, "invalid linkage for function definition");
  4045. break;
  4046. case GlobalValue::PrivateLinkage:
  4047. case GlobalValue::InternalLinkage:
  4048. case GlobalValue::AvailableExternallyLinkage:
  4049. case GlobalValue::LinkOnceAnyLinkage:
  4050. case GlobalValue::LinkOnceODRLinkage:
  4051. case GlobalValue::WeakAnyLinkage:
  4052. case GlobalValue::WeakODRLinkage:
  4053. if (!isDefine)
  4054. return Error(LinkageLoc, "invalid linkage for function declaration");
  4055. break;
  4056. case GlobalValue::AppendingLinkage:
  4057. case GlobalValue::CommonLinkage:
  4058. return Error(LinkageLoc, "invalid function linkage type");
  4059. }
  4060. if (!isValidVisibilityForLinkage(Visibility, Linkage))
  4061. return Error(LinkageLoc,
  4062. "symbol with local linkage must have default visibility");
  4063. if (!FunctionType::isValidReturnType(RetType))
  4064. return Error(RetTypeLoc, "invalid function return type");
  4065. LocTy NameLoc = Lex.getLoc();
  4066. std::string FunctionName;
  4067. if (Lex.getKind() == lltok::GlobalVar) {
  4068. FunctionName = Lex.getStrVal();
  4069. } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
  4070. unsigned NameID = Lex.getUIntVal();
  4071. if (NameID != NumberedVals.size())
  4072. return TokError("function expected to be numbered '%" +
  4073. Twine(NumberedVals.size()) + "'");
  4074. } else {
  4075. return TokError("expected function name");
  4076. }
  4077. Lex.Lex();
  4078. if (Lex.getKind() != lltok::lparen)
  4079. return TokError("expected '(' in function argument list");
  4080. SmallVector<ArgInfo, 8> ArgList;
  4081. bool isVarArg;
  4082. AttrBuilder FuncAttrs;
  4083. std::vector<unsigned> FwdRefAttrGrps;
  4084. LocTy BuiltinLoc;
  4085. std::string Section;
  4086. unsigned Alignment;
  4087. std::string GC;
  4088. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  4089. LocTy UnnamedAddrLoc;
  4090. Constant *Prefix = nullptr;
  4091. Constant *Prologue = nullptr;
  4092. Constant *PersonalityFn = nullptr;
  4093. Comdat *C;
  4094. if (ParseArgumentList(ArgList, isVarArg) ||
  4095. ParseOptionalUnnamedAddr(UnnamedAddr) ||
  4096. ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
  4097. BuiltinLoc) ||
  4098. (EatIfPresent(lltok::kw_section) &&
  4099. ParseStringConstant(Section)) ||
  4100. parseOptionalComdat(FunctionName, C) ||
  4101. ParseOptionalAlignment(Alignment) ||
  4102. (EatIfPresent(lltok::kw_gc) &&
  4103. ParseStringConstant(GC)) ||
  4104. (EatIfPresent(lltok::kw_prefix) &&
  4105. ParseGlobalTypeAndValue(Prefix)) ||
  4106. (EatIfPresent(lltok::kw_prologue) &&
  4107. ParseGlobalTypeAndValue(Prologue)) ||
  4108. (EatIfPresent(lltok::kw_personality) &&
  4109. ParseGlobalTypeAndValue(PersonalityFn)))
  4110. return true;
  4111. if (FuncAttrs.contains(Attribute::Builtin))
  4112. return Error(BuiltinLoc, "'builtin' attribute not valid on function");
  4113. // If the alignment was parsed as an attribute, move to the alignment field.
  4114. if (FuncAttrs.hasAlignmentAttr()) {
  4115. Alignment = FuncAttrs.getAlignment();
  4116. FuncAttrs.removeAttribute(Attribute::Alignment);
  4117. }
  4118. // Okay, if we got here, the function is syntactically valid. Convert types
  4119. // and do semantic checks.
  4120. std::vector<Type*> ParamTypeList;
  4121. SmallVector<AttributeSet, 8> Attrs;
  4122. if (RetAttrs.hasAttributes())
  4123. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  4124. AttributeSet::ReturnIndex,
  4125. RetAttrs));
  4126. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  4127. ParamTypeList.push_back(ArgList[i].Ty);
  4128. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  4129. AttrBuilder B(ArgList[i].Attrs, i + 1);
  4130. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  4131. }
  4132. }
  4133. if (FuncAttrs.hasAttributes())
  4134. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  4135. AttributeSet::FunctionIndex,
  4136. FuncAttrs));
  4137. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  4138. if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
  4139. return Error(RetTypeLoc, "functions with 'sret' argument must return void");
  4140. FunctionType *FT =
  4141. FunctionType::get(RetType, ParamTypeList, isVarArg);
  4142. PointerType *PFT = PointerType::getUnqual(FT);
  4143. Fn = nullptr;
  4144. if (!FunctionName.empty()) {
  4145. // If this was a definition of a forward reference, remove the definition
  4146. // from the forward reference table and fill in the forward ref.
  4147. auto FRVI = ForwardRefVals.find(FunctionName);
  4148. if (FRVI != ForwardRefVals.end()) {
  4149. Fn = M->getFunction(FunctionName);
  4150. if (!Fn)
  4151. return Error(FRVI->second.second, "invalid forward reference to "
  4152. "function as global value!");
  4153. if (Fn->getType() != PFT)
  4154. return Error(FRVI->second.second, "invalid forward reference to "
  4155. "function '" + FunctionName + "' with wrong type!");
  4156. ForwardRefVals.erase(FRVI);
  4157. } else if ((Fn = M->getFunction(FunctionName))) {
  4158. // Reject redefinitions.
  4159. return Error(NameLoc, "invalid redefinition of function '" +
  4160. FunctionName + "'");
  4161. } else if (M->getNamedValue(FunctionName)) {
  4162. return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
  4163. }
  4164. } else {
  4165. // If this is a definition of a forward referenced function, make sure the
  4166. // types agree.
  4167. auto I = ForwardRefValIDs.find(NumberedVals.size());
  4168. if (I != ForwardRefValIDs.end()) {
  4169. Fn = cast<Function>(I->second.first);
  4170. if (Fn->getType() != PFT)
  4171. return Error(NameLoc, "type of definition and forward reference of '@" +
  4172. Twine(NumberedVals.size()) + "' disagree");
  4173. ForwardRefValIDs.erase(I);
  4174. }
  4175. }
  4176. if (!Fn)
  4177. Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
  4178. else // Move the forward-reference to the correct spot in the module.
  4179. M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
  4180. if (FunctionName.empty())
  4181. NumberedVals.push_back(Fn);
  4182. Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
  4183. Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  4184. Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  4185. Fn->setCallingConv(CC);
  4186. Fn->setAttributes(PAL);
  4187. Fn->setUnnamedAddr(UnnamedAddr);
  4188. Fn->setAlignment(Alignment);
  4189. Fn->setSection(Section);
  4190. Fn->setComdat(C);
  4191. Fn->setPersonalityFn(PersonalityFn);
  4192. if (!GC.empty()) Fn->setGC(GC);
  4193. Fn->setPrefixData(Prefix);
  4194. Fn->setPrologueData(Prologue);
  4195. ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
  4196. // Add all of the arguments we parsed to the function.
  4197. Function::arg_iterator ArgIt = Fn->arg_begin();
  4198. for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
  4199. // If the argument has a name, insert it into the argument symbol table.
  4200. if (ArgList[i].Name.empty()) continue;
  4201. // Set the name, if it conflicted, it will be auto-renamed.
  4202. ArgIt->setName(ArgList[i].Name);
  4203. if (ArgIt->getName() != ArgList[i].Name)
  4204. return Error(ArgList[i].Loc, "redefinition of argument '%" +
  4205. ArgList[i].Name + "'");
  4206. }
  4207. if (isDefine)
  4208. return false;
  4209. // Check the declaration has no block address forward references.
  4210. ValID ID;
  4211. if (FunctionName.empty()) {
  4212. ID.Kind = ValID::t_GlobalID;
  4213. ID.UIntVal = NumberedVals.size() - 1;
  4214. } else {
  4215. ID.Kind = ValID::t_GlobalName;
  4216. ID.StrVal = FunctionName;
  4217. }
  4218. auto Blocks = ForwardRefBlockAddresses.find(ID);
  4219. if (Blocks != ForwardRefBlockAddresses.end())
  4220. return Error(Blocks->first.Loc,
  4221. "cannot take blockaddress inside a declaration");
  4222. return false;
  4223. }
  4224. bool LLParser::PerFunctionState::resolveForwardRefBlockAddresses() {
  4225. ValID ID;
  4226. if (FunctionNumber == -1) {
  4227. ID.Kind = ValID::t_GlobalName;
  4228. ID.StrVal = F.getName();
  4229. } else {
  4230. ID.Kind = ValID::t_GlobalID;
  4231. ID.UIntVal = FunctionNumber;
  4232. }
  4233. auto Blocks = P.ForwardRefBlockAddresses.find(ID);
  4234. if (Blocks == P.ForwardRefBlockAddresses.end())
  4235. return false;
  4236. for (const auto &I : Blocks->second) {
  4237. const ValID &BBID = I.first;
  4238. GlobalValue *GV = I.second;
  4239. assert((BBID.Kind == ValID::t_LocalID || BBID.Kind == ValID::t_LocalName) &&
  4240. "Expected local id or name");
  4241. BasicBlock *BB;
  4242. if (BBID.Kind == ValID::t_LocalName)
  4243. BB = GetBB(BBID.StrVal, BBID.Loc);
  4244. else
  4245. BB = GetBB(BBID.UIntVal, BBID.Loc);
  4246. if (!BB)
  4247. return P.Error(BBID.Loc, "referenced value is not a basic block");
  4248. GV->replaceAllUsesWith(BlockAddress::get(&F, BB));
  4249. GV->eraseFromParent();
  4250. }
  4251. P.ForwardRefBlockAddresses.erase(Blocks);
  4252. return false;
  4253. }
  4254. /// ParseFunctionBody
  4255. /// ::= '{' BasicBlock+ UseListOrderDirective* '}'
  4256. bool LLParser::ParseFunctionBody(Function &Fn) {
  4257. if (Lex.getKind() != lltok::lbrace)
  4258. return TokError("expected '{' in function body");
  4259. Lex.Lex(); // eat the {.
  4260. int FunctionNumber = -1;
  4261. if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
  4262. PerFunctionState PFS(*this, Fn, FunctionNumber);
  4263. // Resolve block addresses and allow basic blocks to be forward-declared
  4264. // within this function.
  4265. if (PFS.resolveForwardRefBlockAddresses())
  4266. return true;
  4267. SaveAndRestore<PerFunctionState *> ScopeExit(BlockAddressPFS, &PFS);
  4268. // We need at least one basic block.
  4269. if (Lex.getKind() == lltok::rbrace || Lex.getKind() == lltok::kw_uselistorder)
  4270. return TokError("function body requires at least one basic block");
  4271. while (Lex.getKind() != lltok::rbrace &&
  4272. Lex.getKind() != lltok::kw_uselistorder)
  4273. if (ParseBasicBlock(PFS)) return true;
  4274. while (Lex.getKind() != lltok::rbrace)
  4275. if (ParseUseListOrder(&PFS))
  4276. return true;
  4277. // Eat the }.
  4278. Lex.Lex();
  4279. // Verify function is ok.
  4280. return PFS.FinishFunction();
  4281. }
  4282. /// ParseBasicBlock
  4283. /// ::= LabelStr? Instruction*
  4284. bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
  4285. // If this basic block starts out with a name, remember it.
  4286. std::string Name;
  4287. LocTy NameLoc = Lex.getLoc();
  4288. if (Lex.getKind() == lltok::LabelStr) {
  4289. Name = Lex.getStrVal();
  4290. Lex.Lex();
  4291. }
  4292. BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
  4293. if (!BB)
  4294. return Error(NameLoc,
  4295. "unable to create block named '" + Name + "'");
  4296. std::string NameStr;
  4297. // Parse the instructions in this block until we get a terminator.
  4298. Instruction *Inst;
  4299. do {
  4300. // This instruction may have three possibilities for a name: a) none
  4301. // specified, b) name specified "%foo =", c) number specified: "%4 =".
  4302. LocTy NameLoc = Lex.getLoc();
  4303. int NameID = -1;
  4304. NameStr = "";
  4305. if (Lex.getKind() == lltok::LocalVarID) {
  4306. NameID = Lex.getUIntVal();
  4307. Lex.Lex();
  4308. if (ParseToken(lltok::equal, "expected '=' after instruction id"))
  4309. return true;
  4310. } else if (Lex.getKind() == lltok::LocalVar) {
  4311. NameStr = Lex.getStrVal();
  4312. Lex.Lex();
  4313. if (ParseToken(lltok::equal, "expected '=' after instruction name"))
  4314. return true;
  4315. }
  4316. switch (ParseInstruction(Inst, BB, PFS)) {
  4317. default: llvm_unreachable("Unknown ParseInstruction result!");
  4318. case InstError: return true;
  4319. case InstNormal:
  4320. BB->getInstList().push_back(Inst);
  4321. // With a normal result, we check to see if the instruction is followed by
  4322. // a comma and metadata.
  4323. if (EatIfPresent(lltok::comma))
  4324. if (ParseInstructionMetadata(*Inst))
  4325. return true;
  4326. break;
  4327. case InstExtraComma:
  4328. BB->getInstList().push_back(Inst);
  4329. // If the instruction parser ate an extra comma at the end of it, it
  4330. // *must* be followed by metadata.
  4331. if (ParseInstructionMetadata(*Inst))
  4332. return true;
  4333. break;
  4334. }
  4335. // Set the name on the instruction.
  4336. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
  4337. } while (!isa<TerminatorInst>(Inst));
  4338. return false;
  4339. }
  4340. //===----------------------------------------------------------------------===//
  4341. // Instruction Parsing.
  4342. //===----------------------------------------------------------------------===//
  4343. /// ParseInstruction - Parse one of the many different instructions.
  4344. ///
  4345. int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
  4346. PerFunctionState &PFS) {
  4347. lltok::Kind Token = Lex.getKind();
  4348. if (Token == lltok::Eof)
  4349. return TokError("found end of file when expecting more instructions");
  4350. LocTy Loc = Lex.getLoc();
  4351. unsigned KeywordVal = Lex.getUIntVal();
  4352. Lex.Lex(); // Eat the keyword.
  4353. switch (Token) {
  4354. default: return Error(Loc, "expected instruction opcode");
  4355. // Terminator Instructions.
  4356. case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
  4357. case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
  4358. case lltok::kw_br: return ParseBr(Inst, PFS);
  4359. case lltok::kw_switch: return ParseSwitch(Inst, PFS);
  4360. case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
  4361. case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
  4362. case lltok::kw_resume: return ParseResume(Inst, PFS);
  4363. case lltok::kw_cleanupret: return ParseCleanupRet(Inst, PFS);
  4364. case lltok::kw_catchret: return ParseCatchRet(Inst, PFS);
  4365. case lltok::kw_catchswitch: return ParseCatchSwitch(Inst, PFS);
  4366. case lltok::kw_catchpad: return ParseCatchPad(Inst, PFS);
  4367. case lltok::kw_cleanuppad: return ParseCleanupPad(Inst, PFS);
  4368. // Binary Operators.
  4369. case lltok::kw_add:
  4370. case lltok::kw_sub:
  4371. case lltok::kw_mul:
  4372. case lltok::kw_shl: {
  4373. bool NUW = EatIfPresent(lltok::kw_nuw);
  4374. bool NSW = EatIfPresent(lltok::kw_nsw);
  4375. if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
  4376. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  4377. if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
  4378. if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
  4379. return false;
  4380. }
  4381. case lltok::kw_fadd:
  4382. case lltok::kw_fsub:
  4383. case lltok::kw_fmul:
  4384. case lltok::kw_fdiv:
  4385. case lltok::kw_frem: {
  4386. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  4387. int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
  4388. if (Res != 0)
  4389. return Res;
  4390. if (FMF.any())
  4391. Inst->setFastMathFlags(FMF);
  4392. return 0;
  4393. }
  4394. case lltok::kw_sdiv:
  4395. case lltok::kw_udiv:
  4396. case lltok::kw_lshr:
  4397. case lltok::kw_ashr: {
  4398. bool Exact = EatIfPresent(lltok::kw_exact);
  4399. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  4400. if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
  4401. return false;
  4402. }
  4403. case lltok::kw_urem:
  4404. case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
  4405. case lltok::kw_and:
  4406. case lltok::kw_or:
  4407. case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
  4408. case lltok::kw_icmp: return ParseCompare(Inst, PFS, KeywordVal);
  4409. case lltok::kw_fcmp: {
  4410. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  4411. int Res = ParseCompare(Inst, PFS, KeywordVal);
  4412. if (Res != 0)
  4413. return Res;
  4414. if (FMF.any())
  4415. Inst->setFastMathFlags(FMF);
  4416. return 0;
  4417. }
  4418. // Casts.
  4419. case lltok::kw_trunc:
  4420. case lltok::kw_zext:
  4421. case lltok::kw_sext:
  4422. case lltok::kw_fptrunc:
  4423. case lltok::kw_fpext:
  4424. case lltok::kw_bitcast:
  4425. case lltok::kw_addrspacecast:
  4426. case lltok::kw_uitofp:
  4427. case lltok::kw_sitofp:
  4428. case lltok::kw_fptoui:
  4429. case lltok::kw_fptosi:
  4430. case lltok::kw_inttoptr:
  4431. case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
  4432. // Other.
  4433. case lltok::kw_select: return ParseSelect(Inst, PFS);
  4434. case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
  4435. case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
  4436. case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
  4437. case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
  4438. case lltok::kw_phi: return ParsePHI(Inst, PFS);
  4439. case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
  4440. // Call.
  4441. case lltok::kw_call: return ParseCall(Inst, PFS, CallInst::TCK_None);
  4442. case lltok::kw_tail: return ParseCall(Inst, PFS, CallInst::TCK_Tail);
  4443. case lltok::kw_musttail: return ParseCall(Inst, PFS, CallInst::TCK_MustTail);
  4444. case lltok::kw_notail: return ParseCall(Inst, PFS, CallInst::TCK_NoTail);
  4445. // Memory.
  4446. case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
  4447. case lltok::kw_load: return ParseLoad(Inst, PFS);
  4448. case lltok::kw_store: return ParseStore(Inst, PFS);
  4449. case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
  4450. case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
  4451. case lltok::kw_fence: return ParseFence(Inst, PFS);
  4452. case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
  4453. case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
  4454. case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
  4455. }
  4456. }
  4457. /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
  4458. bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
  4459. if (Opc == Instruction::FCmp) {
  4460. switch (Lex.getKind()) {
  4461. default: return TokError("expected fcmp predicate (e.g. 'oeq')");
  4462. case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
  4463. case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
  4464. case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
  4465. case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
  4466. case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
  4467. case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
  4468. case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
  4469. case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
  4470. case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
  4471. case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
  4472. case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
  4473. case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
  4474. case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
  4475. case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
  4476. case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
  4477. case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
  4478. }
  4479. } else {
  4480. switch (Lex.getKind()) {
  4481. default: return TokError("expected icmp predicate (e.g. 'eq')");
  4482. case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
  4483. case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
  4484. case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
  4485. case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
  4486. case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
  4487. case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
  4488. case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
  4489. case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
  4490. case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
  4491. case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
  4492. }
  4493. }
  4494. Lex.Lex();
  4495. return false;
  4496. }
  4497. //===----------------------------------------------------------------------===//
  4498. // Terminator Instructions.
  4499. //===----------------------------------------------------------------------===//
  4500. /// ParseRet - Parse a return instruction.
  4501. /// ::= 'ret' void (',' !dbg, !1)*
  4502. /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
  4503. bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
  4504. PerFunctionState &PFS) {
  4505. SMLoc TypeLoc = Lex.getLoc();
  4506. Type *Ty = nullptr;
  4507. if (ParseType(Ty, true /*void allowed*/)) return true;
  4508. Type *ResType = PFS.getFunction().getReturnType();
  4509. if (Ty->isVoidTy()) {
  4510. if (!ResType->isVoidTy())
  4511. return Error(TypeLoc, "value doesn't match function result type '" +
  4512. getTypeString(ResType) + "'");
  4513. Inst = ReturnInst::Create(Context);
  4514. return false;
  4515. }
  4516. Value *RV;
  4517. if (ParseValue(Ty, RV, PFS)) return true;
  4518. if (ResType != RV->getType())
  4519. return Error(TypeLoc, "value doesn't match function result type '" +
  4520. getTypeString(ResType) + "'");
  4521. Inst = ReturnInst::Create(Context, RV);
  4522. return false;
  4523. }
  4524. /// ParseBr
  4525. /// ::= 'br' TypeAndValue
  4526. /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  4527. bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
  4528. LocTy Loc, Loc2;
  4529. Value *Op0;
  4530. BasicBlock *Op1, *Op2;
  4531. if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
  4532. if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
  4533. Inst = BranchInst::Create(BB);
  4534. return false;
  4535. }
  4536. if (Op0->getType() != Type::getInt1Ty(Context))
  4537. return Error(Loc, "branch condition must have 'i1' type");
  4538. if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
  4539. ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
  4540. ParseToken(lltok::comma, "expected ',' after true destination") ||
  4541. ParseTypeAndBasicBlock(Op2, Loc2, PFS))
  4542. return true;
  4543. Inst = BranchInst::Create(Op1, Op2, Op0);
  4544. return false;
  4545. }
  4546. /// ParseSwitch
  4547. /// Instruction
  4548. /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
  4549. /// JumpTable
  4550. /// ::= (TypeAndValue ',' TypeAndValue)*
  4551. bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  4552. LocTy CondLoc, BBLoc;
  4553. Value *Cond;
  4554. BasicBlock *DefaultBB;
  4555. if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
  4556. ParseToken(lltok::comma, "expected ',' after switch condition") ||
  4557. ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
  4558. ParseToken(lltok::lsquare, "expected '[' with switch table"))
  4559. return true;
  4560. if (!Cond->getType()->isIntegerTy())
  4561. return Error(CondLoc, "switch condition must have integer type");
  4562. // Parse the jump table pairs.
  4563. SmallPtrSet<Value*, 32> SeenCases;
  4564. SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
  4565. while (Lex.getKind() != lltok::rsquare) {
  4566. Value *Constant;
  4567. BasicBlock *DestBB;
  4568. if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
  4569. ParseToken(lltok::comma, "expected ',' after case value") ||
  4570. ParseTypeAndBasicBlock(DestBB, PFS))
  4571. return true;
  4572. if (!SeenCases.insert(Constant).second)
  4573. return Error(CondLoc, "duplicate case value in switch");
  4574. if (!isa<ConstantInt>(Constant))
  4575. return Error(CondLoc, "case value is not a constant integer");
  4576. Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
  4577. }
  4578. Lex.Lex(); // Eat the ']'.
  4579. SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
  4580. for (unsigned i = 0, e = Table.size(); i != e; ++i)
  4581. SI->addCase(Table[i].first, Table[i].second);
  4582. Inst = SI;
  4583. return false;
  4584. }
  4585. /// ParseIndirectBr
  4586. /// Instruction
  4587. /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
  4588. bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
  4589. LocTy AddrLoc;
  4590. Value *Address;
  4591. if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
  4592. ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
  4593. ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
  4594. return true;
  4595. if (!Address->getType()->isPointerTy())
  4596. return Error(AddrLoc, "indirectbr address must have pointer type");
  4597. // Parse the destination list.
  4598. SmallVector<BasicBlock*, 16> DestList;
  4599. if (Lex.getKind() != lltok::rsquare) {
  4600. BasicBlock *DestBB;
  4601. if (ParseTypeAndBasicBlock(DestBB, PFS))
  4602. return true;
  4603. DestList.push_back(DestBB);
  4604. while (EatIfPresent(lltok::comma)) {
  4605. if (ParseTypeAndBasicBlock(DestBB, PFS))
  4606. return true;
  4607. DestList.push_back(DestBB);
  4608. }
  4609. }
  4610. if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
  4611. return true;
  4612. IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
  4613. for (unsigned i = 0, e = DestList.size(); i != e; ++i)
  4614. IBI->addDestination(DestList[i]);
  4615. Inst = IBI;
  4616. return false;
  4617. }
  4618. /// ParseInvoke
  4619. /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
  4620. /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
  4621. bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
  4622. LocTy CallLoc = Lex.getLoc();
  4623. AttrBuilder RetAttrs, FnAttrs;
  4624. std::vector<unsigned> FwdRefAttrGrps;
  4625. LocTy NoBuiltinLoc;
  4626. unsigned CC;
  4627. Type *RetType = nullptr;
  4628. LocTy RetTypeLoc;
  4629. ValID CalleeID;
  4630. SmallVector<ParamInfo, 16> ArgList;
  4631. SmallVector<OperandBundleDef, 2> BundleList;
  4632. BasicBlock *NormalBB, *UnwindBB;
  4633. if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  4634. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  4635. ParseValID(CalleeID) || ParseParameterList(ArgList, PFS) ||
  4636. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  4637. NoBuiltinLoc) ||
  4638. ParseOptionalOperandBundles(BundleList, PFS) ||
  4639. ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
  4640. ParseTypeAndBasicBlock(NormalBB, PFS) ||
  4641. ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
  4642. ParseTypeAndBasicBlock(UnwindBB, PFS))
  4643. return true;
  4644. // If RetType is a non-function pointer type, then this is the short syntax
  4645. // for the call, which means that RetType is just the return type. Infer the
  4646. // rest of the function argument types from the arguments that are present.
  4647. FunctionType *Ty = dyn_cast<FunctionType>(RetType);
  4648. if (!Ty) {
  4649. // Pull out the types of all of the arguments...
  4650. std::vector<Type*> ParamTypes;
  4651. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  4652. ParamTypes.push_back(ArgList[i].V->getType());
  4653. if (!FunctionType::isValidReturnType(RetType))
  4654. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  4655. Ty = FunctionType::get(RetType, ParamTypes, false);
  4656. }
  4657. CalleeID.FTy = Ty;
  4658. // Look up the callee.
  4659. Value *Callee;
  4660. if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
  4661. return true;
  4662. // Set up the Attribute for the function.
  4663. SmallVector<AttributeSet, 8> Attrs;
  4664. if (RetAttrs.hasAttributes())
  4665. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  4666. AttributeSet::ReturnIndex,
  4667. RetAttrs));
  4668. SmallVector<Value*, 8> Args;
  4669. // Loop through FunctionType's arguments and ensure they are specified
  4670. // correctly. Also, gather any parameter attributes.
  4671. FunctionType::param_iterator I = Ty->param_begin();
  4672. FunctionType::param_iterator E = Ty->param_end();
  4673. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  4674. Type *ExpectedTy = nullptr;
  4675. if (I != E) {
  4676. ExpectedTy = *I++;
  4677. } else if (!Ty->isVarArg()) {
  4678. return Error(ArgList[i].Loc, "too many arguments specified");
  4679. }
  4680. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  4681. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  4682. getTypeString(ExpectedTy) + "'");
  4683. Args.push_back(ArgList[i].V);
  4684. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  4685. AttrBuilder B(ArgList[i].Attrs, i + 1);
  4686. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  4687. }
  4688. }
  4689. if (I != E)
  4690. return Error(CallLoc, "not enough parameters specified for call");
  4691. if (FnAttrs.hasAttributes()) {
  4692. if (FnAttrs.hasAlignmentAttr())
  4693. return Error(CallLoc, "invoke instructions may not have an alignment");
  4694. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  4695. AttributeSet::FunctionIndex,
  4696. FnAttrs));
  4697. }
  4698. // Finish off the Attribute and check them
  4699. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  4700. InvokeInst *II =
  4701. InvokeInst::Create(Ty, Callee, NormalBB, UnwindBB, Args, BundleList);
  4702. II->setCallingConv(CC);
  4703. II->setAttributes(PAL);
  4704. ForwardRefAttrGroups[II] = FwdRefAttrGrps;
  4705. Inst = II;
  4706. return false;
  4707. }
  4708. /// ParseResume
  4709. /// ::= 'resume' TypeAndValue
  4710. bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
  4711. Value *Exn; LocTy ExnLoc;
  4712. if (ParseTypeAndValue(Exn, ExnLoc, PFS))
  4713. return true;
  4714. ResumeInst *RI = ResumeInst::Create(Exn);
  4715. Inst = RI;
  4716. return false;
  4717. }
  4718. bool LLParser::ParseExceptionArgs(SmallVectorImpl<Value *> &Args,
  4719. PerFunctionState &PFS) {
  4720. if (ParseToken(lltok::lsquare, "expected '[' in catchpad/cleanuppad"))
  4721. return true;
  4722. while (Lex.getKind() != lltok::rsquare) {
  4723. // If this isn't the first argument, we need a comma.
  4724. if (!Args.empty() &&
  4725. ParseToken(lltok::comma, "expected ',' in argument list"))
  4726. return true;
  4727. // Parse the argument.
  4728. LocTy ArgLoc;
  4729. Type *ArgTy = nullptr;
  4730. if (ParseType(ArgTy, ArgLoc))
  4731. return true;
  4732. Value *V;
  4733. if (ArgTy->isMetadataTy()) {
  4734. if (ParseMetadataAsValue(V, PFS))
  4735. return true;
  4736. } else {
  4737. if (ParseValue(ArgTy, V, PFS))
  4738. return true;
  4739. }
  4740. Args.push_back(V);
  4741. }
  4742. Lex.Lex(); // Lex the ']'.
  4743. return false;
  4744. }
  4745. /// ParseCleanupRet
  4746. /// ::= 'cleanupret' from Value unwind ('to' 'caller' | TypeAndValue)
  4747. bool LLParser::ParseCleanupRet(Instruction *&Inst, PerFunctionState &PFS) {
  4748. Value *CleanupPad = nullptr;
  4749. if (ParseToken(lltok::kw_from, "expected 'from' after cleanupret"))
  4750. return true;
  4751. if (ParseValue(Type::getTokenTy(Context), CleanupPad, PFS))
  4752. return true;
  4753. if (ParseToken(lltok::kw_unwind, "expected 'unwind' in cleanupret"))
  4754. return true;
  4755. BasicBlock *UnwindBB = nullptr;
  4756. if (Lex.getKind() == lltok::kw_to) {
  4757. Lex.Lex();
  4758. if (ParseToken(lltok::kw_caller, "expected 'caller' in cleanupret"))
  4759. return true;
  4760. } else {
  4761. if (ParseTypeAndBasicBlock(UnwindBB, PFS)) {
  4762. return true;
  4763. }
  4764. }
  4765. Inst = CleanupReturnInst::Create(CleanupPad, UnwindBB);
  4766. return false;
  4767. }
  4768. /// ParseCatchRet
  4769. /// ::= 'catchret' from Parent Value 'to' TypeAndValue
  4770. bool LLParser::ParseCatchRet(Instruction *&Inst, PerFunctionState &PFS) {
  4771. Value *CatchPad = nullptr;
  4772. if (ParseToken(lltok::kw_from, "expected 'from' after catchret"))
  4773. return true;
  4774. if (ParseValue(Type::getTokenTy(Context), CatchPad, PFS))
  4775. return true;
  4776. BasicBlock *BB;
  4777. if (ParseToken(lltok::kw_to, "expected 'to' in catchret") ||
  4778. ParseTypeAndBasicBlock(BB, PFS))
  4779. return true;
  4780. Inst = CatchReturnInst::Create(CatchPad, BB);
  4781. return false;
  4782. }
  4783. /// ParseCatchSwitch
  4784. /// ::= 'catchswitch' within Parent
  4785. bool LLParser::ParseCatchSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  4786. Value *ParentPad;
  4787. LocTy BBLoc;
  4788. if (ParseToken(lltok::kw_within, "expected 'within' after catchswitch"))
  4789. return true;
  4790. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  4791. Lex.getKind() != lltok::LocalVarID)
  4792. return TokError("expected scope value for catchswitch");
  4793. if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
  4794. return true;
  4795. if (ParseToken(lltok::lsquare, "expected '[' with catchswitch labels"))
  4796. return true;
  4797. SmallVector<BasicBlock *, 32> Table;
  4798. do {
  4799. BasicBlock *DestBB;
  4800. if (ParseTypeAndBasicBlock(DestBB, PFS))
  4801. return true;
  4802. Table.push_back(DestBB);
  4803. } while (EatIfPresent(lltok::comma));
  4804. if (ParseToken(lltok::rsquare, "expected ']' after catchswitch labels"))
  4805. return true;
  4806. if (ParseToken(lltok::kw_unwind,
  4807. "expected 'unwind' after catchswitch scope"))
  4808. return true;
  4809. BasicBlock *UnwindBB = nullptr;
  4810. if (EatIfPresent(lltok::kw_to)) {
  4811. if (ParseToken(lltok::kw_caller, "expected 'caller' in catchswitch"))
  4812. return true;
  4813. } else {
  4814. if (ParseTypeAndBasicBlock(UnwindBB, PFS))
  4815. return true;
  4816. }
  4817. auto *CatchSwitch =
  4818. CatchSwitchInst::Create(ParentPad, UnwindBB, Table.size());
  4819. for (BasicBlock *DestBB : Table)
  4820. CatchSwitch->addHandler(DestBB);
  4821. Inst = CatchSwitch;
  4822. return false;
  4823. }
  4824. /// ParseCatchPad
  4825. /// ::= 'catchpad' ParamList 'to' TypeAndValue 'unwind' TypeAndValue
  4826. bool LLParser::ParseCatchPad(Instruction *&Inst, PerFunctionState &PFS) {
  4827. Value *CatchSwitch = nullptr;
  4828. if (ParseToken(lltok::kw_within, "expected 'within' after catchpad"))
  4829. return true;
  4830. if (Lex.getKind() != lltok::LocalVar && Lex.getKind() != lltok::LocalVarID)
  4831. return TokError("expected scope value for catchpad");
  4832. if (ParseValue(Type::getTokenTy(Context), CatchSwitch, PFS))
  4833. return true;
  4834. SmallVector<Value *, 8> Args;
  4835. if (ParseExceptionArgs(Args, PFS))
  4836. return true;
  4837. Inst = CatchPadInst::Create(CatchSwitch, Args);
  4838. return false;
  4839. }
  4840. /// ParseCleanupPad
  4841. /// ::= 'cleanuppad' within Parent ParamList
  4842. bool LLParser::ParseCleanupPad(Instruction *&Inst, PerFunctionState &PFS) {
  4843. Value *ParentPad = nullptr;
  4844. if (ParseToken(lltok::kw_within, "expected 'within' after cleanuppad"))
  4845. return true;
  4846. if (Lex.getKind() != lltok::kw_none && Lex.getKind() != lltok::LocalVar &&
  4847. Lex.getKind() != lltok::LocalVarID)
  4848. return TokError("expected scope value for cleanuppad");
  4849. if (ParseValue(Type::getTokenTy(Context), ParentPad, PFS))
  4850. return true;
  4851. SmallVector<Value *, 8> Args;
  4852. if (ParseExceptionArgs(Args, PFS))
  4853. return true;
  4854. Inst = CleanupPadInst::Create(ParentPad, Args);
  4855. return false;
  4856. }
  4857. //===----------------------------------------------------------------------===//
  4858. // Binary Operators.
  4859. //===----------------------------------------------------------------------===//
  4860. /// ParseArithmetic
  4861. /// ::= ArithmeticOps TypeAndValue ',' Value
  4862. ///
  4863. /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
  4864. /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
  4865. bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
  4866. unsigned Opc, unsigned OperandType) {
  4867. LocTy Loc; Value *LHS, *RHS;
  4868. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  4869. ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
  4870. ParseValue(LHS->getType(), RHS, PFS))
  4871. return true;
  4872. bool Valid;
  4873. switch (OperandType) {
  4874. default: llvm_unreachable("Unknown operand type!");
  4875. case 0: // int or FP.
  4876. Valid = LHS->getType()->isIntOrIntVectorTy() ||
  4877. LHS->getType()->isFPOrFPVectorTy();
  4878. break;
  4879. case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
  4880. case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
  4881. }
  4882. if (!Valid)
  4883. return Error(Loc, "invalid operand type for instruction");
  4884. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  4885. return false;
  4886. }
  4887. /// ParseLogical
  4888. /// ::= ArithmeticOps TypeAndValue ',' Value {
  4889. bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
  4890. unsigned Opc) {
  4891. LocTy Loc; Value *LHS, *RHS;
  4892. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  4893. ParseToken(lltok::comma, "expected ',' in logical operation") ||
  4894. ParseValue(LHS->getType(), RHS, PFS))
  4895. return true;
  4896. if (!LHS->getType()->isIntOrIntVectorTy())
  4897. return Error(Loc,"instruction requires integer or integer vector operands");
  4898. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  4899. return false;
  4900. }
  4901. /// ParseCompare
  4902. /// ::= 'icmp' IPredicates TypeAndValue ',' Value
  4903. /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
  4904. bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
  4905. unsigned Opc) {
  4906. // Parse the integer/fp comparison predicate.
  4907. LocTy Loc;
  4908. unsigned Pred;
  4909. Value *LHS, *RHS;
  4910. if (ParseCmpPredicate(Pred, Opc) ||
  4911. ParseTypeAndValue(LHS, Loc, PFS) ||
  4912. ParseToken(lltok::comma, "expected ',' after compare value") ||
  4913. ParseValue(LHS->getType(), RHS, PFS))
  4914. return true;
  4915. if (Opc == Instruction::FCmp) {
  4916. if (!LHS->getType()->isFPOrFPVectorTy())
  4917. return Error(Loc, "fcmp requires floating point operands");
  4918. Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  4919. } else {
  4920. assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
  4921. if (!LHS->getType()->isIntOrIntVectorTy() &&
  4922. !LHS->getType()->getScalarType()->isPointerTy())
  4923. return Error(Loc, "icmp requires integer operands");
  4924. Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  4925. }
  4926. return false;
  4927. }
  4928. //===----------------------------------------------------------------------===//
  4929. // Other Instructions.
  4930. //===----------------------------------------------------------------------===//
  4931. /// ParseCast
  4932. /// ::= CastOpc TypeAndValue 'to' Type
  4933. bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
  4934. unsigned Opc) {
  4935. LocTy Loc;
  4936. Value *Op;
  4937. Type *DestTy = nullptr;
  4938. if (ParseTypeAndValue(Op, Loc, PFS) ||
  4939. ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
  4940. ParseType(DestTy))
  4941. return true;
  4942. if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
  4943. CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
  4944. return Error(Loc, "invalid cast opcode for cast from '" +
  4945. getTypeString(Op->getType()) + "' to '" +
  4946. getTypeString(DestTy) + "'");
  4947. }
  4948. Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
  4949. return false;
  4950. }
  4951. /// ParseSelect
  4952. /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  4953. bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
  4954. LocTy Loc;
  4955. Value *Op0, *Op1, *Op2;
  4956. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  4957. ParseToken(lltok::comma, "expected ',' after select condition") ||
  4958. ParseTypeAndValue(Op1, PFS) ||
  4959. ParseToken(lltok::comma, "expected ',' after select value") ||
  4960. ParseTypeAndValue(Op2, PFS))
  4961. return true;
  4962. if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
  4963. return Error(Loc, Reason);
  4964. Inst = SelectInst::Create(Op0, Op1, Op2);
  4965. return false;
  4966. }
  4967. /// ParseVA_Arg
  4968. /// ::= 'va_arg' TypeAndValue ',' Type
  4969. bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
  4970. Value *Op;
  4971. Type *EltTy = nullptr;
  4972. LocTy TypeLoc;
  4973. if (ParseTypeAndValue(Op, PFS) ||
  4974. ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
  4975. ParseType(EltTy, TypeLoc))
  4976. return true;
  4977. if (!EltTy->isFirstClassType())
  4978. return Error(TypeLoc, "va_arg requires operand with first class type");
  4979. Inst = new VAArgInst(Op, EltTy);
  4980. return false;
  4981. }
  4982. /// ParseExtractElement
  4983. /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
  4984. bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
  4985. LocTy Loc;
  4986. Value *Op0, *Op1;
  4987. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  4988. ParseToken(lltok::comma, "expected ',' after extract value") ||
  4989. ParseTypeAndValue(Op1, PFS))
  4990. return true;
  4991. if (!ExtractElementInst::isValidOperands(Op0, Op1))
  4992. return Error(Loc, "invalid extractelement operands");
  4993. Inst = ExtractElementInst::Create(Op0, Op1);
  4994. return false;
  4995. }
  4996. /// ParseInsertElement
  4997. /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  4998. bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
  4999. LocTy Loc;
  5000. Value *Op0, *Op1, *Op2;
  5001. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5002. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5003. ParseTypeAndValue(Op1, PFS) ||
  5004. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5005. ParseTypeAndValue(Op2, PFS))
  5006. return true;
  5007. if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
  5008. return Error(Loc, "invalid insertelement operands");
  5009. Inst = InsertElementInst::Create(Op0, Op1, Op2);
  5010. return false;
  5011. }
  5012. /// ParseShuffleVector
  5013. /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  5014. bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
  5015. LocTy Loc;
  5016. Value *Op0, *Op1, *Op2;
  5017. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  5018. ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
  5019. ParseTypeAndValue(Op1, PFS) ||
  5020. ParseToken(lltok::comma, "expected ',' after shuffle value") ||
  5021. ParseTypeAndValue(Op2, PFS))
  5022. return true;
  5023. if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
  5024. return Error(Loc, "invalid shufflevector operands");
  5025. Inst = new ShuffleVectorInst(Op0, Op1, Op2);
  5026. return false;
  5027. }
  5028. /// ParsePHI
  5029. /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
  5030. int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
  5031. Type *Ty = nullptr; LocTy TypeLoc;
  5032. Value *Op0, *Op1;
  5033. if (ParseType(Ty, TypeLoc) ||
  5034. ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  5035. ParseValue(Ty, Op0, PFS) ||
  5036. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5037. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  5038. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  5039. return true;
  5040. bool AteExtraComma = false;
  5041. SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
  5042. while (true) {
  5043. PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
  5044. if (!EatIfPresent(lltok::comma))
  5045. break;
  5046. if (Lex.getKind() == lltok::MetadataVar) {
  5047. AteExtraComma = true;
  5048. break;
  5049. }
  5050. if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  5051. ParseValue(Ty, Op0, PFS) ||
  5052. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  5053. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  5054. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  5055. return true;
  5056. }
  5057. if (!Ty->isFirstClassType())
  5058. return Error(TypeLoc, "phi node must have first class type");
  5059. PHINode *PN = PHINode::Create(Ty, PHIVals.size());
  5060. for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
  5061. PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
  5062. Inst = PN;
  5063. return AteExtraComma ? InstExtraComma : InstNormal;
  5064. }
  5065. /// ParseLandingPad
  5066. /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
  5067. /// Clause
  5068. /// ::= 'catch' TypeAndValue
  5069. /// ::= 'filter'
  5070. /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
  5071. bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
  5072. Type *Ty = nullptr; LocTy TyLoc;
  5073. if (ParseType(Ty, TyLoc))
  5074. return true;
  5075. std::unique_ptr<LandingPadInst> LP(LandingPadInst::Create(Ty, 0));
  5076. LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
  5077. while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
  5078. LandingPadInst::ClauseType CT;
  5079. if (EatIfPresent(lltok::kw_catch))
  5080. CT = LandingPadInst::Catch;
  5081. else if (EatIfPresent(lltok::kw_filter))
  5082. CT = LandingPadInst::Filter;
  5083. else
  5084. return TokError("expected 'catch' or 'filter' clause type");
  5085. Value *V;
  5086. LocTy VLoc;
  5087. if (ParseTypeAndValue(V, VLoc, PFS))
  5088. return true;
  5089. // A 'catch' type expects a non-array constant. A filter clause expects an
  5090. // array constant.
  5091. if (CT == LandingPadInst::Catch) {
  5092. if (isa<ArrayType>(V->getType()))
  5093. Error(VLoc, "'catch' clause has an invalid type");
  5094. } else {
  5095. if (!isa<ArrayType>(V->getType()))
  5096. Error(VLoc, "'filter' clause has an invalid type");
  5097. }
  5098. Constant *CV = dyn_cast<Constant>(V);
  5099. if (!CV)
  5100. return Error(VLoc, "clause argument must be a constant");
  5101. LP->addClause(CV);
  5102. }
  5103. Inst = LP.release();
  5104. return false;
  5105. }
  5106. /// ParseCall
  5107. /// ::= 'call' OptionalFastMathFlags OptionalCallingConv
  5108. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5109. /// ::= 'tail' 'call' OptionalFastMathFlags OptionalCallingConv
  5110. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5111. /// ::= 'musttail' 'call' OptionalFastMathFlags OptionalCallingConv
  5112. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5113. /// ::= 'notail' 'call' OptionalFastMathFlags OptionalCallingConv
  5114. /// OptionalAttrs Type Value ParameterList OptionalAttrs
  5115. bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
  5116. CallInst::TailCallKind TCK) {
  5117. AttrBuilder RetAttrs, FnAttrs;
  5118. std::vector<unsigned> FwdRefAttrGrps;
  5119. LocTy BuiltinLoc;
  5120. unsigned CC;
  5121. Type *RetType = nullptr;
  5122. LocTy RetTypeLoc;
  5123. ValID CalleeID;
  5124. SmallVector<ParamInfo, 16> ArgList;
  5125. SmallVector<OperandBundleDef, 2> BundleList;
  5126. LocTy CallLoc = Lex.getLoc();
  5127. if (TCK != CallInst::TCK_None &&
  5128. ParseToken(lltok::kw_call,
  5129. "expected 'tail call', 'musttail call', or 'notail call'"))
  5130. return true;
  5131. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  5132. if (ParseOptionalCallingConv(CC) || ParseOptionalReturnAttrs(RetAttrs) ||
  5133. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  5134. ParseValID(CalleeID) ||
  5135. ParseParameterList(ArgList, PFS, TCK == CallInst::TCK_MustTail,
  5136. PFS.getFunction().isVarArg()) ||
  5137. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false, BuiltinLoc) ||
  5138. ParseOptionalOperandBundles(BundleList, PFS))
  5139. return true;
  5140. if (FMF.any() && !RetType->isFPOrFPVectorTy())
  5141. return Error(CallLoc, "fast-math-flags specified for call without "
  5142. "floating-point scalar or vector return type");
  5143. // If RetType is a non-function pointer type, then this is the short syntax
  5144. // for the call, which means that RetType is just the return type. Infer the
  5145. // rest of the function argument types from the arguments that are present.
  5146. FunctionType *Ty = dyn_cast<FunctionType>(RetType);
  5147. if (!Ty) {
  5148. // Pull out the types of all of the arguments...
  5149. std::vector<Type*> ParamTypes;
  5150. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  5151. ParamTypes.push_back(ArgList[i].V->getType());
  5152. if (!FunctionType::isValidReturnType(RetType))
  5153. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  5154. Ty = FunctionType::get(RetType, ParamTypes, false);
  5155. }
  5156. CalleeID.FTy = Ty;
  5157. // Look up the callee.
  5158. Value *Callee;
  5159. if (ConvertValIDToValue(PointerType::getUnqual(Ty), CalleeID, Callee, &PFS))
  5160. return true;
  5161. // Set up the Attribute for the function.
  5162. SmallVector<AttributeSet, 8> Attrs;
  5163. if (RetAttrs.hasAttributes())
  5164. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  5165. AttributeSet::ReturnIndex,
  5166. RetAttrs));
  5167. SmallVector<Value*, 8> Args;
  5168. // Loop through FunctionType's arguments and ensure they are specified
  5169. // correctly. Also, gather any parameter attributes.
  5170. FunctionType::param_iterator I = Ty->param_begin();
  5171. FunctionType::param_iterator E = Ty->param_end();
  5172. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  5173. Type *ExpectedTy = nullptr;
  5174. if (I != E) {
  5175. ExpectedTy = *I++;
  5176. } else if (!Ty->isVarArg()) {
  5177. return Error(ArgList[i].Loc, "too many arguments specified");
  5178. }
  5179. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  5180. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  5181. getTypeString(ExpectedTy) + "'");
  5182. Args.push_back(ArgList[i].V);
  5183. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  5184. AttrBuilder B(ArgList[i].Attrs, i + 1);
  5185. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  5186. }
  5187. }
  5188. if (I != E)
  5189. return Error(CallLoc, "not enough parameters specified for call");
  5190. if (FnAttrs.hasAttributes()) {
  5191. if (FnAttrs.hasAlignmentAttr())
  5192. return Error(CallLoc, "call instructions may not have an alignment");
  5193. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  5194. AttributeSet::FunctionIndex,
  5195. FnAttrs));
  5196. }
  5197. // Finish off the Attribute and check them
  5198. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  5199. CallInst *CI = CallInst::Create(Ty, Callee, Args, BundleList);
  5200. CI->setTailCallKind(TCK);
  5201. CI->setCallingConv(CC);
  5202. if (FMF.any())
  5203. CI->setFastMathFlags(FMF);
  5204. CI->setAttributes(PAL);
  5205. ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
  5206. Inst = CI;
  5207. return false;
  5208. }
  5209. //===----------------------------------------------------------------------===//
  5210. // Memory Instructions.
  5211. //===----------------------------------------------------------------------===//
  5212. /// ParseAlloc
  5213. /// ::= 'alloca' 'inalloca'? 'swifterror'? Type (',' TypeAndValue)?
  5214. /// (',' 'align' i32)?
  5215. int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
  5216. Value *Size = nullptr;
  5217. LocTy SizeLoc, TyLoc;
  5218. unsigned Alignment = 0;
  5219. Type *Ty = nullptr;
  5220. bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
  5221. bool IsSwiftError = EatIfPresent(lltok::kw_swifterror);
  5222. if (ParseType(Ty, TyLoc)) return true;
  5223. if (Ty->isFunctionTy() || !PointerType::isValidElementType(Ty))
  5224. return Error(TyLoc, "invalid type for alloca");
  5225. bool AteExtraComma = false;
  5226. if (EatIfPresent(lltok::comma)) {
  5227. if (Lex.getKind() == lltok::kw_align) {
  5228. if (ParseOptionalAlignment(Alignment)) return true;
  5229. } else if (Lex.getKind() == lltok::MetadataVar) {
  5230. AteExtraComma = true;
  5231. } else {
  5232. if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
  5233. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  5234. return true;
  5235. }
  5236. }
  5237. if (Size && !Size->getType()->isIntegerTy())
  5238. return Error(SizeLoc, "element count must have integer type");
  5239. AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
  5240. AI->setUsedWithInAlloca(IsInAlloca);
  5241. AI->setSwiftError(IsSwiftError);
  5242. Inst = AI;
  5243. return AteExtraComma ? InstExtraComma : InstNormal;
  5244. }
  5245. /// ParseLoad
  5246. /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
  5247. /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
  5248. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  5249. int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
  5250. Value *Val; LocTy Loc;
  5251. unsigned Alignment = 0;
  5252. bool AteExtraComma = false;
  5253. bool isAtomic = false;
  5254. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5255. SynchronizationScope Scope = CrossThread;
  5256. if (Lex.getKind() == lltok::kw_atomic) {
  5257. isAtomic = true;
  5258. Lex.Lex();
  5259. }
  5260. bool isVolatile = false;
  5261. if (Lex.getKind() == lltok::kw_volatile) {
  5262. isVolatile = true;
  5263. Lex.Lex();
  5264. }
  5265. Type *Ty;
  5266. LocTy ExplicitTypeLoc = Lex.getLoc();
  5267. if (ParseType(Ty) ||
  5268. ParseToken(lltok::comma, "expected comma after load's type") ||
  5269. ParseTypeAndValue(Val, Loc, PFS) ||
  5270. ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
  5271. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  5272. return true;
  5273. if (!Val->getType()->isPointerTy() || !Ty->isFirstClassType())
  5274. return Error(Loc, "load operand must be a pointer to a first class type");
  5275. if (isAtomic && !Alignment)
  5276. return Error(Loc, "atomic load must have explicit non-zero alignment");
  5277. if (Ordering == AtomicOrdering::Release ||
  5278. Ordering == AtomicOrdering::AcquireRelease)
  5279. return Error(Loc, "atomic load cannot use Release ordering");
  5280. if (Ty != cast<PointerType>(Val->getType())->getElementType())
  5281. return Error(ExplicitTypeLoc,
  5282. "explicit pointee type doesn't match operand's pointee type");
  5283. Inst = new LoadInst(Ty, Val, "", isVolatile, Alignment, Ordering, Scope);
  5284. return AteExtraComma ? InstExtraComma : InstNormal;
  5285. }
  5286. /// ParseStore
  5287. /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
  5288. /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
  5289. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  5290. int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
  5291. Value *Val, *Ptr; LocTy Loc, PtrLoc;
  5292. unsigned Alignment = 0;
  5293. bool AteExtraComma = false;
  5294. bool isAtomic = false;
  5295. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5296. SynchronizationScope Scope = CrossThread;
  5297. if (Lex.getKind() == lltok::kw_atomic) {
  5298. isAtomic = true;
  5299. Lex.Lex();
  5300. }
  5301. bool isVolatile = false;
  5302. if (Lex.getKind() == lltok::kw_volatile) {
  5303. isVolatile = true;
  5304. Lex.Lex();
  5305. }
  5306. if (ParseTypeAndValue(Val, Loc, PFS) ||
  5307. ParseToken(lltok::comma, "expected ',' after store operand") ||
  5308. ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5309. ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
  5310. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  5311. return true;
  5312. if (!Ptr->getType()->isPointerTy())
  5313. return Error(PtrLoc, "store operand must be a pointer");
  5314. if (!Val->getType()->isFirstClassType())
  5315. return Error(Loc, "store operand must be a first class value");
  5316. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  5317. return Error(Loc, "stored value and pointer type do not match");
  5318. if (isAtomic && !Alignment)
  5319. return Error(Loc, "atomic store must have explicit non-zero alignment");
  5320. if (Ordering == AtomicOrdering::Acquire ||
  5321. Ordering == AtomicOrdering::AcquireRelease)
  5322. return Error(Loc, "atomic store cannot use Acquire ordering");
  5323. Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
  5324. return AteExtraComma ? InstExtraComma : InstNormal;
  5325. }
  5326. /// ParseCmpXchg
  5327. /// ::= 'cmpxchg' 'weak'? 'volatile'? TypeAndValue ',' TypeAndValue ','
  5328. /// TypeAndValue 'singlethread'? AtomicOrdering AtomicOrdering
  5329. int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
  5330. Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
  5331. bool AteExtraComma = false;
  5332. AtomicOrdering SuccessOrdering = AtomicOrdering::NotAtomic;
  5333. AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic;
  5334. SynchronizationScope Scope = CrossThread;
  5335. bool isVolatile = false;
  5336. bool isWeak = false;
  5337. if (EatIfPresent(lltok::kw_weak))
  5338. isWeak = true;
  5339. if (EatIfPresent(lltok::kw_volatile))
  5340. isVolatile = true;
  5341. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5342. ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
  5343. ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
  5344. ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
  5345. ParseTypeAndValue(New, NewLoc, PFS) ||
  5346. ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
  5347. ParseOrdering(FailureOrdering))
  5348. return true;
  5349. if (SuccessOrdering == AtomicOrdering::Unordered ||
  5350. FailureOrdering == AtomicOrdering::Unordered)
  5351. return TokError("cmpxchg cannot be unordered");
  5352. if (isStrongerThan(FailureOrdering, SuccessOrdering))
  5353. return TokError("cmpxchg failure argument shall be no stronger than the "
  5354. "success argument");
  5355. if (FailureOrdering == AtomicOrdering::Release ||
  5356. FailureOrdering == AtomicOrdering::AcquireRelease)
  5357. return TokError(
  5358. "cmpxchg failure ordering cannot include release semantics");
  5359. if (!Ptr->getType()->isPointerTy())
  5360. return Error(PtrLoc, "cmpxchg operand must be a pointer");
  5361. if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
  5362. return Error(CmpLoc, "compare value and pointer type do not match");
  5363. if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
  5364. return Error(NewLoc, "new value and pointer type do not match");
  5365. if (!New->getType()->isFirstClassType())
  5366. return Error(NewLoc, "cmpxchg operand must be a first class value");
  5367. AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(
  5368. Ptr, Cmp, New, SuccessOrdering, FailureOrdering, Scope);
  5369. CXI->setVolatile(isVolatile);
  5370. CXI->setWeak(isWeak);
  5371. Inst = CXI;
  5372. return AteExtraComma ? InstExtraComma : InstNormal;
  5373. }
  5374. /// ParseAtomicRMW
  5375. /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
  5376. /// 'singlethread'? AtomicOrdering
  5377. int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
  5378. Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
  5379. bool AteExtraComma = false;
  5380. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5381. SynchronizationScope Scope = CrossThread;
  5382. bool isVolatile = false;
  5383. AtomicRMWInst::BinOp Operation;
  5384. if (EatIfPresent(lltok::kw_volatile))
  5385. isVolatile = true;
  5386. switch (Lex.getKind()) {
  5387. default: return TokError("expected binary operation in atomicrmw");
  5388. case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
  5389. case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
  5390. case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
  5391. case lltok::kw_and: Operation = AtomicRMWInst::And; break;
  5392. case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
  5393. case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
  5394. case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
  5395. case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
  5396. case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
  5397. case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
  5398. case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
  5399. }
  5400. Lex.Lex(); // Eat the operation.
  5401. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  5402. ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
  5403. ParseTypeAndValue(Val, ValLoc, PFS) ||
  5404. ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
  5405. return true;
  5406. if (Ordering == AtomicOrdering::Unordered)
  5407. return TokError("atomicrmw cannot be unordered");
  5408. if (!Ptr->getType()->isPointerTy())
  5409. return Error(PtrLoc, "atomicrmw operand must be a pointer");
  5410. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  5411. return Error(ValLoc, "atomicrmw value and pointer type do not match");
  5412. if (!Val->getType()->isIntegerTy())
  5413. return Error(ValLoc, "atomicrmw operand must be an integer");
  5414. unsigned Size = Val->getType()->getPrimitiveSizeInBits();
  5415. if (Size < 8 || (Size & (Size - 1)))
  5416. return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
  5417. " integer");
  5418. AtomicRMWInst *RMWI =
  5419. new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
  5420. RMWI->setVolatile(isVolatile);
  5421. Inst = RMWI;
  5422. return AteExtraComma ? InstExtraComma : InstNormal;
  5423. }
  5424. /// ParseFence
  5425. /// ::= 'fence' 'singlethread'? AtomicOrdering
  5426. int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
  5427. AtomicOrdering Ordering = AtomicOrdering::NotAtomic;
  5428. SynchronizationScope Scope = CrossThread;
  5429. if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
  5430. return true;
  5431. if (Ordering == AtomicOrdering::Unordered)
  5432. return TokError("fence cannot be unordered");
  5433. if (Ordering == AtomicOrdering::Monotonic)
  5434. return TokError("fence cannot be monotonic");
  5435. Inst = new FenceInst(Context, Ordering, Scope);
  5436. return InstNormal;
  5437. }
  5438. /// ParseGetElementPtr
  5439. /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
  5440. int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
  5441. Value *Ptr = nullptr;
  5442. Value *Val = nullptr;
  5443. LocTy Loc, EltLoc;
  5444. bool InBounds = EatIfPresent(lltok::kw_inbounds);
  5445. Type *Ty = nullptr;
  5446. LocTy ExplicitTypeLoc = Lex.getLoc();
  5447. if (ParseType(Ty) ||
  5448. ParseToken(lltok::comma, "expected comma after getelementptr's type") ||
  5449. ParseTypeAndValue(Ptr, Loc, PFS))
  5450. return true;
  5451. Type *BaseType = Ptr->getType();
  5452. PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
  5453. if (!BasePointerType)
  5454. return Error(Loc, "base of getelementptr must be a pointer");
  5455. if (Ty != BasePointerType->getElementType())
  5456. return Error(ExplicitTypeLoc,
  5457. "explicit pointee type doesn't match operand's pointee type");
  5458. SmallVector<Value*, 16> Indices;
  5459. bool AteExtraComma = false;
  5460. // GEP returns a vector of pointers if at least one of parameters is a vector.
  5461. // All vector parameters should have the same vector width.
  5462. unsigned GEPWidth = BaseType->isVectorTy() ?
  5463. BaseType->getVectorNumElements() : 0;
  5464. while (EatIfPresent(lltok::comma)) {
  5465. if (Lex.getKind() == lltok::MetadataVar) {
  5466. AteExtraComma = true;
  5467. break;
  5468. }
  5469. if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
  5470. if (!Val->getType()->getScalarType()->isIntegerTy())
  5471. return Error(EltLoc, "getelementptr index must be an integer");
  5472. if (Val->getType()->isVectorTy()) {
  5473. unsigned ValNumEl = Val->getType()->getVectorNumElements();
  5474. if (GEPWidth && GEPWidth != ValNumEl)
  5475. return Error(EltLoc,
  5476. "getelementptr vector index has a wrong number of elements");
  5477. GEPWidth = ValNumEl;
  5478. }
  5479. Indices.push_back(Val);
  5480. }
  5481. SmallPtrSet<Type*, 4> Visited;
  5482. if (!Indices.empty() && !Ty->isSized(&Visited))
  5483. return Error(Loc, "base element of getelementptr must be sized");
  5484. if (!GetElementPtrInst::getIndexedType(Ty, Indices))
  5485. return Error(Loc, "invalid getelementptr indices");
  5486. Inst = GetElementPtrInst::Create(Ty, Ptr, Indices);
  5487. if (InBounds)
  5488. cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
  5489. return AteExtraComma ? InstExtraComma : InstNormal;
  5490. }
  5491. /// ParseExtractValue
  5492. /// ::= 'extractvalue' TypeAndValue (',' uint32)+
  5493. int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
  5494. Value *Val; LocTy Loc;
  5495. SmallVector<unsigned, 4> Indices;
  5496. bool AteExtraComma;
  5497. if (ParseTypeAndValue(Val, Loc, PFS) ||
  5498. ParseIndexList(Indices, AteExtraComma))
  5499. return true;
  5500. if (!Val->getType()->isAggregateType())
  5501. return Error(Loc, "extractvalue operand must be aggregate type");
  5502. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  5503. return Error(Loc, "invalid indices for extractvalue");
  5504. Inst = ExtractValueInst::Create(Val, Indices);
  5505. return AteExtraComma ? InstExtraComma : InstNormal;
  5506. }
  5507. /// ParseInsertValue
  5508. /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
  5509. int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
  5510. Value *Val0, *Val1; LocTy Loc0, Loc1;
  5511. SmallVector<unsigned, 4> Indices;
  5512. bool AteExtraComma;
  5513. if (ParseTypeAndValue(Val0, Loc0, PFS) ||
  5514. ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
  5515. ParseTypeAndValue(Val1, Loc1, PFS) ||
  5516. ParseIndexList(Indices, AteExtraComma))
  5517. return true;
  5518. if (!Val0->getType()->isAggregateType())
  5519. return Error(Loc0, "insertvalue operand must be aggregate type");
  5520. Type *IndexedType = ExtractValueInst::getIndexedType(Val0->getType(), Indices);
  5521. if (!IndexedType)
  5522. return Error(Loc0, "invalid indices for insertvalue");
  5523. if (IndexedType != Val1->getType())
  5524. return Error(Loc1, "insertvalue operand and field disagree in type: '" +
  5525. getTypeString(Val1->getType()) + "' instead of '" +
  5526. getTypeString(IndexedType) + "'");
  5527. Inst = InsertValueInst::Create(Val0, Val1, Indices);
  5528. return AteExtraComma ? InstExtraComma : InstNormal;
  5529. }
  5530. //===----------------------------------------------------------------------===//
  5531. // Embedded metadata.
  5532. //===----------------------------------------------------------------------===//
  5533. /// ParseMDNodeVector
  5534. /// ::= { Element (',' Element)* }
  5535. /// Element
  5536. /// ::= 'null' | TypeAndValue
  5537. bool LLParser::ParseMDNodeVector(SmallVectorImpl<Metadata *> &Elts) {
  5538. if (ParseToken(lltok::lbrace, "expected '{' here"))
  5539. return true;
  5540. // Check for an empty list.
  5541. if (EatIfPresent(lltok::rbrace))
  5542. return false;
  5543. do {
  5544. // Null is a special case since it is typeless.
  5545. if (EatIfPresent(lltok::kw_null)) {
  5546. Elts.push_back(nullptr);
  5547. continue;
  5548. }
  5549. Metadata *MD;
  5550. if (ParseMetadata(MD, nullptr))
  5551. return true;
  5552. Elts.push_back(MD);
  5553. } while (EatIfPresent(lltok::comma));
  5554. return ParseToken(lltok::rbrace, "expected end of metadata node");
  5555. }
  5556. //===----------------------------------------------------------------------===//
  5557. // Use-list order directives.
  5558. //===----------------------------------------------------------------------===//
  5559. bool LLParser::sortUseListOrder(Value *V, ArrayRef<unsigned> Indexes,
  5560. SMLoc Loc) {
  5561. if (V->use_empty())
  5562. return Error(Loc, "value has no uses");
  5563. unsigned NumUses = 0;
  5564. SmallDenseMap<const Use *, unsigned, 16> Order;
  5565. for (const Use &U : V->uses()) {
  5566. if (++NumUses > Indexes.size())
  5567. break;
  5568. Order[&U] = Indexes[NumUses - 1];
  5569. }
  5570. if (NumUses < 2)
  5571. return Error(Loc, "value only has one use");
  5572. if (Order.size() != Indexes.size() || NumUses > Indexes.size())
  5573. return Error(Loc, "wrong number of indexes, expected " +
  5574. Twine(std::distance(V->use_begin(), V->use_end())));
  5575. V->sortUseList([&](const Use &L, const Use &R) {
  5576. return Order.lookup(&L) < Order.lookup(&R);
  5577. });
  5578. return false;
  5579. }
  5580. /// ParseUseListOrderIndexes
  5581. /// ::= '{' uint32 (',' uint32)+ '}'
  5582. bool LLParser::ParseUseListOrderIndexes(SmallVectorImpl<unsigned> &Indexes) {
  5583. SMLoc Loc = Lex.getLoc();
  5584. if (ParseToken(lltok::lbrace, "expected '{' here"))
  5585. return true;
  5586. if (Lex.getKind() == lltok::rbrace)
  5587. return Lex.Error("expected non-empty list of uselistorder indexes");
  5588. // Use Offset, Max, and IsOrdered to check consistency of indexes. The
  5589. // indexes should be distinct numbers in the range [0, size-1], and should
  5590. // not be in order.
  5591. unsigned Offset = 0;
  5592. unsigned Max = 0;
  5593. bool IsOrdered = true;
  5594. assert(Indexes.empty() && "Expected empty order vector");
  5595. do {
  5596. unsigned Index;
  5597. if (ParseUInt32(Index))
  5598. return true;
  5599. // Update consistency checks.
  5600. Offset += Index - Indexes.size();
  5601. Max = std::max(Max, Index);
  5602. IsOrdered &= Index == Indexes.size();
  5603. Indexes.push_back(Index);
  5604. } while (EatIfPresent(lltok::comma));
  5605. if (ParseToken(lltok::rbrace, "expected '}' here"))
  5606. return true;
  5607. if (Indexes.size() < 2)
  5608. return Error(Loc, "expected >= 2 uselistorder indexes");
  5609. if (Offset != 0 || Max >= Indexes.size())
  5610. return Error(Loc, "expected distinct uselistorder indexes in range [0, size)");
  5611. if (IsOrdered)
  5612. return Error(Loc, "expected uselistorder indexes to change the order");
  5613. return false;
  5614. }
  5615. /// ParseUseListOrder
  5616. /// ::= 'uselistorder' Type Value ',' UseListOrderIndexes
  5617. bool LLParser::ParseUseListOrder(PerFunctionState *PFS) {
  5618. SMLoc Loc = Lex.getLoc();
  5619. if (ParseToken(lltok::kw_uselistorder, "expected uselistorder directive"))
  5620. return true;
  5621. Value *V;
  5622. SmallVector<unsigned, 16> Indexes;
  5623. if (ParseTypeAndValue(V, PFS) ||
  5624. ParseToken(lltok::comma, "expected comma in uselistorder directive") ||
  5625. ParseUseListOrderIndexes(Indexes))
  5626. return true;
  5627. return sortUseListOrder(V, Indexes, Loc);
  5628. }
  5629. /// ParseUseListOrderBB
  5630. /// ::= 'uselistorder_bb' @foo ',' %bar ',' UseListOrderIndexes
  5631. bool LLParser::ParseUseListOrderBB() {
  5632. assert(Lex.getKind() == lltok::kw_uselistorder_bb);
  5633. SMLoc Loc = Lex.getLoc();
  5634. Lex.Lex();
  5635. ValID Fn, Label;
  5636. SmallVector<unsigned, 16> Indexes;
  5637. if (ParseValID(Fn) ||
  5638. ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  5639. ParseValID(Label) ||
  5640. ParseToken(lltok::comma, "expected comma in uselistorder_bb directive") ||
  5641. ParseUseListOrderIndexes(Indexes))
  5642. return true;
  5643. // Check the function.
  5644. GlobalValue *GV;
  5645. if (Fn.Kind == ValID::t_GlobalName)
  5646. GV = M->getNamedValue(Fn.StrVal);
  5647. else if (Fn.Kind == ValID::t_GlobalID)
  5648. GV = Fn.UIntVal < NumberedVals.size() ? NumberedVals[Fn.UIntVal] : nullptr;
  5649. else
  5650. return Error(Fn.Loc, "expected function name in uselistorder_bb");
  5651. if (!GV)
  5652. return Error(Fn.Loc, "invalid function forward reference in uselistorder_bb");
  5653. auto *F = dyn_cast<Function>(GV);
  5654. if (!F)
  5655. return Error(Fn.Loc, "expected function name in uselistorder_bb");
  5656. if (F->isDeclaration())
  5657. return Error(Fn.Loc, "invalid declaration in uselistorder_bb");
  5658. // Check the basic block.
  5659. if (Label.Kind == ValID::t_LocalID)
  5660. return Error(Label.Loc, "invalid numeric label in uselistorder_bb");
  5661. if (Label.Kind != ValID::t_LocalName)
  5662. return Error(Label.Loc, "expected basic block name in uselistorder_bb");
  5663. Value *V = F->getValueSymbolTable().lookup(Label.StrVal);
  5664. if (!V)
  5665. return Error(Label.Loc, "invalid basic block in uselistorder_bb");
  5666. if (!isa<BasicBlock>(V))
  5667. return Error(Label.Loc, "expected basic block in uselistorder_bb");
  5668. return sortUseListOrder(V, Indexes, Loc);
  5669. }