LLParser.cpp 203 KB

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