LLParser.cpp 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431
  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/IR/AutoUpgrade.h"
  16. #include "llvm/IR/CallingConv.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/InlineAsm.h"
  20. #include "llvm/IR/Instructions.h"
  21. #include "llvm/IR/LLVMContext.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/ValueSymbolTable.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. using namespace llvm;
  28. static std::string getTypeString(Type *T) {
  29. std::string Result;
  30. raw_string_ostream Tmp(Result);
  31. Tmp << *T;
  32. return Tmp.str();
  33. }
  34. /// Run: module ::= toplevelentity*
  35. bool LLParser::Run() {
  36. // Prime the lexer.
  37. Lex.Lex();
  38. return ParseTopLevelEntities() ||
  39. ValidateEndOfModule();
  40. }
  41. /// ValidateEndOfModule - Do final validity and sanity checks at the end of the
  42. /// module.
  43. bool LLParser::ValidateEndOfModule() {
  44. // Handle any instruction metadata forward references.
  45. if (!ForwardRefInstMetadata.empty()) {
  46. for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
  47. I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
  48. I != E; ++I) {
  49. Instruction *Inst = I->first;
  50. const std::vector<MDRef> &MDList = I->second;
  51. for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
  52. unsigned SlotNo = MDList[i].MDSlot;
  53. if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
  54. return Error(MDList[i].Loc, "use of undefined metadata '!" +
  55. Twine(SlotNo) + "'");
  56. Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
  57. }
  58. }
  59. ForwardRefInstMetadata.clear();
  60. }
  61. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  62. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  63. // Handle any function attribute group forward references.
  64. for (std::map<Value*, std::vector<unsigned> >::iterator
  65. I = ForwardRefAttrGroups.begin(), E = ForwardRefAttrGroups.end();
  66. I != E; ++I) {
  67. Value *V = I->first;
  68. std::vector<unsigned> &Vec = I->second;
  69. AttrBuilder B;
  70. for (std::vector<unsigned>::iterator VI = Vec.begin(), VE = Vec.end();
  71. VI != VE; ++VI)
  72. B.merge(NumberedAttrBuilders[*VI]);
  73. if (Function *Fn = dyn_cast<Function>(V)) {
  74. AttributeSet AS = Fn->getAttributes();
  75. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  76. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  77. AS.getFnAttributes());
  78. FnAttrs.merge(B);
  79. // If the alignment was parsed as an attribute, move to the alignment
  80. // field.
  81. if (FnAttrs.hasAlignmentAttr()) {
  82. Fn->setAlignment(FnAttrs.getAlignment());
  83. FnAttrs.removeAttribute(Attribute::Alignment);
  84. }
  85. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  86. AttributeSet::get(Context,
  87. AttributeSet::FunctionIndex,
  88. FnAttrs));
  89. Fn->setAttributes(AS);
  90. } else if (CallInst *CI = dyn_cast<CallInst>(V)) {
  91. AttributeSet AS = CI->getAttributes();
  92. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  93. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  94. AS.getFnAttributes());
  95. FnAttrs.merge(B);
  96. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  97. AttributeSet::get(Context,
  98. AttributeSet::FunctionIndex,
  99. FnAttrs));
  100. CI->setAttributes(AS);
  101. } else if (InvokeInst *II = dyn_cast<InvokeInst>(V)) {
  102. AttributeSet AS = II->getAttributes();
  103. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  104. AS = AS.removeAttributes(Context, AttributeSet::FunctionIndex,
  105. AS.getFnAttributes());
  106. FnAttrs.merge(B);
  107. AS = AS.addAttributes(Context, AttributeSet::FunctionIndex,
  108. AttributeSet::get(Context,
  109. AttributeSet::FunctionIndex,
  110. FnAttrs));
  111. II->setAttributes(AS);
  112. } else {
  113. llvm_unreachable("invalid object with forward attribute group reference");
  114. }
  115. }
  116. // If there are entries in ForwardRefBlockAddresses at this point, they are
  117. // references after the function was defined. Resolve those now.
  118. while (!ForwardRefBlockAddresses.empty()) {
  119. // Okay, we are referencing an already-parsed function, resolve them now.
  120. Function *TheFn = 0;
  121. const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
  122. if (Fn.Kind == ValID::t_GlobalName)
  123. TheFn = M->getFunction(Fn.StrVal);
  124. else if (Fn.UIntVal < NumberedVals.size())
  125. TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
  126. if (TheFn == 0)
  127. return Error(Fn.Loc, "unknown function referenced by blockaddress");
  128. // Resolve all these references.
  129. if (ResolveForwardRefBlockAddresses(TheFn,
  130. ForwardRefBlockAddresses.begin()->second,
  131. 0))
  132. return true;
  133. ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
  134. }
  135. for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
  136. if (NumberedTypes[i].second.isValid())
  137. return Error(NumberedTypes[i].second,
  138. "use of undefined type '%" + Twine(i) + "'");
  139. for (StringMap<std::pair<Type*, LocTy> >::iterator I =
  140. NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
  141. if (I->second.second.isValid())
  142. return Error(I->second.second,
  143. "use of undefined type named '" + I->getKey() + "'");
  144. if (!ForwardRefVals.empty())
  145. return Error(ForwardRefVals.begin()->second.second,
  146. "use of undefined value '@" + ForwardRefVals.begin()->first +
  147. "'");
  148. if (!ForwardRefValIDs.empty())
  149. return Error(ForwardRefValIDs.begin()->second.second,
  150. "use of undefined value '@" +
  151. Twine(ForwardRefValIDs.begin()->first) + "'");
  152. if (!ForwardRefMDNodes.empty())
  153. return Error(ForwardRefMDNodes.begin()->second.second,
  154. "use of undefined metadata '!" +
  155. Twine(ForwardRefMDNodes.begin()->first) + "'");
  156. // Look for intrinsic functions and CallInst that need to be upgraded
  157. for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
  158. UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
  159. UpgradeDebugInfo(*M);
  160. return false;
  161. }
  162. bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
  163. std::vector<std::pair<ValID, GlobalValue*> > &Refs,
  164. PerFunctionState *PFS) {
  165. // Loop over all the references, resolving them.
  166. for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
  167. BasicBlock *Res;
  168. if (PFS) {
  169. if (Refs[i].first.Kind == ValID::t_LocalName)
  170. Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
  171. else
  172. Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
  173. } else if (Refs[i].first.Kind == ValID::t_LocalID) {
  174. return Error(Refs[i].first.Loc,
  175. "cannot take address of numeric label after the function is defined");
  176. } else {
  177. Res = dyn_cast_or_null<BasicBlock>(
  178. TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
  179. }
  180. if (Res == 0)
  181. return Error(Refs[i].first.Loc,
  182. "referenced value is not a basic block");
  183. // Get the BlockAddress for this and update references to use it.
  184. BlockAddress *BA = BlockAddress::get(TheFn, Res);
  185. Refs[i].second->replaceAllUsesWith(BA);
  186. Refs[i].second->eraseFromParent();
  187. }
  188. return false;
  189. }
  190. //===----------------------------------------------------------------------===//
  191. // Top-Level Entities
  192. //===----------------------------------------------------------------------===//
  193. bool LLParser::ParseTopLevelEntities() {
  194. while (1) {
  195. switch (Lex.getKind()) {
  196. default: return TokError("expected top-level entity");
  197. case lltok::Eof: return false;
  198. case lltok::kw_declare: if (ParseDeclare()) return true; break;
  199. case lltok::kw_define: if (ParseDefine()) return true; break;
  200. case lltok::kw_module: if (ParseModuleAsm()) return true; break;
  201. case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
  202. case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
  203. case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
  204. case lltok::LocalVar: if (ParseNamedType()) return true; break;
  205. case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
  206. case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
  207. case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
  208. case lltok::MetadataVar:if (ParseNamedMetadata()) return true; break;
  209. // The Global variable production with no name can have many different
  210. // optional leading prefixes, the production is:
  211. // GlobalVar ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  212. // OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
  213. // ('constant'|'global') ...
  214. case lltok::kw_private: // OptionalLinkage
  215. case lltok::kw_internal: // OptionalLinkage
  216. case lltok::kw_weak: // OptionalLinkage
  217. case lltok::kw_weak_odr: // OptionalLinkage
  218. case lltok::kw_linkonce: // OptionalLinkage
  219. case lltok::kw_linkonce_odr: // OptionalLinkage
  220. case lltok::kw_appending: // OptionalLinkage
  221. case lltok::kw_common: // OptionalLinkage
  222. case lltok::kw_extern_weak: // OptionalLinkage
  223. case lltok::kw_external: { // OptionalLinkage
  224. unsigned Linkage, Visibility, DLLStorageClass;
  225. if (ParseOptionalLinkage(Linkage) ||
  226. ParseOptionalVisibility(Visibility) ||
  227. ParseOptionalDLLStorageClass(DLLStorageClass) ||
  228. ParseGlobal("", SMLoc(), Linkage, true, Visibility, DLLStorageClass))
  229. return true;
  230. break;
  231. }
  232. case lltok::kw_default: // OptionalVisibility
  233. case lltok::kw_hidden: // OptionalVisibility
  234. case lltok::kw_protected: { // OptionalVisibility
  235. unsigned Visibility, DLLStorageClass;
  236. if (ParseOptionalVisibility(Visibility) ||
  237. ParseOptionalDLLStorageClass(DLLStorageClass) ||
  238. ParseGlobal("", SMLoc(), 0, false, Visibility, DLLStorageClass))
  239. return true;
  240. break;
  241. }
  242. case lltok::kw_thread_local: // OptionalThreadLocal
  243. case lltok::kw_addrspace: // OptionalAddrSpace
  244. case lltok::kw_constant: // GlobalType
  245. case lltok::kw_global: // GlobalType
  246. if (ParseGlobal("", SMLoc(), 0, false, 0, 0)) return true;
  247. break;
  248. case lltok::kw_attributes: if (ParseUnnamedAttrGrp()) return true; break;
  249. }
  250. }
  251. }
  252. /// toplevelentity
  253. /// ::= 'module' 'asm' STRINGCONSTANT
  254. bool LLParser::ParseModuleAsm() {
  255. assert(Lex.getKind() == lltok::kw_module);
  256. Lex.Lex();
  257. std::string AsmStr;
  258. if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
  259. ParseStringConstant(AsmStr)) return true;
  260. M->appendModuleInlineAsm(AsmStr);
  261. return false;
  262. }
  263. /// toplevelentity
  264. /// ::= 'target' 'triple' '=' STRINGCONSTANT
  265. /// ::= 'target' 'datalayout' '=' STRINGCONSTANT
  266. bool LLParser::ParseTargetDefinition() {
  267. assert(Lex.getKind() == lltok::kw_target);
  268. std::string Str;
  269. switch (Lex.Lex()) {
  270. default: return TokError("unknown target property");
  271. case lltok::kw_triple:
  272. Lex.Lex();
  273. if (ParseToken(lltok::equal, "expected '=' after target triple") ||
  274. ParseStringConstant(Str))
  275. return true;
  276. M->setTargetTriple(Str);
  277. return false;
  278. case lltok::kw_datalayout:
  279. Lex.Lex();
  280. if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
  281. ParseStringConstant(Str))
  282. return true;
  283. M->setDataLayout(Str);
  284. return false;
  285. }
  286. }
  287. /// toplevelentity
  288. /// ::= 'deplibs' '=' '[' ']'
  289. /// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
  290. /// FIXME: Remove in 4.0. Currently parse, but ignore.
  291. bool LLParser::ParseDepLibs() {
  292. assert(Lex.getKind() == lltok::kw_deplibs);
  293. Lex.Lex();
  294. if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
  295. ParseToken(lltok::lsquare, "expected '=' after deplibs"))
  296. return true;
  297. if (EatIfPresent(lltok::rsquare))
  298. return false;
  299. do {
  300. std::string Str;
  301. if (ParseStringConstant(Str)) return true;
  302. } while (EatIfPresent(lltok::comma));
  303. return ParseToken(lltok::rsquare, "expected ']' at end of list");
  304. }
  305. /// ParseUnnamedType:
  306. /// ::= LocalVarID '=' 'type' type
  307. bool LLParser::ParseUnnamedType() {
  308. LocTy TypeLoc = Lex.getLoc();
  309. unsigned TypeID = Lex.getUIntVal();
  310. Lex.Lex(); // eat LocalVarID;
  311. if (ParseToken(lltok::equal, "expected '=' after name") ||
  312. ParseToken(lltok::kw_type, "expected 'type' after '='"))
  313. return true;
  314. if (TypeID >= NumberedTypes.size())
  315. NumberedTypes.resize(TypeID+1);
  316. Type *Result = 0;
  317. if (ParseStructDefinition(TypeLoc, "",
  318. NumberedTypes[TypeID], Result)) return true;
  319. if (!isa<StructType>(Result)) {
  320. std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
  321. if (Entry.first)
  322. return Error(TypeLoc, "non-struct types may not be recursive");
  323. Entry.first = Result;
  324. Entry.second = SMLoc();
  325. }
  326. return false;
  327. }
  328. /// toplevelentity
  329. /// ::= LocalVar '=' 'type' type
  330. bool LLParser::ParseNamedType() {
  331. std::string Name = Lex.getStrVal();
  332. LocTy NameLoc = Lex.getLoc();
  333. Lex.Lex(); // eat LocalVar.
  334. if (ParseToken(lltok::equal, "expected '=' after name") ||
  335. ParseToken(lltok::kw_type, "expected 'type' after name"))
  336. return true;
  337. Type *Result = 0;
  338. if (ParseStructDefinition(NameLoc, Name,
  339. NamedTypes[Name], Result)) return true;
  340. if (!isa<StructType>(Result)) {
  341. std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
  342. if (Entry.first)
  343. return Error(NameLoc, "non-struct types may not be recursive");
  344. Entry.first = Result;
  345. Entry.second = SMLoc();
  346. }
  347. return false;
  348. }
  349. /// toplevelentity
  350. /// ::= 'declare' FunctionHeader
  351. bool LLParser::ParseDeclare() {
  352. assert(Lex.getKind() == lltok::kw_declare);
  353. Lex.Lex();
  354. Function *F;
  355. return ParseFunctionHeader(F, false);
  356. }
  357. /// toplevelentity
  358. /// ::= 'define' FunctionHeader '{' ...
  359. bool LLParser::ParseDefine() {
  360. assert(Lex.getKind() == lltok::kw_define);
  361. Lex.Lex();
  362. Function *F;
  363. return ParseFunctionHeader(F, true) ||
  364. ParseFunctionBody(*F);
  365. }
  366. /// ParseGlobalType
  367. /// ::= 'constant'
  368. /// ::= 'global'
  369. bool LLParser::ParseGlobalType(bool &IsConstant) {
  370. if (Lex.getKind() == lltok::kw_constant)
  371. IsConstant = true;
  372. else if (Lex.getKind() == lltok::kw_global)
  373. IsConstant = false;
  374. else {
  375. IsConstant = false;
  376. return TokError("expected 'global' or 'constant'");
  377. }
  378. Lex.Lex();
  379. return false;
  380. }
  381. /// ParseUnnamedGlobal:
  382. /// OptionalVisibility ALIAS ...
  383. /// OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  384. /// ... -> global variable
  385. /// GlobalID '=' OptionalVisibility ALIAS ...
  386. /// GlobalID '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  387. /// ... -> global variable
  388. bool LLParser::ParseUnnamedGlobal() {
  389. unsigned VarID = NumberedVals.size();
  390. std::string Name;
  391. LocTy NameLoc = Lex.getLoc();
  392. // Handle the GlobalID form.
  393. if (Lex.getKind() == lltok::GlobalID) {
  394. if (Lex.getUIntVal() != VarID)
  395. return Error(Lex.getLoc(), "variable expected to be numbered '%" +
  396. Twine(VarID) + "'");
  397. Lex.Lex(); // eat GlobalID;
  398. if (ParseToken(lltok::equal, "expected '=' after name"))
  399. return true;
  400. }
  401. bool HasLinkage;
  402. unsigned Linkage, Visibility, DLLStorageClass;
  403. if (ParseOptionalLinkage(Linkage, HasLinkage) ||
  404. ParseOptionalVisibility(Visibility) ||
  405. ParseOptionalDLLStorageClass(DLLStorageClass))
  406. return true;
  407. if (HasLinkage || Lex.getKind() != lltok::kw_alias)
  408. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  409. DLLStorageClass);
  410. return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
  411. }
  412. /// ParseNamedGlobal:
  413. /// GlobalVar '=' OptionalVisibility ALIAS ...
  414. /// GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  415. /// ... -> global variable
  416. bool LLParser::ParseNamedGlobal() {
  417. assert(Lex.getKind() == lltok::GlobalVar);
  418. LocTy NameLoc = Lex.getLoc();
  419. std::string Name = Lex.getStrVal();
  420. Lex.Lex();
  421. bool HasLinkage;
  422. unsigned Linkage, Visibility, DLLStorageClass;
  423. if (ParseToken(lltok::equal, "expected '=' in global variable") ||
  424. ParseOptionalLinkage(Linkage, HasLinkage) ||
  425. ParseOptionalVisibility(Visibility) ||
  426. ParseOptionalDLLStorageClass(DLLStorageClass))
  427. return true;
  428. if (HasLinkage || Lex.getKind() != lltok::kw_alias)
  429. return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility,
  430. DLLStorageClass);
  431. return ParseAlias(Name, NameLoc, Visibility, DLLStorageClass);
  432. }
  433. // MDString:
  434. // ::= '!' STRINGCONSTANT
  435. bool LLParser::ParseMDString(MDString *&Result) {
  436. std::string Str;
  437. if (ParseStringConstant(Str)) return true;
  438. Result = MDString::get(Context, Str);
  439. return false;
  440. }
  441. // MDNode:
  442. // ::= '!' MDNodeNumber
  443. //
  444. /// This version of ParseMDNodeID returns the slot number and null in the case
  445. /// of a forward reference.
  446. bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
  447. // !{ ..., !42, ... }
  448. if (ParseUInt32(SlotNo)) return true;
  449. // Check existing MDNode.
  450. if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
  451. Result = NumberedMetadata[SlotNo];
  452. else
  453. Result = 0;
  454. return false;
  455. }
  456. bool LLParser::ParseMDNodeID(MDNode *&Result) {
  457. // !{ ..., !42, ... }
  458. unsigned MID = 0;
  459. if (ParseMDNodeID(Result, MID)) return true;
  460. // If not a forward reference, just return it now.
  461. if (Result) return false;
  462. // Otherwise, create MDNode forward reference.
  463. MDNode *FwdNode = MDNode::getTemporary(Context, None);
  464. ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
  465. if (NumberedMetadata.size() <= MID)
  466. NumberedMetadata.resize(MID+1);
  467. NumberedMetadata[MID] = FwdNode;
  468. Result = FwdNode;
  469. return false;
  470. }
  471. /// ParseNamedMetadata:
  472. /// !foo = !{ !1, !2 }
  473. bool LLParser::ParseNamedMetadata() {
  474. assert(Lex.getKind() == lltok::MetadataVar);
  475. std::string Name = Lex.getStrVal();
  476. Lex.Lex();
  477. if (ParseToken(lltok::equal, "expected '=' here") ||
  478. ParseToken(lltok::exclaim, "Expected '!' here") ||
  479. ParseToken(lltok::lbrace, "Expected '{' here"))
  480. return true;
  481. NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
  482. if (Lex.getKind() != lltok::rbrace)
  483. do {
  484. if (ParseToken(lltok::exclaim, "Expected '!' here"))
  485. return true;
  486. MDNode *N = 0;
  487. if (ParseMDNodeID(N)) return true;
  488. NMD->addOperand(N);
  489. } while (EatIfPresent(lltok::comma));
  490. if (ParseToken(lltok::rbrace, "expected end of metadata node"))
  491. return true;
  492. return false;
  493. }
  494. /// ParseStandaloneMetadata:
  495. /// !42 = !{...}
  496. bool LLParser::ParseStandaloneMetadata() {
  497. assert(Lex.getKind() == lltok::exclaim);
  498. Lex.Lex();
  499. unsigned MetadataID = 0;
  500. LocTy TyLoc;
  501. Type *Ty = 0;
  502. SmallVector<Value *, 16> Elts;
  503. if (ParseUInt32(MetadataID) ||
  504. ParseToken(lltok::equal, "expected '=' here") ||
  505. ParseType(Ty, TyLoc) ||
  506. ParseToken(lltok::exclaim, "Expected '!' here") ||
  507. ParseToken(lltok::lbrace, "Expected '{' here") ||
  508. ParseMDNodeVector(Elts, NULL) ||
  509. ParseToken(lltok::rbrace, "expected end of metadata node"))
  510. return true;
  511. MDNode *Init = MDNode::get(Context, Elts);
  512. // See if this was forward referenced, if so, handle it.
  513. std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
  514. FI = ForwardRefMDNodes.find(MetadataID);
  515. if (FI != ForwardRefMDNodes.end()) {
  516. MDNode *Temp = FI->second.first;
  517. Temp->replaceAllUsesWith(Init);
  518. MDNode::deleteTemporary(Temp);
  519. ForwardRefMDNodes.erase(FI);
  520. assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
  521. } else {
  522. if (MetadataID >= NumberedMetadata.size())
  523. NumberedMetadata.resize(MetadataID+1);
  524. if (NumberedMetadata[MetadataID] != 0)
  525. return TokError("Metadata id is already used");
  526. NumberedMetadata[MetadataID] = Init;
  527. }
  528. return false;
  529. }
  530. /// ParseAlias:
  531. /// ::= GlobalVar '=' OptionalVisibility OptionalDLLStorageClass 'alias'
  532. /// OptionalLinkage Aliasee
  533. /// Aliasee
  534. /// ::= TypeAndValue
  535. /// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
  536. /// ::= 'getelementptr' 'inbounds'? '(' ... ')'
  537. ///
  538. /// Everything through DLL storage class has already been parsed.
  539. ///
  540. bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
  541. unsigned Visibility, unsigned DLLStorageClass) {
  542. assert(Lex.getKind() == lltok::kw_alias);
  543. Lex.Lex();
  544. LocTy LinkageLoc = Lex.getLoc();
  545. unsigned L;
  546. if (ParseOptionalLinkage(L))
  547. return true;
  548. GlobalValue::LinkageTypes Linkage = (GlobalValue::LinkageTypes) L;
  549. if(!GlobalAlias::isValidLinkage(Linkage))
  550. return Error(LinkageLoc, "invalid linkage type for alias");
  551. Constant *Aliasee;
  552. LocTy AliaseeLoc = Lex.getLoc();
  553. if (Lex.getKind() != lltok::kw_bitcast &&
  554. Lex.getKind() != lltok::kw_getelementptr) {
  555. if (ParseGlobalTypeAndValue(Aliasee)) return true;
  556. } else {
  557. // The bitcast dest type is not present, it is implied by the dest type.
  558. ValID ID;
  559. if (ParseValID(ID)) return true;
  560. if (ID.Kind != ValID::t_Constant)
  561. return Error(AliaseeLoc, "invalid aliasee");
  562. Aliasee = ID.ConstantVal;
  563. }
  564. if (!Aliasee->getType()->isPointerTy())
  565. return Error(AliaseeLoc, "alias must have pointer type");
  566. // Okay, create the alias but do not insert it into the module yet.
  567. GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
  568. (GlobalValue::LinkageTypes)Linkage, Name,
  569. Aliasee);
  570. GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  571. GA->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  572. // See if this value already exists in the symbol table. If so, it is either
  573. // a redefinition or a definition of a forward reference.
  574. if (GlobalValue *Val = M->getNamedValue(Name)) {
  575. // See if this was a redefinition. If so, there is no entry in
  576. // ForwardRefVals.
  577. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
  578. I = ForwardRefVals.find(Name);
  579. if (I == ForwardRefVals.end())
  580. return Error(NameLoc, "redefinition of global named '@" + Name + "'");
  581. // Otherwise, this was a definition of forward ref. Verify that types
  582. // agree.
  583. if (Val->getType() != GA->getType())
  584. return Error(NameLoc,
  585. "forward reference and definition of alias have different types");
  586. // If they agree, just RAUW the old value with the alias and remove the
  587. // forward ref info.
  588. Val->replaceAllUsesWith(GA);
  589. Val->eraseFromParent();
  590. ForwardRefVals.erase(I);
  591. }
  592. // Insert into the module, we know its name won't collide now.
  593. M->getAliasList().push_back(GA);
  594. assert(GA->getName() == Name && "Should not be a name conflict!");
  595. return false;
  596. }
  597. /// ParseGlobal
  598. /// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  599. /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
  600. /// OptionalExternallyInitialized GlobalType Type Const
  601. /// ::= OptionalLinkage OptionalVisibility OptionalDLLStorageClass
  602. /// OptionalThreadLocal OptionalAddrSpace OptionalUnNammedAddr
  603. /// OptionalExternallyInitialized GlobalType Type Const
  604. ///
  605. /// Everything up to and including OptionalDLLStorageClass has been parsed
  606. /// already.
  607. ///
  608. bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
  609. unsigned Linkage, bool HasLinkage,
  610. unsigned Visibility, unsigned DLLStorageClass) {
  611. unsigned AddrSpace;
  612. bool IsConstant, UnnamedAddr, IsExternallyInitialized;
  613. GlobalVariable::ThreadLocalMode TLM;
  614. LocTy UnnamedAddrLoc;
  615. LocTy IsExternallyInitializedLoc;
  616. LocTy TyLoc;
  617. Type *Ty = 0;
  618. if (ParseOptionalThreadLocal(TLM) ||
  619. ParseOptionalAddrSpace(AddrSpace) ||
  620. ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
  621. &UnnamedAddrLoc) ||
  622. ParseOptionalToken(lltok::kw_externally_initialized,
  623. IsExternallyInitialized,
  624. &IsExternallyInitializedLoc) ||
  625. ParseGlobalType(IsConstant) ||
  626. ParseType(Ty, TyLoc))
  627. return true;
  628. // If the linkage is specified and is external, then no initializer is
  629. // present.
  630. Constant *Init = 0;
  631. if (!HasLinkage || (Linkage != GlobalValue::ExternalWeakLinkage &&
  632. Linkage != GlobalValue::ExternalLinkage)) {
  633. if (ParseGlobalValue(Ty, Init))
  634. return true;
  635. }
  636. if (Ty->isFunctionTy() || Ty->isLabelTy())
  637. return Error(TyLoc, "invalid type for global variable");
  638. GlobalVariable *GV = 0;
  639. // See if the global was forward referenced, if so, use the global.
  640. if (!Name.empty()) {
  641. if (GlobalValue *GVal = M->getNamedValue(Name)) {
  642. if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
  643. return Error(NameLoc, "redefinition of global '@" + Name + "'");
  644. GV = cast<GlobalVariable>(GVal);
  645. }
  646. } else {
  647. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
  648. I = ForwardRefValIDs.find(NumberedVals.size());
  649. if (I != ForwardRefValIDs.end()) {
  650. GV = cast<GlobalVariable>(I->second.first);
  651. ForwardRefValIDs.erase(I);
  652. }
  653. }
  654. if (GV == 0) {
  655. GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
  656. Name, 0, GlobalVariable::NotThreadLocal,
  657. AddrSpace);
  658. } else {
  659. if (GV->getType()->getElementType() != Ty)
  660. return Error(TyLoc,
  661. "forward reference and definition of global have different types");
  662. // Move the forward-reference to the correct spot in the module.
  663. M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
  664. }
  665. if (Name.empty())
  666. NumberedVals.push_back(GV);
  667. // Set the parsed properties on the global.
  668. if (Init)
  669. GV->setInitializer(Init);
  670. GV->setConstant(IsConstant);
  671. GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
  672. GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  673. GV->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  674. GV->setExternallyInitialized(IsExternallyInitialized);
  675. GV->setThreadLocalMode(TLM);
  676. GV->setUnnamedAddr(UnnamedAddr);
  677. // Parse attributes on the global.
  678. while (Lex.getKind() == lltok::comma) {
  679. Lex.Lex();
  680. if (Lex.getKind() == lltok::kw_section) {
  681. Lex.Lex();
  682. GV->setSection(Lex.getStrVal());
  683. if (ParseToken(lltok::StringConstant, "expected global section string"))
  684. return true;
  685. } else if (Lex.getKind() == lltok::kw_align) {
  686. unsigned Alignment;
  687. if (ParseOptionalAlignment(Alignment)) return true;
  688. GV->setAlignment(Alignment);
  689. } else {
  690. TokError("unknown global variable property!");
  691. }
  692. }
  693. return false;
  694. }
  695. /// ParseUnnamedAttrGrp
  696. /// ::= 'attributes' AttrGrpID '=' '{' AttrValPair+ '}'
  697. bool LLParser::ParseUnnamedAttrGrp() {
  698. assert(Lex.getKind() == lltok::kw_attributes);
  699. LocTy AttrGrpLoc = Lex.getLoc();
  700. Lex.Lex();
  701. assert(Lex.getKind() == lltok::AttrGrpID);
  702. unsigned VarID = Lex.getUIntVal();
  703. std::vector<unsigned> unused;
  704. LocTy BuiltinLoc;
  705. Lex.Lex();
  706. if (ParseToken(lltok::equal, "expected '=' here") ||
  707. ParseToken(lltok::lbrace, "expected '{' here") ||
  708. ParseFnAttributeValuePairs(NumberedAttrBuilders[VarID], unused, true,
  709. BuiltinLoc) ||
  710. ParseToken(lltok::rbrace, "expected end of attribute group"))
  711. return true;
  712. if (!NumberedAttrBuilders[VarID].hasAttributes())
  713. return Error(AttrGrpLoc, "attribute group has no attributes");
  714. return false;
  715. }
  716. /// ParseFnAttributeValuePairs
  717. /// ::= <attr> | <attr> '=' <value>
  718. bool LLParser::ParseFnAttributeValuePairs(AttrBuilder &B,
  719. std::vector<unsigned> &FwdRefAttrGrps,
  720. bool inAttrGrp, LocTy &BuiltinLoc) {
  721. bool HaveError = false;
  722. B.clear();
  723. while (true) {
  724. lltok::Kind Token = Lex.getKind();
  725. if (Token == lltok::kw_builtin)
  726. BuiltinLoc = Lex.getLoc();
  727. switch (Token) {
  728. default:
  729. if (!inAttrGrp) return HaveError;
  730. return Error(Lex.getLoc(), "unterminated attribute group");
  731. case lltok::rbrace:
  732. // Finished.
  733. return false;
  734. case lltok::AttrGrpID: {
  735. // Allow a function to reference an attribute group:
  736. //
  737. // define void @foo() #1 { ... }
  738. if (inAttrGrp)
  739. HaveError |=
  740. Error(Lex.getLoc(),
  741. "cannot have an attribute group reference in an attribute group");
  742. unsigned AttrGrpNum = Lex.getUIntVal();
  743. if (inAttrGrp) break;
  744. // Save the reference to the attribute group. We'll fill it in later.
  745. FwdRefAttrGrps.push_back(AttrGrpNum);
  746. break;
  747. }
  748. // Target-dependent attributes:
  749. case lltok::StringConstant: {
  750. std::string Attr = Lex.getStrVal();
  751. Lex.Lex();
  752. std::string Val;
  753. if (EatIfPresent(lltok::equal) &&
  754. ParseStringConstant(Val))
  755. return true;
  756. B.addAttribute(Attr, Val);
  757. continue;
  758. }
  759. // Target-independent attributes:
  760. case lltok::kw_align: {
  761. // As a hack, we allow function alignment to be initially parsed as an
  762. // attribute on a function declaration/definition or added to an attribute
  763. // group and later moved to the alignment field.
  764. unsigned Alignment;
  765. if (inAttrGrp) {
  766. Lex.Lex();
  767. if (ParseToken(lltok::equal, "expected '=' here") ||
  768. ParseUInt32(Alignment))
  769. return true;
  770. } else {
  771. if (ParseOptionalAlignment(Alignment))
  772. return true;
  773. }
  774. B.addAlignmentAttr(Alignment);
  775. continue;
  776. }
  777. case lltok::kw_alignstack: {
  778. unsigned Alignment;
  779. if (inAttrGrp) {
  780. Lex.Lex();
  781. if (ParseToken(lltok::equal, "expected '=' here") ||
  782. ParseUInt32(Alignment))
  783. return true;
  784. } else {
  785. if (ParseOptionalStackAlignment(Alignment))
  786. return true;
  787. }
  788. B.addStackAlignmentAttr(Alignment);
  789. continue;
  790. }
  791. case lltok::kw_alwaysinline: B.addAttribute(Attribute::AlwaysInline); break;
  792. case lltok::kw_builtin: B.addAttribute(Attribute::Builtin); break;
  793. case lltok::kw_cold: B.addAttribute(Attribute::Cold); break;
  794. case lltok::kw_inlinehint: B.addAttribute(Attribute::InlineHint); break;
  795. case lltok::kw_minsize: B.addAttribute(Attribute::MinSize); break;
  796. case lltok::kw_naked: B.addAttribute(Attribute::Naked); break;
  797. case lltok::kw_nobuiltin: B.addAttribute(Attribute::NoBuiltin); break;
  798. case lltok::kw_noduplicate: B.addAttribute(Attribute::NoDuplicate); break;
  799. case lltok::kw_noimplicitfloat: B.addAttribute(Attribute::NoImplicitFloat); break;
  800. case lltok::kw_noinline: B.addAttribute(Attribute::NoInline); break;
  801. case lltok::kw_nonlazybind: B.addAttribute(Attribute::NonLazyBind); break;
  802. case lltok::kw_noredzone: B.addAttribute(Attribute::NoRedZone); break;
  803. case lltok::kw_noreturn: B.addAttribute(Attribute::NoReturn); break;
  804. case lltok::kw_nounwind: B.addAttribute(Attribute::NoUnwind); break;
  805. case lltok::kw_optnone: B.addAttribute(Attribute::OptimizeNone); break;
  806. case lltok::kw_optsize: B.addAttribute(Attribute::OptimizeForSize); break;
  807. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  808. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  809. case lltok::kw_returns_twice: B.addAttribute(Attribute::ReturnsTwice); break;
  810. case lltok::kw_ssp: B.addAttribute(Attribute::StackProtect); break;
  811. case lltok::kw_sspreq: B.addAttribute(Attribute::StackProtectReq); break;
  812. case lltok::kw_sspstrong: B.addAttribute(Attribute::StackProtectStrong); break;
  813. case lltok::kw_sanitize_address: B.addAttribute(Attribute::SanitizeAddress); break;
  814. case lltok::kw_sanitize_thread: B.addAttribute(Attribute::SanitizeThread); break;
  815. case lltok::kw_sanitize_memory: B.addAttribute(Attribute::SanitizeMemory); break;
  816. case lltok::kw_uwtable: B.addAttribute(Attribute::UWTable); break;
  817. // Error handling.
  818. case lltok::kw_inreg:
  819. case lltok::kw_signext:
  820. case lltok::kw_zeroext:
  821. HaveError |=
  822. Error(Lex.getLoc(),
  823. "invalid use of attribute on a function");
  824. break;
  825. case lltok::kw_byval:
  826. case lltok::kw_inalloca:
  827. case lltok::kw_nest:
  828. case lltok::kw_noalias:
  829. case lltok::kw_nocapture:
  830. case lltok::kw_returned:
  831. case lltok::kw_sret:
  832. HaveError |=
  833. Error(Lex.getLoc(),
  834. "invalid use of parameter-only attribute on a function");
  835. break;
  836. }
  837. Lex.Lex();
  838. }
  839. }
  840. //===----------------------------------------------------------------------===//
  841. // GlobalValue Reference/Resolution Routines.
  842. //===----------------------------------------------------------------------===//
  843. /// GetGlobalVal - Get a value with the specified name or ID, creating a
  844. /// forward reference record if needed. This can return null if the value
  845. /// exists but does not have the right type.
  846. GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
  847. LocTy Loc) {
  848. PointerType *PTy = dyn_cast<PointerType>(Ty);
  849. if (PTy == 0) {
  850. Error(Loc, "global variable reference must have pointer type");
  851. return 0;
  852. }
  853. // Look this name up in the normal function symbol table.
  854. GlobalValue *Val =
  855. cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
  856. // If this is a forward reference for the value, see if we already created a
  857. // forward ref record.
  858. if (Val == 0) {
  859. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
  860. I = ForwardRefVals.find(Name);
  861. if (I != ForwardRefVals.end())
  862. Val = I->second.first;
  863. }
  864. // If we have the value in the symbol table or fwd-ref table, return it.
  865. if (Val) {
  866. if (Val->getType() == Ty) return Val;
  867. Error(Loc, "'@" + Name + "' defined with type '" +
  868. getTypeString(Val->getType()) + "'");
  869. return 0;
  870. }
  871. // Otherwise, create a new forward reference for this value and remember it.
  872. GlobalValue *FwdVal;
  873. if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
  874. FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
  875. else
  876. FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
  877. GlobalValue::ExternalWeakLinkage, 0, Name,
  878. 0, GlobalVariable::NotThreadLocal,
  879. PTy->getAddressSpace());
  880. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  881. return FwdVal;
  882. }
  883. GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
  884. PointerType *PTy = dyn_cast<PointerType>(Ty);
  885. if (PTy == 0) {
  886. Error(Loc, "global variable reference must have pointer type");
  887. return 0;
  888. }
  889. GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
  890. // If this is a forward reference for the value, see if we already created a
  891. // forward ref record.
  892. if (Val == 0) {
  893. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
  894. I = ForwardRefValIDs.find(ID);
  895. if (I != ForwardRefValIDs.end())
  896. Val = I->second.first;
  897. }
  898. // If we have the value in the symbol table or fwd-ref table, return it.
  899. if (Val) {
  900. if (Val->getType() == Ty) return Val;
  901. Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
  902. getTypeString(Val->getType()) + "'");
  903. return 0;
  904. }
  905. // Otherwise, create a new forward reference for this value and remember it.
  906. GlobalValue *FwdVal;
  907. if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
  908. FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
  909. else
  910. FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
  911. GlobalValue::ExternalWeakLinkage, 0, "");
  912. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  913. return FwdVal;
  914. }
  915. //===----------------------------------------------------------------------===//
  916. // Helper Routines.
  917. //===----------------------------------------------------------------------===//
  918. /// ParseToken - If the current token has the specified kind, eat it and return
  919. /// success. Otherwise, emit the specified error and return failure.
  920. bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
  921. if (Lex.getKind() != T)
  922. return TokError(ErrMsg);
  923. Lex.Lex();
  924. return false;
  925. }
  926. /// ParseStringConstant
  927. /// ::= StringConstant
  928. bool LLParser::ParseStringConstant(std::string &Result) {
  929. if (Lex.getKind() != lltok::StringConstant)
  930. return TokError("expected string constant");
  931. Result = Lex.getStrVal();
  932. Lex.Lex();
  933. return false;
  934. }
  935. /// ParseUInt32
  936. /// ::= uint32
  937. bool LLParser::ParseUInt32(unsigned &Val) {
  938. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
  939. return TokError("expected integer");
  940. uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
  941. if (Val64 != unsigned(Val64))
  942. return TokError("expected 32-bit integer (too large)");
  943. Val = Val64;
  944. Lex.Lex();
  945. return false;
  946. }
  947. /// ParseTLSModel
  948. /// := 'localdynamic'
  949. /// := 'initialexec'
  950. /// := 'localexec'
  951. bool LLParser::ParseTLSModel(GlobalVariable::ThreadLocalMode &TLM) {
  952. switch (Lex.getKind()) {
  953. default:
  954. return TokError("expected localdynamic, initialexec or localexec");
  955. case lltok::kw_localdynamic:
  956. TLM = GlobalVariable::LocalDynamicTLSModel;
  957. break;
  958. case lltok::kw_initialexec:
  959. TLM = GlobalVariable::InitialExecTLSModel;
  960. break;
  961. case lltok::kw_localexec:
  962. TLM = GlobalVariable::LocalExecTLSModel;
  963. break;
  964. }
  965. Lex.Lex();
  966. return false;
  967. }
  968. /// ParseOptionalThreadLocal
  969. /// := /*empty*/
  970. /// := 'thread_local'
  971. /// := 'thread_local' '(' tlsmodel ')'
  972. bool LLParser::ParseOptionalThreadLocal(GlobalVariable::ThreadLocalMode &TLM) {
  973. TLM = GlobalVariable::NotThreadLocal;
  974. if (!EatIfPresent(lltok::kw_thread_local))
  975. return false;
  976. TLM = GlobalVariable::GeneralDynamicTLSModel;
  977. if (Lex.getKind() == lltok::lparen) {
  978. Lex.Lex();
  979. return ParseTLSModel(TLM) ||
  980. ParseToken(lltok::rparen, "expected ')' after thread local model");
  981. }
  982. return false;
  983. }
  984. /// ParseOptionalAddrSpace
  985. /// := /*empty*/
  986. /// := 'addrspace' '(' uint32 ')'
  987. bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
  988. AddrSpace = 0;
  989. if (!EatIfPresent(lltok::kw_addrspace))
  990. return false;
  991. return ParseToken(lltok::lparen, "expected '(' in address space") ||
  992. ParseUInt32(AddrSpace) ||
  993. ParseToken(lltok::rparen, "expected ')' in address space");
  994. }
  995. /// ParseOptionalParamAttrs - Parse a potentially empty list of parameter attributes.
  996. bool LLParser::ParseOptionalParamAttrs(AttrBuilder &B) {
  997. bool HaveError = false;
  998. B.clear();
  999. while (1) {
  1000. lltok::Kind Token = Lex.getKind();
  1001. switch (Token) {
  1002. default: // End of attributes.
  1003. return HaveError;
  1004. case lltok::kw_align: {
  1005. unsigned Alignment;
  1006. if (ParseOptionalAlignment(Alignment))
  1007. return true;
  1008. B.addAlignmentAttr(Alignment);
  1009. continue;
  1010. }
  1011. case lltok::kw_byval: B.addAttribute(Attribute::ByVal); break;
  1012. case lltok::kw_inalloca: B.addAttribute(Attribute::InAlloca); break;
  1013. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1014. case lltok::kw_nest: B.addAttribute(Attribute::Nest); break;
  1015. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1016. case lltok::kw_nocapture: B.addAttribute(Attribute::NoCapture); break;
  1017. case lltok::kw_readnone: B.addAttribute(Attribute::ReadNone); break;
  1018. case lltok::kw_readonly: B.addAttribute(Attribute::ReadOnly); break;
  1019. case lltok::kw_returned: B.addAttribute(Attribute::Returned); break;
  1020. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1021. case lltok::kw_sret: B.addAttribute(Attribute::StructRet); break;
  1022. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1023. case lltok::kw_alignstack:
  1024. case lltok::kw_alwaysinline:
  1025. case lltok::kw_builtin:
  1026. case lltok::kw_inlinehint:
  1027. case lltok::kw_minsize:
  1028. case lltok::kw_naked:
  1029. case lltok::kw_nobuiltin:
  1030. case lltok::kw_noduplicate:
  1031. case lltok::kw_noimplicitfloat:
  1032. case lltok::kw_noinline:
  1033. case lltok::kw_nonlazybind:
  1034. case lltok::kw_noredzone:
  1035. case lltok::kw_noreturn:
  1036. case lltok::kw_nounwind:
  1037. case lltok::kw_optnone:
  1038. case lltok::kw_optsize:
  1039. case lltok::kw_returns_twice:
  1040. case lltok::kw_sanitize_address:
  1041. case lltok::kw_sanitize_memory:
  1042. case lltok::kw_sanitize_thread:
  1043. case lltok::kw_ssp:
  1044. case lltok::kw_sspreq:
  1045. case lltok::kw_sspstrong:
  1046. case lltok::kw_uwtable:
  1047. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1048. break;
  1049. }
  1050. Lex.Lex();
  1051. }
  1052. }
  1053. /// ParseOptionalReturnAttrs - Parse a potentially empty list of return attributes.
  1054. bool LLParser::ParseOptionalReturnAttrs(AttrBuilder &B) {
  1055. bool HaveError = false;
  1056. B.clear();
  1057. while (1) {
  1058. lltok::Kind Token = Lex.getKind();
  1059. switch (Token) {
  1060. default: // End of attributes.
  1061. return HaveError;
  1062. case lltok::kw_inreg: B.addAttribute(Attribute::InReg); break;
  1063. case lltok::kw_noalias: B.addAttribute(Attribute::NoAlias); break;
  1064. case lltok::kw_signext: B.addAttribute(Attribute::SExt); break;
  1065. case lltok::kw_zeroext: B.addAttribute(Attribute::ZExt); break;
  1066. // Error handling.
  1067. case lltok::kw_align:
  1068. case lltok::kw_byval:
  1069. case lltok::kw_inalloca:
  1070. case lltok::kw_nest:
  1071. case lltok::kw_nocapture:
  1072. case lltok::kw_returned:
  1073. case lltok::kw_sret:
  1074. HaveError |= Error(Lex.getLoc(), "invalid use of parameter-only attribute");
  1075. break;
  1076. case lltok::kw_alignstack:
  1077. case lltok::kw_alwaysinline:
  1078. case lltok::kw_builtin:
  1079. case lltok::kw_cold:
  1080. case lltok::kw_inlinehint:
  1081. case lltok::kw_minsize:
  1082. case lltok::kw_naked:
  1083. case lltok::kw_nobuiltin:
  1084. case lltok::kw_noduplicate:
  1085. case lltok::kw_noimplicitfloat:
  1086. case lltok::kw_noinline:
  1087. case lltok::kw_nonlazybind:
  1088. case lltok::kw_noredzone:
  1089. case lltok::kw_noreturn:
  1090. case lltok::kw_nounwind:
  1091. case lltok::kw_optnone:
  1092. case lltok::kw_optsize:
  1093. case lltok::kw_returns_twice:
  1094. case lltok::kw_sanitize_address:
  1095. case lltok::kw_sanitize_memory:
  1096. case lltok::kw_sanitize_thread:
  1097. case lltok::kw_ssp:
  1098. case lltok::kw_sspreq:
  1099. case lltok::kw_sspstrong:
  1100. case lltok::kw_uwtable:
  1101. HaveError |= Error(Lex.getLoc(), "invalid use of function-only attribute");
  1102. break;
  1103. case lltok::kw_readnone:
  1104. case lltok::kw_readonly:
  1105. HaveError |= Error(Lex.getLoc(), "invalid use of attribute on return type");
  1106. }
  1107. Lex.Lex();
  1108. }
  1109. }
  1110. /// ParseOptionalLinkage
  1111. /// ::= /*empty*/
  1112. /// ::= 'private'
  1113. /// ::= 'internal'
  1114. /// ::= 'weak'
  1115. /// ::= 'weak_odr'
  1116. /// ::= 'linkonce'
  1117. /// ::= 'linkonce_odr'
  1118. /// ::= 'available_externally'
  1119. /// ::= 'appending'
  1120. /// ::= 'common'
  1121. /// ::= 'extern_weak'
  1122. /// ::= 'external'
  1123. bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
  1124. HasLinkage = false;
  1125. switch (Lex.getKind()) {
  1126. default: Res=GlobalValue::ExternalLinkage; return false;
  1127. case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
  1128. case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
  1129. case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
  1130. case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
  1131. case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
  1132. case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
  1133. case lltok::kw_available_externally:
  1134. Res = GlobalValue::AvailableExternallyLinkage;
  1135. break;
  1136. case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
  1137. case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
  1138. case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
  1139. case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
  1140. }
  1141. Lex.Lex();
  1142. HasLinkage = true;
  1143. return false;
  1144. }
  1145. /// ParseOptionalVisibility
  1146. /// ::= /*empty*/
  1147. /// ::= 'default'
  1148. /// ::= 'hidden'
  1149. /// ::= 'protected'
  1150. ///
  1151. bool LLParser::ParseOptionalVisibility(unsigned &Res) {
  1152. switch (Lex.getKind()) {
  1153. default: Res = GlobalValue::DefaultVisibility; return false;
  1154. case lltok::kw_default: Res = GlobalValue::DefaultVisibility; break;
  1155. case lltok::kw_hidden: Res = GlobalValue::HiddenVisibility; break;
  1156. case lltok::kw_protected: Res = GlobalValue::ProtectedVisibility; break;
  1157. }
  1158. Lex.Lex();
  1159. return false;
  1160. }
  1161. /// ParseOptionalDLLStorageClass
  1162. /// ::= /*empty*/
  1163. /// ::= 'dllimport'
  1164. /// ::= 'dllexport'
  1165. ///
  1166. bool LLParser::ParseOptionalDLLStorageClass(unsigned &Res) {
  1167. switch (Lex.getKind()) {
  1168. default: Res = GlobalValue::DefaultStorageClass; return false;
  1169. case lltok::kw_dllimport: Res = GlobalValue::DLLImportStorageClass; break;
  1170. case lltok::kw_dllexport: Res = GlobalValue::DLLExportStorageClass; break;
  1171. }
  1172. Lex.Lex();
  1173. return false;
  1174. }
  1175. /// ParseOptionalCallingConv
  1176. /// ::= /*empty*/
  1177. /// ::= 'ccc'
  1178. /// ::= 'fastcc'
  1179. /// ::= 'kw_intel_ocl_bicc'
  1180. /// ::= 'coldcc'
  1181. /// ::= 'x86_stdcallcc'
  1182. /// ::= 'x86_fastcallcc'
  1183. /// ::= 'x86_thiscallcc'
  1184. /// ::= 'x86_cdeclmethodcc'
  1185. /// ::= 'arm_apcscc'
  1186. /// ::= 'arm_aapcscc'
  1187. /// ::= 'arm_aapcs_vfpcc'
  1188. /// ::= 'msp430_intrcc'
  1189. /// ::= 'ptx_kernel'
  1190. /// ::= 'ptx_device'
  1191. /// ::= 'spir_func'
  1192. /// ::= 'spir_kernel'
  1193. /// ::= 'x86_64_sysvcc'
  1194. /// ::= 'x86_64_win64cc'
  1195. /// ::= 'webkit_jscc'
  1196. /// ::= 'anyregcc'
  1197. /// ::= 'preserve_mostcc'
  1198. /// ::= 'preserve_allcc'
  1199. /// ::= 'cc' UINT
  1200. ///
  1201. bool LLParser::ParseOptionalCallingConv(CallingConv::ID &CC) {
  1202. switch (Lex.getKind()) {
  1203. default: CC = CallingConv::C; return false;
  1204. case lltok::kw_ccc: CC = CallingConv::C; break;
  1205. case lltok::kw_fastcc: CC = CallingConv::Fast; break;
  1206. case lltok::kw_coldcc: CC = CallingConv::Cold; break;
  1207. case lltok::kw_x86_stdcallcc: CC = CallingConv::X86_StdCall; break;
  1208. case lltok::kw_x86_fastcallcc: CC = CallingConv::X86_FastCall; break;
  1209. case lltok::kw_x86_thiscallcc: CC = CallingConv::X86_ThisCall; break;
  1210. case lltok::kw_x86_cdeclmethodcc:CC = CallingConv::X86_CDeclMethod; break;
  1211. case lltok::kw_arm_apcscc: CC = CallingConv::ARM_APCS; break;
  1212. case lltok::kw_arm_aapcscc: CC = CallingConv::ARM_AAPCS; break;
  1213. case lltok::kw_arm_aapcs_vfpcc:CC = CallingConv::ARM_AAPCS_VFP; break;
  1214. case lltok::kw_msp430_intrcc: CC = CallingConv::MSP430_INTR; break;
  1215. case lltok::kw_ptx_kernel: CC = CallingConv::PTX_Kernel; break;
  1216. case lltok::kw_ptx_device: CC = CallingConv::PTX_Device; break;
  1217. case lltok::kw_spir_kernel: CC = CallingConv::SPIR_KERNEL; break;
  1218. case lltok::kw_spir_func: CC = CallingConv::SPIR_FUNC; break;
  1219. case lltok::kw_intel_ocl_bicc: CC = CallingConv::Intel_OCL_BI; break;
  1220. case lltok::kw_x86_64_sysvcc: CC = CallingConv::X86_64_SysV; break;
  1221. case lltok::kw_x86_64_win64cc: CC = CallingConv::X86_64_Win64; break;
  1222. case lltok::kw_webkit_jscc: CC = CallingConv::WebKit_JS; break;
  1223. case lltok::kw_anyregcc: CC = CallingConv::AnyReg; break;
  1224. case lltok::kw_preserve_mostcc:CC = CallingConv::PreserveMost; break;
  1225. case lltok::kw_preserve_allcc: CC = CallingConv::PreserveAll; break;
  1226. case lltok::kw_cc: {
  1227. unsigned ArbitraryCC;
  1228. Lex.Lex();
  1229. if (ParseUInt32(ArbitraryCC))
  1230. return true;
  1231. CC = static_cast<CallingConv::ID>(ArbitraryCC);
  1232. return false;
  1233. }
  1234. }
  1235. Lex.Lex();
  1236. return false;
  1237. }
  1238. /// ParseInstructionMetadata
  1239. /// ::= !dbg !42 (',' !dbg !57)*
  1240. bool LLParser::ParseInstructionMetadata(Instruction *Inst,
  1241. PerFunctionState *PFS) {
  1242. do {
  1243. if (Lex.getKind() != lltok::MetadataVar)
  1244. return TokError("expected metadata after comma");
  1245. std::string Name = Lex.getStrVal();
  1246. unsigned MDK = M->getMDKindID(Name);
  1247. Lex.Lex();
  1248. MDNode *Node;
  1249. SMLoc Loc = Lex.getLoc();
  1250. if (ParseToken(lltok::exclaim, "expected '!' here"))
  1251. return true;
  1252. // This code is similar to that of ParseMetadataValue, however it needs to
  1253. // have special-case code for a forward reference; see the comments on
  1254. // ForwardRefInstMetadata for details. Also, MDStrings are not supported
  1255. // at the top level here.
  1256. if (Lex.getKind() == lltok::lbrace) {
  1257. ValID ID;
  1258. if (ParseMetadataListValue(ID, PFS))
  1259. return true;
  1260. assert(ID.Kind == ValID::t_MDNode);
  1261. Inst->setMetadata(MDK, ID.MDNodeVal);
  1262. } else {
  1263. unsigned NodeID = 0;
  1264. if (ParseMDNodeID(Node, NodeID))
  1265. return true;
  1266. if (Node) {
  1267. // If we got the node, add it to the instruction.
  1268. Inst->setMetadata(MDK, Node);
  1269. } else {
  1270. MDRef R = { Loc, MDK, NodeID };
  1271. // Otherwise, remember that this should be resolved later.
  1272. ForwardRefInstMetadata[Inst].push_back(R);
  1273. }
  1274. }
  1275. if (MDK == LLVMContext::MD_tbaa)
  1276. InstsWithTBAATag.push_back(Inst);
  1277. // If this is the end of the list, we're done.
  1278. } while (EatIfPresent(lltok::comma));
  1279. return false;
  1280. }
  1281. /// ParseOptionalAlignment
  1282. /// ::= /* empty */
  1283. /// ::= 'align' 4
  1284. bool LLParser::ParseOptionalAlignment(unsigned &Alignment) {
  1285. Alignment = 0;
  1286. if (!EatIfPresent(lltok::kw_align))
  1287. return false;
  1288. LocTy AlignLoc = Lex.getLoc();
  1289. if (ParseUInt32(Alignment)) return true;
  1290. if (!isPowerOf2_32(Alignment))
  1291. return Error(AlignLoc, "alignment is not a power of two");
  1292. if (Alignment > Value::MaximumAlignment)
  1293. return Error(AlignLoc, "huge alignments are not supported yet");
  1294. return false;
  1295. }
  1296. /// ParseOptionalCommaAlign
  1297. /// ::=
  1298. /// ::= ',' align 4
  1299. ///
  1300. /// This returns with AteExtraComma set to true if it ate an excess comma at the
  1301. /// end.
  1302. bool LLParser::ParseOptionalCommaAlign(unsigned &Alignment,
  1303. bool &AteExtraComma) {
  1304. AteExtraComma = false;
  1305. while (EatIfPresent(lltok::comma)) {
  1306. // Metadata at the end is an early exit.
  1307. if (Lex.getKind() == lltok::MetadataVar) {
  1308. AteExtraComma = true;
  1309. return false;
  1310. }
  1311. if (Lex.getKind() != lltok::kw_align)
  1312. return Error(Lex.getLoc(), "expected metadata or 'align'");
  1313. if (ParseOptionalAlignment(Alignment)) return true;
  1314. }
  1315. return false;
  1316. }
  1317. /// ParseScopeAndOrdering
  1318. /// if isAtomic: ::= 'singlethread'? AtomicOrdering
  1319. /// else: ::=
  1320. ///
  1321. /// This sets Scope and Ordering to the parsed values.
  1322. bool LLParser::ParseScopeAndOrdering(bool isAtomic, SynchronizationScope &Scope,
  1323. AtomicOrdering &Ordering) {
  1324. if (!isAtomic)
  1325. return false;
  1326. Scope = CrossThread;
  1327. if (EatIfPresent(lltok::kw_singlethread))
  1328. Scope = SingleThread;
  1329. return ParseOrdering(Ordering);
  1330. }
  1331. /// ParseOrdering
  1332. /// ::= AtomicOrdering
  1333. ///
  1334. /// This sets Ordering to the parsed value.
  1335. bool LLParser::ParseOrdering(AtomicOrdering &Ordering) {
  1336. switch (Lex.getKind()) {
  1337. default: return TokError("Expected ordering on atomic instruction");
  1338. case lltok::kw_unordered: Ordering = Unordered; break;
  1339. case lltok::kw_monotonic: Ordering = Monotonic; break;
  1340. case lltok::kw_acquire: Ordering = Acquire; break;
  1341. case lltok::kw_release: Ordering = Release; break;
  1342. case lltok::kw_acq_rel: Ordering = AcquireRelease; break;
  1343. case lltok::kw_seq_cst: Ordering = SequentiallyConsistent; break;
  1344. }
  1345. Lex.Lex();
  1346. return false;
  1347. }
  1348. /// ParseOptionalStackAlignment
  1349. /// ::= /* empty */
  1350. /// ::= 'alignstack' '(' 4 ')'
  1351. bool LLParser::ParseOptionalStackAlignment(unsigned &Alignment) {
  1352. Alignment = 0;
  1353. if (!EatIfPresent(lltok::kw_alignstack))
  1354. return false;
  1355. LocTy ParenLoc = Lex.getLoc();
  1356. if (!EatIfPresent(lltok::lparen))
  1357. return Error(ParenLoc, "expected '('");
  1358. LocTy AlignLoc = Lex.getLoc();
  1359. if (ParseUInt32(Alignment)) return true;
  1360. ParenLoc = Lex.getLoc();
  1361. if (!EatIfPresent(lltok::rparen))
  1362. return Error(ParenLoc, "expected ')'");
  1363. if (!isPowerOf2_32(Alignment))
  1364. return Error(AlignLoc, "stack alignment is not a power of two");
  1365. return false;
  1366. }
  1367. /// ParseIndexList - This parses the index list for an insert/extractvalue
  1368. /// instruction. This sets AteExtraComma in the case where we eat an extra
  1369. /// comma at the end of the line and find that it is followed by metadata.
  1370. /// Clients that don't allow metadata can call the version of this function that
  1371. /// only takes one argument.
  1372. ///
  1373. /// ParseIndexList
  1374. /// ::= (',' uint32)+
  1375. ///
  1376. bool LLParser::ParseIndexList(SmallVectorImpl<unsigned> &Indices,
  1377. bool &AteExtraComma) {
  1378. AteExtraComma = false;
  1379. if (Lex.getKind() != lltok::comma)
  1380. return TokError("expected ',' as start of index list");
  1381. while (EatIfPresent(lltok::comma)) {
  1382. if (Lex.getKind() == lltok::MetadataVar) {
  1383. AteExtraComma = true;
  1384. return false;
  1385. }
  1386. unsigned Idx = 0;
  1387. if (ParseUInt32(Idx)) return true;
  1388. Indices.push_back(Idx);
  1389. }
  1390. return false;
  1391. }
  1392. //===----------------------------------------------------------------------===//
  1393. // Type Parsing.
  1394. //===----------------------------------------------------------------------===//
  1395. /// ParseType - Parse a type.
  1396. bool LLParser::ParseType(Type *&Result, bool AllowVoid) {
  1397. SMLoc TypeLoc = Lex.getLoc();
  1398. switch (Lex.getKind()) {
  1399. default:
  1400. return TokError("expected type");
  1401. case lltok::Type:
  1402. // Type ::= 'float' | 'void' (etc)
  1403. Result = Lex.getTyVal();
  1404. Lex.Lex();
  1405. break;
  1406. case lltok::lbrace:
  1407. // Type ::= StructType
  1408. if (ParseAnonStructType(Result, false))
  1409. return true;
  1410. break;
  1411. case lltok::lsquare:
  1412. // Type ::= '[' ... ']'
  1413. Lex.Lex(); // eat the lsquare.
  1414. if (ParseArrayVectorType(Result, false))
  1415. return true;
  1416. break;
  1417. case lltok::less: // Either vector or packed struct.
  1418. // Type ::= '<' ... '>'
  1419. Lex.Lex();
  1420. if (Lex.getKind() == lltok::lbrace) {
  1421. if (ParseAnonStructType(Result, true) ||
  1422. ParseToken(lltok::greater, "expected '>' at end of packed struct"))
  1423. return true;
  1424. } else if (ParseArrayVectorType(Result, true))
  1425. return true;
  1426. break;
  1427. case lltok::LocalVar: {
  1428. // Type ::= %foo
  1429. std::pair<Type*, LocTy> &Entry = NamedTypes[Lex.getStrVal()];
  1430. // If the type hasn't been defined yet, create a forward definition and
  1431. // remember where that forward def'n was seen (in case it never is defined).
  1432. if (Entry.first == 0) {
  1433. Entry.first = StructType::create(Context, Lex.getStrVal());
  1434. Entry.second = Lex.getLoc();
  1435. }
  1436. Result = Entry.first;
  1437. Lex.Lex();
  1438. break;
  1439. }
  1440. case lltok::LocalVarID: {
  1441. // Type ::= %4
  1442. if (Lex.getUIntVal() >= NumberedTypes.size())
  1443. NumberedTypes.resize(Lex.getUIntVal()+1);
  1444. std::pair<Type*, LocTy> &Entry = NumberedTypes[Lex.getUIntVal()];
  1445. // If the type hasn't been defined yet, create a forward definition and
  1446. // remember where that forward def'n was seen (in case it never is defined).
  1447. if (Entry.first == 0) {
  1448. Entry.first = StructType::create(Context);
  1449. Entry.second = Lex.getLoc();
  1450. }
  1451. Result = Entry.first;
  1452. Lex.Lex();
  1453. break;
  1454. }
  1455. }
  1456. // Parse the type suffixes.
  1457. while (1) {
  1458. switch (Lex.getKind()) {
  1459. // End of type.
  1460. default:
  1461. if (!AllowVoid && Result->isVoidTy())
  1462. return Error(TypeLoc, "void type only allowed for function results");
  1463. return false;
  1464. // Type ::= Type '*'
  1465. case lltok::star:
  1466. if (Result->isLabelTy())
  1467. return TokError("basic block pointers are invalid");
  1468. if (Result->isVoidTy())
  1469. return TokError("pointers to void are invalid - use i8* instead");
  1470. if (!PointerType::isValidElementType(Result))
  1471. return TokError("pointer to this type is invalid");
  1472. Result = PointerType::getUnqual(Result);
  1473. Lex.Lex();
  1474. break;
  1475. // Type ::= Type 'addrspace' '(' uint32 ')' '*'
  1476. case lltok::kw_addrspace: {
  1477. if (Result->isLabelTy())
  1478. return TokError("basic block pointers are invalid");
  1479. if (Result->isVoidTy())
  1480. return TokError("pointers to void are invalid; use i8* instead");
  1481. if (!PointerType::isValidElementType(Result))
  1482. return TokError("pointer to this type is invalid");
  1483. unsigned AddrSpace;
  1484. if (ParseOptionalAddrSpace(AddrSpace) ||
  1485. ParseToken(lltok::star, "expected '*' in address space"))
  1486. return true;
  1487. Result = PointerType::get(Result, AddrSpace);
  1488. break;
  1489. }
  1490. /// Types '(' ArgTypeListI ')' OptFuncAttrs
  1491. case lltok::lparen:
  1492. if (ParseFunctionType(Result))
  1493. return true;
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. /// ParseParameterList
  1499. /// ::= '(' ')'
  1500. /// ::= '(' Arg (',' Arg)* ')'
  1501. /// Arg
  1502. /// ::= Type OptionalAttributes Value OptionalAttributes
  1503. bool LLParser::ParseParameterList(SmallVectorImpl<ParamInfo> &ArgList,
  1504. PerFunctionState &PFS) {
  1505. if (ParseToken(lltok::lparen, "expected '(' in call"))
  1506. return true;
  1507. unsigned AttrIndex = 1;
  1508. while (Lex.getKind() != lltok::rparen) {
  1509. // If this isn't the first argument, we need a comma.
  1510. if (!ArgList.empty() &&
  1511. ParseToken(lltok::comma, "expected ',' in argument list"))
  1512. return true;
  1513. // Parse the argument.
  1514. LocTy ArgLoc;
  1515. Type *ArgTy = 0;
  1516. AttrBuilder ArgAttrs;
  1517. Value *V;
  1518. if (ParseType(ArgTy, ArgLoc))
  1519. return true;
  1520. // Otherwise, handle normal operands.
  1521. if (ParseOptionalParamAttrs(ArgAttrs) || ParseValue(ArgTy, V, PFS))
  1522. return true;
  1523. ArgList.push_back(ParamInfo(ArgLoc, V, AttributeSet::get(V->getContext(),
  1524. AttrIndex++,
  1525. ArgAttrs)));
  1526. }
  1527. Lex.Lex(); // Lex the ')'.
  1528. return false;
  1529. }
  1530. /// ParseArgumentList - Parse the argument list for a function type or function
  1531. /// prototype.
  1532. /// ::= '(' ArgTypeListI ')'
  1533. /// ArgTypeListI
  1534. /// ::= /*empty*/
  1535. /// ::= '...'
  1536. /// ::= ArgTypeList ',' '...'
  1537. /// ::= ArgType (',' ArgType)*
  1538. ///
  1539. bool LLParser::ParseArgumentList(SmallVectorImpl<ArgInfo> &ArgList,
  1540. bool &isVarArg){
  1541. isVarArg = false;
  1542. assert(Lex.getKind() == lltok::lparen);
  1543. Lex.Lex(); // eat the (.
  1544. if (Lex.getKind() == lltok::rparen) {
  1545. // empty
  1546. } else if (Lex.getKind() == lltok::dotdotdot) {
  1547. isVarArg = true;
  1548. Lex.Lex();
  1549. } else {
  1550. LocTy TypeLoc = Lex.getLoc();
  1551. Type *ArgTy = 0;
  1552. AttrBuilder Attrs;
  1553. std::string Name;
  1554. if (ParseType(ArgTy) ||
  1555. ParseOptionalParamAttrs(Attrs)) return true;
  1556. if (ArgTy->isVoidTy())
  1557. return Error(TypeLoc, "argument can not have void type");
  1558. if (Lex.getKind() == lltok::LocalVar) {
  1559. Name = Lex.getStrVal();
  1560. Lex.Lex();
  1561. }
  1562. if (!FunctionType::isValidArgumentType(ArgTy))
  1563. return Error(TypeLoc, "invalid type for function argument");
  1564. unsigned AttrIndex = 1;
  1565. ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
  1566. AttributeSet::get(ArgTy->getContext(),
  1567. AttrIndex++, Attrs), Name));
  1568. while (EatIfPresent(lltok::comma)) {
  1569. // Handle ... at end of arg list.
  1570. if (EatIfPresent(lltok::dotdotdot)) {
  1571. isVarArg = true;
  1572. break;
  1573. }
  1574. // Otherwise must be an argument type.
  1575. TypeLoc = Lex.getLoc();
  1576. if (ParseType(ArgTy) || ParseOptionalParamAttrs(Attrs)) return true;
  1577. if (ArgTy->isVoidTy())
  1578. return Error(TypeLoc, "argument can not have void type");
  1579. if (Lex.getKind() == lltok::LocalVar) {
  1580. Name = Lex.getStrVal();
  1581. Lex.Lex();
  1582. } else {
  1583. Name = "";
  1584. }
  1585. if (!ArgTy->isFirstClassType())
  1586. return Error(TypeLoc, "invalid type for function argument");
  1587. ArgList.push_back(ArgInfo(TypeLoc, ArgTy,
  1588. AttributeSet::get(ArgTy->getContext(),
  1589. AttrIndex++, Attrs),
  1590. Name));
  1591. }
  1592. }
  1593. return ParseToken(lltok::rparen, "expected ')' at end of argument list");
  1594. }
  1595. /// ParseFunctionType
  1596. /// ::= Type ArgumentList OptionalAttrs
  1597. bool LLParser::ParseFunctionType(Type *&Result) {
  1598. assert(Lex.getKind() == lltok::lparen);
  1599. if (!FunctionType::isValidReturnType(Result))
  1600. return TokError("invalid function return type");
  1601. SmallVector<ArgInfo, 8> ArgList;
  1602. bool isVarArg;
  1603. if (ParseArgumentList(ArgList, isVarArg))
  1604. return true;
  1605. // Reject names on the arguments lists.
  1606. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  1607. if (!ArgList[i].Name.empty())
  1608. return Error(ArgList[i].Loc, "argument name invalid in function type");
  1609. if (ArgList[i].Attrs.hasAttributes(i + 1))
  1610. return Error(ArgList[i].Loc,
  1611. "argument attributes invalid in function type");
  1612. }
  1613. SmallVector<Type*, 16> ArgListTy;
  1614. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  1615. ArgListTy.push_back(ArgList[i].Ty);
  1616. Result = FunctionType::get(Result, ArgListTy, isVarArg);
  1617. return false;
  1618. }
  1619. /// ParseAnonStructType - Parse an anonymous struct type, which is inlined into
  1620. /// other structs.
  1621. bool LLParser::ParseAnonStructType(Type *&Result, bool Packed) {
  1622. SmallVector<Type*, 8> Elts;
  1623. if (ParseStructBody(Elts)) return true;
  1624. Result = StructType::get(Context, Elts, Packed);
  1625. return false;
  1626. }
  1627. /// ParseStructDefinition - Parse a struct in a 'type' definition.
  1628. bool LLParser::ParseStructDefinition(SMLoc TypeLoc, StringRef Name,
  1629. std::pair<Type*, LocTy> &Entry,
  1630. Type *&ResultTy) {
  1631. // If the type was already defined, diagnose the redefinition.
  1632. if (Entry.first && !Entry.second.isValid())
  1633. return Error(TypeLoc, "redefinition of type");
  1634. // If we have opaque, just return without filling in the definition for the
  1635. // struct. This counts as a definition as far as the .ll file goes.
  1636. if (EatIfPresent(lltok::kw_opaque)) {
  1637. // This type is being defined, so clear the location to indicate this.
  1638. Entry.second = SMLoc();
  1639. // If this type number has never been uttered, create it.
  1640. if (Entry.first == 0)
  1641. Entry.first = StructType::create(Context, Name);
  1642. ResultTy = Entry.first;
  1643. return false;
  1644. }
  1645. // If the type starts with '<', then it is either a packed struct or a vector.
  1646. bool isPacked = EatIfPresent(lltok::less);
  1647. // If we don't have a struct, then we have a random type alias, which we
  1648. // accept for compatibility with old files. These types are not allowed to be
  1649. // forward referenced and not allowed to be recursive.
  1650. if (Lex.getKind() != lltok::lbrace) {
  1651. if (Entry.first)
  1652. return Error(TypeLoc, "forward references to non-struct type");
  1653. ResultTy = 0;
  1654. if (isPacked)
  1655. return ParseArrayVectorType(ResultTy, true);
  1656. return ParseType(ResultTy);
  1657. }
  1658. // This type is being defined, so clear the location to indicate this.
  1659. Entry.second = SMLoc();
  1660. // If this type number has never been uttered, create it.
  1661. if (Entry.first == 0)
  1662. Entry.first = StructType::create(Context, Name);
  1663. StructType *STy = cast<StructType>(Entry.first);
  1664. SmallVector<Type*, 8> Body;
  1665. if (ParseStructBody(Body) ||
  1666. (isPacked && ParseToken(lltok::greater, "expected '>' in packed struct")))
  1667. return true;
  1668. STy->setBody(Body, isPacked);
  1669. ResultTy = STy;
  1670. return false;
  1671. }
  1672. /// ParseStructType: Handles packed and unpacked types. </> parsed elsewhere.
  1673. /// StructType
  1674. /// ::= '{' '}'
  1675. /// ::= '{' Type (',' Type)* '}'
  1676. /// ::= '<' '{' '}' '>'
  1677. /// ::= '<' '{' Type (',' Type)* '}' '>'
  1678. bool LLParser::ParseStructBody(SmallVectorImpl<Type*> &Body) {
  1679. assert(Lex.getKind() == lltok::lbrace);
  1680. Lex.Lex(); // Consume the '{'
  1681. // Handle the empty struct.
  1682. if (EatIfPresent(lltok::rbrace))
  1683. return false;
  1684. LocTy EltTyLoc = Lex.getLoc();
  1685. Type *Ty = 0;
  1686. if (ParseType(Ty)) return true;
  1687. Body.push_back(Ty);
  1688. if (!StructType::isValidElementType(Ty))
  1689. return Error(EltTyLoc, "invalid element type for struct");
  1690. while (EatIfPresent(lltok::comma)) {
  1691. EltTyLoc = Lex.getLoc();
  1692. if (ParseType(Ty)) return true;
  1693. if (!StructType::isValidElementType(Ty))
  1694. return Error(EltTyLoc, "invalid element type for struct");
  1695. Body.push_back(Ty);
  1696. }
  1697. return ParseToken(lltok::rbrace, "expected '}' at end of struct");
  1698. }
  1699. /// ParseArrayVectorType - Parse an array or vector type, assuming the first
  1700. /// token has already been consumed.
  1701. /// Type
  1702. /// ::= '[' APSINTVAL 'x' Types ']'
  1703. /// ::= '<' APSINTVAL 'x' Types '>'
  1704. bool LLParser::ParseArrayVectorType(Type *&Result, bool isVector) {
  1705. if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned() ||
  1706. Lex.getAPSIntVal().getBitWidth() > 64)
  1707. return TokError("expected number in address space");
  1708. LocTy SizeLoc = Lex.getLoc();
  1709. uint64_t Size = Lex.getAPSIntVal().getZExtValue();
  1710. Lex.Lex();
  1711. if (ParseToken(lltok::kw_x, "expected 'x' after element count"))
  1712. return true;
  1713. LocTy TypeLoc = Lex.getLoc();
  1714. Type *EltTy = 0;
  1715. if (ParseType(EltTy)) return true;
  1716. if (ParseToken(isVector ? lltok::greater : lltok::rsquare,
  1717. "expected end of sequential type"))
  1718. return true;
  1719. if (isVector) {
  1720. if (Size == 0)
  1721. return Error(SizeLoc, "zero element vector is illegal");
  1722. if ((unsigned)Size != Size)
  1723. return Error(SizeLoc, "size too large for vector");
  1724. if (!VectorType::isValidElementType(EltTy))
  1725. return Error(TypeLoc, "invalid vector element type");
  1726. Result = VectorType::get(EltTy, unsigned(Size));
  1727. } else {
  1728. if (!ArrayType::isValidElementType(EltTy))
  1729. return Error(TypeLoc, "invalid array element type");
  1730. Result = ArrayType::get(EltTy, Size);
  1731. }
  1732. return false;
  1733. }
  1734. //===----------------------------------------------------------------------===//
  1735. // Function Semantic Analysis.
  1736. //===----------------------------------------------------------------------===//
  1737. LLParser::PerFunctionState::PerFunctionState(LLParser &p, Function &f,
  1738. int functionNumber)
  1739. : P(p), F(f), FunctionNumber(functionNumber) {
  1740. // Insert unnamed arguments into the NumberedVals list.
  1741. for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
  1742. AI != E; ++AI)
  1743. if (!AI->hasName())
  1744. NumberedVals.push_back(AI);
  1745. }
  1746. LLParser::PerFunctionState::~PerFunctionState() {
  1747. // If there were any forward referenced non-basicblock values, delete them.
  1748. for (std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1749. I = ForwardRefVals.begin(), E = ForwardRefVals.end(); I != E; ++I)
  1750. if (!isa<BasicBlock>(I->second.first)) {
  1751. I->second.first->replaceAllUsesWith(
  1752. UndefValue::get(I->second.first->getType()));
  1753. delete I->second.first;
  1754. I->second.first = 0;
  1755. }
  1756. for (std::map<unsigned, std::pair<Value*, LocTy> >::iterator
  1757. I = ForwardRefValIDs.begin(), E = ForwardRefValIDs.end(); I != E; ++I)
  1758. if (!isa<BasicBlock>(I->second.first)) {
  1759. I->second.first->replaceAllUsesWith(
  1760. UndefValue::get(I->second.first->getType()));
  1761. delete I->second.first;
  1762. I->second.first = 0;
  1763. }
  1764. }
  1765. bool LLParser::PerFunctionState::FinishFunction() {
  1766. // Check to see if someone took the address of labels in this block.
  1767. if (!P.ForwardRefBlockAddresses.empty()) {
  1768. ValID FunctionID;
  1769. if (!F.getName().empty()) {
  1770. FunctionID.Kind = ValID::t_GlobalName;
  1771. FunctionID.StrVal = F.getName();
  1772. } else {
  1773. FunctionID.Kind = ValID::t_GlobalID;
  1774. FunctionID.UIntVal = FunctionNumber;
  1775. }
  1776. std::map<ValID, std::vector<std::pair<ValID, GlobalValue*> > >::iterator
  1777. FRBAI = P.ForwardRefBlockAddresses.find(FunctionID);
  1778. if (FRBAI != P.ForwardRefBlockAddresses.end()) {
  1779. // Resolve all these references.
  1780. if (P.ResolveForwardRefBlockAddresses(&F, FRBAI->second, this))
  1781. return true;
  1782. P.ForwardRefBlockAddresses.erase(FRBAI);
  1783. }
  1784. }
  1785. if (!ForwardRefVals.empty())
  1786. return P.Error(ForwardRefVals.begin()->second.second,
  1787. "use of undefined value '%" + ForwardRefVals.begin()->first +
  1788. "'");
  1789. if (!ForwardRefValIDs.empty())
  1790. return P.Error(ForwardRefValIDs.begin()->second.second,
  1791. "use of undefined value '%" +
  1792. Twine(ForwardRefValIDs.begin()->first) + "'");
  1793. return false;
  1794. }
  1795. /// GetVal - Get a value with the specified name or ID, creating a
  1796. /// forward reference record if needed. This can return null if the value
  1797. /// exists but does not have the right type.
  1798. Value *LLParser::PerFunctionState::GetVal(const std::string &Name,
  1799. Type *Ty, LocTy Loc) {
  1800. // Look this name up in the normal function symbol table.
  1801. Value *Val = F.getValueSymbolTable().lookup(Name);
  1802. // If this is a forward reference for the value, see if we already created a
  1803. // forward ref record.
  1804. if (Val == 0) {
  1805. std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1806. I = ForwardRefVals.find(Name);
  1807. if (I != ForwardRefVals.end())
  1808. Val = I->second.first;
  1809. }
  1810. // If we have the value in the symbol table or fwd-ref table, return it.
  1811. if (Val) {
  1812. if (Val->getType() == Ty) return Val;
  1813. if (Ty->isLabelTy())
  1814. P.Error(Loc, "'%" + Name + "' is not a basic block");
  1815. else
  1816. P.Error(Loc, "'%" + Name + "' defined with type '" +
  1817. getTypeString(Val->getType()) + "'");
  1818. return 0;
  1819. }
  1820. // Don't make placeholders with invalid type.
  1821. if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
  1822. P.Error(Loc, "invalid use of a non-first-class type");
  1823. return 0;
  1824. }
  1825. // Otherwise, create a new forward reference for this value and remember it.
  1826. Value *FwdVal;
  1827. if (Ty->isLabelTy())
  1828. FwdVal = BasicBlock::Create(F.getContext(), Name, &F);
  1829. else
  1830. FwdVal = new Argument(Ty, Name);
  1831. ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
  1832. return FwdVal;
  1833. }
  1834. Value *LLParser::PerFunctionState::GetVal(unsigned ID, Type *Ty,
  1835. LocTy Loc) {
  1836. // Look this name up in the normal function symbol table.
  1837. Value *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
  1838. // If this is a forward reference for the value, see if we already created a
  1839. // forward ref record.
  1840. if (Val == 0) {
  1841. std::map<unsigned, std::pair<Value*, LocTy> >::iterator
  1842. I = ForwardRefValIDs.find(ID);
  1843. if (I != ForwardRefValIDs.end())
  1844. Val = I->second.first;
  1845. }
  1846. // If we have the value in the symbol table or fwd-ref table, return it.
  1847. if (Val) {
  1848. if (Val->getType() == Ty) return Val;
  1849. if (Ty->isLabelTy())
  1850. P.Error(Loc, "'%" + Twine(ID) + "' is not a basic block");
  1851. else
  1852. P.Error(Loc, "'%" + Twine(ID) + "' defined with type '" +
  1853. getTypeString(Val->getType()) + "'");
  1854. return 0;
  1855. }
  1856. if (!Ty->isFirstClassType() && !Ty->isLabelTy()) {
  1857. P.Error(Loc, "invalid use of a non-first-class type");
  1858. return 0;
  1859. }
  1860. // Otherwise, create a new forward reference for this value and remember it.
  1861. Value *FwdVal;
  1862. if (Ty->isLabelTy())
  1863. FwdVal = BasicBlock::Create(F.getContext(), "", &F);
  1864. else
  1865. FwdVal = new Argument(Ty);
  1866. ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
  1867. return FwdVal;
  1868. }
  1869. /// SetInstName - After an instruction is parsed and inserted into its
  1870. /// basic block, this installs its name.
  1871. bool LLParser::PerFunctionState::SetInstName(int NameID,
  1872. const std::string &NameStr,
  1873. LocTy NameLoc, Instruction *Inst) {
  1874. // If this instruction has void type, it cannot have a name or ID specified.
  1875. if (Inst->getType()->isVoidTy()) {
  1876. if (NameID != -1 || !NameStr.empty())
  1877. return P.Error(NameLoc, "instructions returning void cannot have a name");
  1878. return false;
  1879. }
  1880. // If this was a numbered instruction, verify that the instruction is the
  1881. // expected value and resolve any forward references.
  1882. if (NameStr.empty()) {
  1883. // If neither a name nor an ID was specified, just use the next ID.
  1884. if (NameID == -1)
  1885. NameID = NumberedVals.size();
  1886. if (unsigned(NameID) != NumberedVals.size())
  1887. return P.Error(NameLoc, "instruction expected to be numbered '%" +
  1888. Twine(NumberedVals.size()) + "'");
  1889. std::map<unsigned, std::pair<Value*, LocTy> >::iterator FI =
  1890. ForwardRefValIDs.find(NameID);
  1891. if (FI != ForwardRefValIDs.end()) {
  1892. if (FI->second.first->getType() != Inst->getType())
  1893. return P.Error(NameLoc, "instruction forward referenced with type '" +
  1894. getTypeString(FI->second.first->getType()) + "'");
  1895. FI->second.first->replaceAllUsesWith(Inst);
  1896. delete FI->second.first;
  1897. ForwardRefValIDs.erase(FI);
  1898. }
  1899. NumberedVals.push_back(Inst);
  1900. return false;
  1901. }
  1902. // Otherwise, the instruction had a name. Resolve forward refs and set it.
  1903. std::map<std::string, std::pair<Value*, LocTy> >::iterator
  1904. FI = ForwardRefVals.find(NameStr);
  1905. if (FI != ForwardRefVals.end()) {
  1906. if (FI->second.first->getType() != Inst->getType())
  1907. return P.Error(NameLoc, "instruction forward referenced with type '" +
  1908. getTypeString(FI->second.first->getType()) + "'");
  1909. FI->second.first->replaceAllUsesWith(Inst);
  1910. delete FI->second.first;
  1911. ForwardRefVals.erase(FI);
  1912. }
  1913. // Set the name on the instruction.
  1914. Inst->setName(NameStr);
  1915. if (Inst->getName() != NameStr)
  1916. return P.Error(NameLoc, "multiple definition of local value named '" +
  1917. NameStr + "'");
  1918. return false;
  1919. }
  1920. /// GetBB - Get a basic block with the specified name or ID, creating a
  1921. /// forward reference record if needed.
  1922. BasicBlock *LLParser::PerFunctionState::GetBB(const std::string &Name,
  1923. LocTy Loc) {
  1924. return cast_or_null<BasicBlock>(GetVal(Name,
  1925. Type::getLabelTy(F.getContext()), Loc));
  1926. }
  1927. BasicBlock *LLParser::PerFunctionState::GetBB(unsigned ID, LocTy Loc) {
  1928. return cast_or_null<BasicBlock>(GetVal(ID,
  1929. Type::getLabelTy(F.getContext()), Loc));
  1930. }
  1931. /// DefineBB - Define the specified basic block, which is either named or
  1932. /// unnamed. If there is an error, this returns null otherwise it returns
  1933. /// the block being defined.
  1934. BasicBlock *LLParser::PerFunctionState::DefineBB(const std::string &Name,
  1935. LocTy Loc) {
  1936. BasicBlock *BB;
  1937. if (Name.empty())
  1938. BB = GetBB(NumberedVals.size(), Loc);
  1939. else
  1940. BB = GetBB(Name, Loc);
  1941. if (BB == 0) return 0; // Already diagnosed error.
  1942. // Move the block to the end of the function. Forward ref'd blocks are
  1943. // inserted wherever they happen to be referenced.
  1944. F.getBasicBlockList().splice(F.end(), F.getBasicBlockList(), BB);
  1945. // Remove the block from forward ref sets.
  1946. if (Name.empty()) {
  1947. ForwardRefValIDs.erase(NumberedVals.size());
  1948. NumberedVals.push_back(BB);
  1949. } else {
  1950. // BB forward references are already in the function symbol table.
  1951. ForwardRefVals.erase(Name);
  1952. }
  1953. return BB;
  1954. }
  1955. //===----------------------------------------------------------------------===//
  1956. // Constants.
  1957. //===----------------------------------------------------------------------===//
  1958. /// ParseValID - Parse an abstract value that doesn't necessarily have a
  1959. /// type implied. For example, if we parse "4" we don't know what integer type
  1960. /// it has. The value will later be combined with its type and checked for
  1961. /// sanity. PFS is used to convert function-local operands of metadata (since
  1962. /// metadata operands are not just parsed here but also converted to values).
  1963. /// PFS can be null when we are not parsing metadata values inside a function.
  1964. bool LLParser::ParseValID(ValID &ID, PerFunctionState *PFS) {
  1965. ID.Loc = Lex.getLoc();
  1966. switch (Lex.getKind()) {
  1967. default: return TokError("expected value token");
  1968. case lltok::GlobalID: // @42
  1969. ID.UIntVal = Lex.getUIntVal();
  1970. ID.Kind = ValID::t_GlobalID;
  1971. break;
  1972. case lltok::GlobalVar: // @foo
  1973. ID.StrVal = Lex.getStrVal();
  1974. ID.Kind = ValID::t_GlobalName;
  1975. break;
  1976. case lltok::LocalVarID: // %42
  1977. ID.UIntVal = Lex.getUIntVal();
  1978. ID.Kind = ValID::t_LocalID;
  1979. break;
  1980. case lltok::LocalVar: // %foo
  1981. ID.StrVal = Lex.getStrVal();
  1982. ID.Kind = ValID::t_LocalName;
  1983. break;
  1984. case lltok::exclaim: // !42, !{...}, or !"foo"
  1985. return ParseMetadataValue(ID, PFS);
  1986. case lltok::APSInt:
  1987. ID.APSIntVal = Lex.getAPSIntVal();
  1988. ID.Kind = ValID::t_APSInt;
  1989. break;
  1990. case lltok::APFloat:
  1991. ID.APFloatVal = Lex.getAPFloatVal();
  1992. ID.Kind = ValID::t_APFloat;
  1993. break;
  1994. case lltok::kw_true:
  1995. ID.ConstantVal = ConstantInt::getTrue(Context);
  1996. ID.Kind = ValID::t_Constant;
  1997. break;
  1998. case lltok::kw_false:
  1999. ID.ConstantVal = ConstantInt::getFalse(Context);
  2000. ID.Kind = ValID::t_Constant;
  2001. break;
  2002. case lltok::kw_null: ID.Kind = ValID::t_Null; break;
  2003. case lltok::kw_undef: ID.Kind = ValID::t_Undef; break;
  2004. case lltok::kw_zeroinitializer: ID.Kind = ValID::t_Zero; break;
  2005. case lltok::lbrace: {
  2006. // ValID ::= '{' ConstVector '}'
  2007. Lex.Lex();
  2008. SmallVector<Constant*, 16> Elts;
  2009. if (ParseGlobalValueVector(Elts) ||
  2010. ParseToken(lltok::rbrace, "expected end of struct constant"))
  2011. return true;
  2012. ID.ConstantStructElts = new Constant*[Elts.size()];
  2013. ID.UIntVal = Elts.size();
  2014. memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
  2015. ID.Kind = ValID::t_ConstantStruct;
  2016. return false;
  2017. }
  2018. case lltok::less: {
  2019. // ValID ::= '<' ConstVector '>' --> Vector.
  2020. // ValID ::= '<' '{' ConstVector '}' '>' --> Packed Struct.
  2021. Lex.Lex();
  2022. bool isPackedStruct = EatIfPresent(lltok::lbrace);
  2023. SmallVector<Constant*, 16> Elts;
  2024. LocTy FirstEltLoc = Lex.getLoc();
  2025. if (ParseGlobalValueVector(Elts) ||
  2026. (isPackedStruct &&
  2027. ParseToken(lltok::rbrace, "expected end of packed struct")) ||
  2028. ParseToken(lltok::greater, "expected end of constant"))
  2029. return true;
  2030. if (isPackedStruct) {
  2031. ID.ConstantStructElts = new Constant*[Elts.size()];
  2032. memcpy(ID.ConstantStructElts, Elts.data(), Elts.size()*sizeof(Elts[0]));
  2033. ID.UIntVal = Elts.size();
  2034. ID.Kind = ValID::t_PackedConstantStruct;
  2035. return false;
  2036. }
  2037. if (Elts.empty())
  2038. return Error(ID.Loc, "constant vector must not be empty");
  2039. if (!Elts[0]->getType()->isIntegerTy() &&
  2040. !Elts[0]->getType()->isFloatingPointTy() &&
  2041. !Elts[0]->getType()->isPointerTy())
  2042. return Error(FirstEltLoc,
  2043. "vector elements must have integer, pointer or floating point type");
  2044. // Verify that all the vector elements have the same type.
  2045. for (unsigned i = 1, e = Elts.size(); i != e; ++i)
  2046. if (Elts[i]->getType() != Elts[0]->getType())
  2047. return Error(FirstEltLoc,
  2048. "vector element #" + Twine(i) +
  2049. " is not of type '" + getTypeString(Elts[0]->getType()));
  2050. ID.ConstantVal = ConstantVector::get(Elts);
  2051. ID.Kind = ValID::t_Constant;
  2052. return false;
  2053. }
  2054. case lltok::lsquare: { // Array Constant
  2055. Lex.Lex();
  2056. SmallVector<Constant*, 16> Elts;
  2057. LocTy FirstEltLoc = Lex.getLoc();
  2058. if (ParseGlobalValueVector(Elts) ||
  2059. ParseToken(lltok::rsquare, "expected end of array constant"))
  2060. return true;
  2061. // Handle empty element.
  2062. if (Elts.empty()) {
  2063. // Use undef instead of an array because it's inconvenient to determine
  2064. // the element type at this point, there being no elements to examine.
  2065. ID.Kind = ValID::t_EmptyArray;
  2066. return false;
  2067. }
  2068. if (!Elts[0]->getType()->isFirstClassType())
  2069. return Error(FirstEltLoc, "invalid array element type: " +
  2070. getTypeString(Elts[0]->getType()));
  2071. ArrayType *ATy = ArrayType::get(Elts[0]->getType(), Elts.size());
  2072. // Verify all elements are correct type!
  2073. for (unsigned i = 0, e = Elts.size(); i != e; ++i) {
  2074. if (Elts[i]->getType() != Elts[0]->getType())
  2075. return Error(FirstEltLoc,
  2076. "array element #" + Twine(i) +
  2077. " is not of type '" + getTypeString(Elts[0]->getType()));
  2078. }
  2079. ID.ConstantVal = ConstantArray::get(ATy, Elts);
  2080. ID.Kind = ValID::t_Constant;
  2081. return false;
  2082. }
  2083. case lltok::kw_c: // c "foo"
  2084. Lex.Lex();
  2085. ID.ConstantVal = ConstantDataArray::getString(Context, Lex.getStrVal(),
  2086. false);
  2087. if (ParseToken(lltok::StringConstant, "expected string")) return true;
  2088. ID.Kind = ValID::t_Constant;
  2089. return false;
  2090. case lltok::kw_asm: {
  2091. // ValID ::= 'asm' SideEffect? AlignStack? IntelDialect? STRINGCONSTANT ','
  2092. // STRINGCONSTANT
  2093. bool HasSideEffect, AlignStack, AsmDialect;
  2094. Lex.Lex();
  2095. if (ParseOptionalToken(lltok::kw_sideeffect, HasSideEffect) ||
  2096. ParseOptionalToken(lltok::kw_alignstack, AlignStack) ||
  2097. ParseOptionalToken(lltok::kw_inteldialect, AsmDialect) ||
  2098. ParseStringConstant(ID.StrVal) ||
  2099. ParseToken(lltok::comma, "expected comma in inline asm expression") ||
  2100. ParseToken(lltok::StringConstant, "expected constraint string"))
  2101. return true;
  2102. ID.StrVal2 = Lex.getStrVal();
  2103. ID.UIntVal = unsigned(HasSideEffect) | (unsigned(AlignStack)<<1) |
  2104. (unsigned(AsmDialect)<<2);
  2105. ID.Kind = ValID::t_InlineAsm;
  2106. return false;
  2107. }
  2108. case lltok::kw_blockaddress: {
  2109. // ValID ::= 'blockaddress' '(' @foo ',' %bar ')'
  2110. Lex.Lex();
  2111. ValID Fn, Label;
  2112. if (ParseToken(lltok::lparen, "expected '(' in block address expression") ||
  2113. ParseValID(Fn) ||
  2114. ParseToken(lltok::comma, "expected comma in block address expression")||
  2115. ParseValID(Label) ||
  2116. ParseToken(lltok::rparen, "expected ')' in block address expression"))
  2117. return true;
  2118. if (Fn.Kind != ValID::t_GlobalID && Fn.Kind != ValID::t_GlobalName)
  2119. return Error(Fn.Loc, "expected function name in blockaddress");
  2120. if (Label.Kind != ValID::t_LocalID && Label.Kind != ValID::t_LocalName)
  2121. return Error(Label.Loc, "expected basic block name in blockaddress");
  2122. // Make a global variable as a placeholder for this reference.
  2123. GlobalVariable *FwdRef = new GlobalVariable(*M, Type::getInt8Ty(Context),
  2124. false, GlobalValue::InternalLinkage,
  2125. 0, "");
  2126. ForwardRefBlockAddresses[Fn].push_back(std::make_pair(Label, FwdRef));
  2127. ID.ConstantVal = FwdRef;
  2128. ID.Kind = ValID::t_Constant;
  2129. return false;
  2130. }
  2131. case lltok::kw_trunc:
  2132. case lltok::kw_zext:
  2133. case lltok::kw_sext:
  2134. case lltok::kw_fptrunc:
  2135. case lltok::kw_fpext:
  2136. case lltok::kw_bitcast:
  2137. case lltok::kw_addrspacecast:
  2138. case lltok::kw_uitofp:
  2139. case lltok::kw_sitofp:
  2140. case lltok::kw_fptoui:
  2141. case lltok::kw_fptosi:
  2142. case lltok::kw_inttoptr:
  2143. case lltok::kw_ptrtoint: {
  2144. unsigned Opc = Lex.getUIntVal();
  2145. Type *DestTy = 0;
  2146. Constant *SrcVal;
  2147. Lex.Lex();
  2148. if (ParseToken(lltok::lparen, "expected '(' after constantexpr cast") ||
  2149. ParseGlobalTypeAndValue(SrcVal) ||
  2150. ParseToken(lltok::kw_to, "expected 'to' in constantexpr cast") ||
  2151. ParseType(DestTy) ||
  2152. ParseToken(lltok::rparen, "expected ')' at end of constantexpr cast"))
  2153. return true;
  2154. if (!CastInst::castIsValid((Instruction::CastOps)Opc, SrcVal, DestTy))
  2155. return Error(ID.Loc, "invalid cast opcode for cast from '" +
  2156. getTypeString(SrcVal->getType()) + "' to '" +
  2157. getTypeString(DestTy) + "'");
  2158. ID.ConstantVal = ConstantExpr::getCast((Instruction::CastOps)Opc,
  2159. SrcVal, DestTy);
  2160. ID.Kind = ValID::t_Constant;
  2161. return false;
  2162. }
  2163. case lltok::kw_extractvalue: {
  2164. Lex.Lex();
  2165. Constant *Val;
  2166. SmallVector<unsigned, 4> Indices;
  2167. if (ParseToken(lltok::lparen, "expected '(' in extractvalue constantexpr")||
  2168. ParseGlobalTypeAndValue(Val) ||
  2169. ParseIndexList(Indices) ||
  2170. ParseToken(lltok::rparen, "expected ')' in extractvalue constantexpr"))
  2171. return true;
  2172. if (!Val->getType()->isAggregateType())
  2173. return Error(ID.Loc, "extractvalue operand must be aggregate type");
  2174. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  2175. return Error(ID.Loc, "invalid indices for extractvalue");
  2176. ID.ConstantVal = ConstantExpr::getExtractValue(Val, Indices);
  2177. ID.Kind = ValID::t_Constant;
  2178. return false;
  2179. }
  2180. case lltok::kw_insertvalue: {
  2181. Lex.Lex();
  2182. Constant *Val0, *Val1;
  2183. SmallVector<unsigned, 4> Indices;
  2184. if (ParseToken(lltok::lparen, "expected '(' in insertvalue constantexpr")||
  2185. ParseGlobalTypeAndValue(Val0) ||
  2186. ParseToken(lltok::comma, "expected comma in insertvalue constantexpr")||
  2187. ParseGlobalTypeAndValue(Val1) ||
  2188. ParseIndexList(Indices) ||
  2189. ParseToken(lltok::rparen, "expected ')' in insertvalue constantexpr"))
  2190. return true;
  2191. if (!Val0->getType()->isAggregateType())
  2192. return Error(ID.Loc, "insertvalue operand must be aggregate type");
  2193. if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
  2194. return Error(ID.Loc, "invalid indices for insertvalue");
  2195. ID.ConstantVal = ConstantExpr::getInsertValue(Val0, Val1, Indices);
  2196. ID.Kind = ValID::t_Constant;
  2197. return false;
  2198. }
  2199. case lltok::kw_icmp:
  2200. case lltok::kw_fcmp: {
  2201. unsigned PredVal, Opc = Lex.getUIntVal();
  2202. Constant *Val0, *Val1;
  2203. Lex.Lex();
  2204. if (ParseCmpPredicate(PredVal, Opc) ||
  2205. ParseToken(lltok::lparen, "expected '(' in compare constantexpr") ||
  2206. ParseGlobalTypeAndValue(Val0) ||
  2207. ParseToken(lltok::comma, "expected comma in compare constantexpr") ||
  2208. ParseGlobalTypeAndValue(Val1) ||
  2209. ParseToken(lltok::rparen, "expected ')' in compare constantexpr"))
  2210. return true;
  2211. if (Val0->getType() != Val1->getType())
  2212. return Error(ID.Loc, "compare operands must have the same type");
  2213. CmpInst::Predicate Pred = (CmpInst::Predicate)PredVal;
  2214. if (Opc == Instruction::FCmp) {
  2215. if (!Val0->getType()->isFPOrFPVectorTy())
  2216. return Error(ID.Loc, "fcmp requires floating point operands");
  2217. ID.ConstantVal = ConstantExpr::getFCmp(Pred, Val0, Val1);
  2218. } else {
  2219. assert(Opc == Instruction::ICmp && "Unexpected opcode for CmpInst!");
  2220. if (!Val0->getType()->isIntOrIntVectorTy() &&
  2221. !Val0->getType()->getScalarType()->isPointerTy())
  2222. return Error(ID.Loc, "icmp requires pointer or integer operands");
  2223. ID.ConstantVal = ConstantExpr::getICmp(Pred, Val0, Val1);
  2224. }
  2225. ID.Kind = ValID::t_Constant;
  2226. return false;
  2227. }
  2228. // Binary Operators.
  2229. case lltok::kw_add:
  2230. case lltok::kw_fadd:
  2231. case lltok::kw_sub:
  2232. case lltok::kw_fsub:
  2233. case lltok::kw_mul:
  2234. case lltok::kw_fmul:
  2235. case lltok::kw_udiv:
  2236. case lltok::kw_sdiv:
  2237. case lltok::kw_fdiv:
  2238. case lltok::kw_urem:
  2239. case lltok::kw_srem:
  2240. case lltok::kw_frem:
  2241. case lltok::kw_shl:
  2242. case lltok::kw_lshr:
  2243. case lltok::kw_ashr: {
  2244. bool NUW = false;
  2245. bool NSW = false;
  2246. bool Exact = false;
  2247. unsigned Opc = Lex.getUIntVal();
  2248. Constant *Val0, *Val1;
  2249. Lex.Lex();
  2250. LocTy ModifierLoc = Lex.getLoc();
  2251. if (Opc == Instruction::Add || Opc == Instruction::Sub ||
  2252. Opc == Instruction::Mul || Opc == Instruction::Shl) {
  2253. if (EatIfPresent(lltok::kw_nuw))
  2254. NUW = true;
  2255. if (EatIfPresent(lltok::kw_nsw)) {
  2256. NSW = true;
  2257. if (EatIfPresent(lltok::kw_nuw))
  2258. NUW = true;
  2259. }
  2260. } else if (Opc == Instruction::SDiv || Opc == Instruction::UDiv ||
  2261. Opc == Instruction::LShr || Opc == Instruction::AShr) {
  2262. if (EatIfPresent(lltok::kw_exact))
  2263. Exact = true;
  2264. }
  2265. if (ParseToken(lltok::lparen, "expected '(' in binary constantexpr") ||
  2266. ParseGlobalTypeAndValue(Val0) ||
  2267. ParseToken(lltok::comma, "expected comma in binary constantexpr") ||
  2268. ParseGlobalTypeAndValue(Val1) ||
  2269. ParseToken(lltok::rparen, "expected ')' in binary constantexpr"))
  2270. return true;
  2271. if (Val0->getType() != Val1->getType())
  2272. return Error(ID.Loc, "operands of constexpr must have same type");
  2273. if (!Val0->getType()->isIntOrIntVectorTy()) {
  2274. if (NUW)
  2275. return Error(ModifierLoc, "nuw only applies to integer operations");
  2276. if (NSW)
  2277. return Error(ModifierLoc, "nsw only applies to integer operations");
  2278. }
  2279. // Check that the type is valid for the operator.
  2280. switch (Opc) {
  2281. case Instruction::Add:
  2282. case Instruction::Sub:
  2283. case Instruction::Mul:
  2284. case Instruction::UDiv:
  2285. case Instruction::SDiv:
  2286. case Instruction::URem:
  2287. case Instruction::SRem:
  2288. case Instruction::Shl:
  2289. case Instruction::AShr:
  2290. case Instruction::LShr:
  2291. if (!Val0->getType()->isIntOrIntVectorTy())
  2292. return Error(ID.Loc, "constexpr requires integer operands");
  2293. break;
  2294. case Instruction::FAdd:
  2295. case Instruction::FSub:
  2296. case Instruction::FMul:
  2297. case Instruction::FDiv:
  2298. case Instruction::FRem:
  2299. if (!Val0->getType()->isFPOrFPVectorTy())
  2300. return Error(ID.Loc, "constexpr requires fp operands");
  2301. break;
  2302. default: llvm_unreachable("Unknown binary operator!");
  2303. }
  2304. unsigned Flags = 0;
  2305. if (NUW) Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2306. if (NSW) Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2307. if (Exact) Flags |= PossiblyExactOperator::IsExact;
  2308. Constant *C = ConstantExpr::get(Opc, Val0, Val1, Flags);
  2309. ID.ConstantVal = C;
  2310. ID.Kind = ValID::t_Constant;
  2311. return false;
  2312. }
  2313. // Logical Operations
  2314. case lltok::kw_and:
  2315. case lltok::kw_or:
  2316. case lltok::kw_xor: {
  2317. unsigned Opc = Lex.getUIntVal();
  2318. Constant *Val0, *Val1;
  2319. Lex.Lex();
  2320. if (ParseToken(lltok::lparen, "expected '(' in logical constantexpr") ||
  2321. ParseGlobalTypeAndValue(Val0) ||
  2322. ParseToken(lltok::comma, "expected comma in logical constantexpr") ||
  2323. ParseGlobalTypeAndValue(Val1) ||
  2324. ParseToken(lltok::rparen, "expected ')' in logical constantexpr"))
  2325. return true;
  2326. if (Val0->getType() != Val1->getType())
  2327. return Error(ID.Loc, "operands of constexpr must have same type");
  2328. if (!Val0->getType()->isIntOrIntVectorTy())
  2329. return Error(ID.Loc,
  2330. "constexpr requires integer or integer vector operands");
  2331. ID.ConstantVal = ConstantExpr::get(Opc, Val0, Val1);
  2332. ID.Kind = ValID::t_Constant;
  2333. return false;
  2334. }
  2335. case lltok::kw_getelementptr:
  2336. case lltok::kw_shufflevector:
  2337. case lltok::kw_insertelement:
  2338. case lltok::kw_extractelement:
  2339. case lltok::kw_select: {
  2340. unsigned Opc = Lex.getUIntVal();
  2341. SmallVector<Constant*, 16> Elts;
  2342. bool InBounds = false;
  2343. Lex.Lex();
  2344. if (Opc == Instruction::GetElementPtr)
  2345. InBounds = EatIfPresent(lltok::kw_inbounds);
  2346. if (ParseToken(lltok::lparen, "expected '(' in constantexpr") ||
  2347. ParseGlobalValueVector(Elts) ||
  2348. ParseToken(lltok::rparen, "expected ')' in constantexpr"))
  2349. return true;
  2350. if (Opc == Instruction::GetElementPtr) {
  2351. if (Elts.size() == 0 ||
  2352. !Elts[0]->getType()->getScalarType()->isPointerTy())
  2353. return Error(ID.Loc, "getelementptr requires pointer operand");
  2354. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2355. if (!GetElementPtrInst::getIndexedType(Elts[0]->getType(), Indices))
  2356. return Error(ID.Loc, "invalid indices for getelementptr");
  2357. ID.ConstantVal = ConstantExpr::getGetElementPtr(Elts[0], Indices,
  2358. InBounds);
  2359. } else if (Opc == Instruction::Select) {
  2360. if (Elts.size() != 3)
  2361. return Error(ID.Loc, "expected three operands to select");
  2362. if (const char *Reason = SelectInst::areInvalidOperands(Elts[0], Elts[1],
  2363. Elts[2]))
  2364. return Error(ID.Loc, Reason);
  2365. ID.ConstantVal = ConstantExpr::getSelect(Elts[0], Elts[1], Elts[2]);
  2366. } else if (Opc == Instruction::ShuffleVector) {
  2367. if (Elts.size() != 3)
  2368. return Error(ID.Loc, "expected three operands to shufflevector");
  2369. if (!ShuffleVectorInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  2370. return Error(ID.Loc, "invalid operands to shufflevector");
  2371. ID.ConstantVal =
  2372. ConstantExpr::getShuffleVector(Elts[0], Elts[1],Elts[2]);
  2373. } else if (Opc == Instruction::ExtractElement) {
  2374. if (Elts.size() != 2)
  2375. return Error(ID.Loc, "expected two operands to extractelement");
  2376. if (!ExtractElementInst::isValidOperands(Elts[0], Elts[1]))
  2377. return Error(ID.Loc, "invalid extractelement operands");
  2378. ID.ConstantVal = ConstantExpr::getExtractElement(Elts[0], Elts[1]);
  2379. } else {
  2380. assert(Opc == Instruction::InsertElement && "Unknown opcode");
  2381. if (Elts.size() != 3)
  2382. return Error(ID.Loc, "expected three operands to insertelement");
  2383. if (!InsertElementInst::isValidOperands(Elts[0], Elts[1], Elts[2]))
  2384. return Error(ID.Loc, "invalid insertelement operands");
  2385. ID.ConstantVal =
  2386. ConstantExpr::getInsertElement(Elts[0], Elts[1],Elts[2]);
  2387. }
  2388. ID.Kind = ValID::t_Constant;
  2389. return false;
  2390. }
  2391. }
  2392. Lex.Lex();
  2393. return false;
  2394. }
  2395. /// ParseGlobalValue - Parse a global value with the specified type.
  2396. bool LLParser::ParseGlobalValue(Type *Ty, Constant *&C) {
  2397. C = 0;
  2398. ValID ID;
  2399. Value *V = NULL;
  2400. bool Parsed = ParseValID(ID) ||
  2401. ConvertValIDToValue(Ty, ID, V, NULL);
  2402. if (V && !(C = dyn_cast<Constant>(V)))
  2403. return Error(ID.Loc, "global values must be constants");
  2404. return Parsed;
  2405. }
  2406. bool LLParser::ParseGlobalTypeAndValue(Constant *&V) {
  2407. Type *Ty = 0;
  2408. return ParseType(Ty) ||
  2409. ParseGlobalValue(Ty, V);
  2410. }
  2411. /// ParseGlobalValueVector
  2412. /// ::= /*empty*/
  2413. /// ::= TypeAndValue (',' TypeAndValue)*
  2414. bool LLParser::ParseGlobalValueVector(SmallVectorImpl<Constant*> &Elts) {
  2415. // Empty list.
  2416. if (Lex.getKind() == lltok::rbrace ||
  2417. Lex.getKind() == lltok::rsquare ||
  2418. Lex.getKind() == lltok::greater ||
  2419. Lex.getKind() == lltok::rparen)
  2420. return false;
  2421. Constant *C;
  2422. if (ParseGlobalTypeAndValue(C)) return true;
  2423. Elts.push_back(C);
  2424. while (EatIfPresent(lltok::comma)) {
  2425. if (ParseGlobalTypeAndValue(C)) return true;
  2426. Elts.push_back(C);
  2427. }
  2428. return false;
  2429. }
  2430. bool LLParser::ParseMetadataListValue(ValID &ID, PerFunctionState *PFS) {
  2431. assert(Lex.getKind() == lltok::lbrace);
  2432. Lex.Lex();
  2433. SmallVector<Value*, 16> Elts;
  2434. if (ParseMDNodeVector(Elts, PFS) ||
  2435. ParseToken(lltok::rbrace, "expected end of metadata node"))
  2436. return true;
  2437. ID.MDNodeVal = MDNode::get(Context, Elts);
  2438. ID.Kind = ValID::t_MDNode;
  2439. return false;
  2440. }
  2441. /// ParseMetadataValue
  2442. /// ::= !42
  2443. /// ::= !{...}
  2444. /// ::= !"string"
  2445. bool LLParser::ParseMetadataValue(ValID &ID, PerFunctionState *PFS) {
  2446. assert(Lex.getKind() == lltok::exclaim);
  2447. Lex.Lex();
  2448. // MDNode:
  2449. // !{ ... }
  2450. if (Lex.getKind() == lltok::lbrace)
  2451. return ParseMetadataListValue(ID, PFS);
  2452. // Standalone metadata reference
  2453. // !42
  2454. if (Lex.getKind() == lltok::APSInt) {
  2455. if (ParseMDNodeID(ID.MDNodeVal)) return true;
  2456. ID.Kind = ValID::t_MDNode;
  2457. return false;
  2458. }
  2459. // MDString:
  2460. // ::= '!' STRINGCONSTANT
  2461. if (ParseMDString(ID.MDStringVal)) return true;
  2462. ID.Kind = ValID::t_MDString;
  2463. return false;
  2464. }
  2465. //===----------------------------------------------------------------------===//
  2466. // Function Parsing.
  2467. //===----------------------------------------------------------------------===//
  2468. bool LLParser::ConvertValIDToValue(Type *Ty, ValID &ID, Value *&V,
  2469. PerFunctionState *PFS) {
  2470. if (Ty->isFunctionTy())
  2471. return Error(ID.Loc, "functions are not values, refer to them as pointers");
  2472. switch (ID.Kind) {
  2473. case ValID::t_LocalID:
  2474. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  2475. V = PFS->GetVal(ID.UIntVal, Ty, ID.Loc);
  2476. return (V == 0);
  2477. case ValID::t_LocalName:
  2478. if (!PFS) return Error(ID.Loc, "invalid use of function-local name");
  2479. V = PFS->GetVal(ID.StrVal, Ty, ID.Loc);
  2480. return (V == 0);
  2481. case ValID::t_InlineAsm: {
  2482. PointerType *PTy = dyn_cast<PointerType>(Ty);
  2483. FunctionType *FTy =
  2484. PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
  2485. if (!FTy || !InlineAsm::Verify(FTy, ID.StrVal2))
  2486. return Error(ID.Loc, "invalid type for inline asm constraint string");
  2487. V = InlineAsm::get(FTy, ID.StrVal, ID.StrVal2, ID.UIntVal&1,
  2488. (ID.UIntVal>>1)&1, (InlineAsm::AsmDialect(ID.UIntVal>>2)));
  2489. return false;
  2490. }
  2491. case ValID::t_MDNode:
  2492. if (!Ty->isMetadataTy())
  2493. return Error(ID.Loc, "metadata value must have metadata type");
  2494. V = ID.MDNodeVal;
  2495. return false;
  2496. case ValID::t_MDString:
  2497. if (!Ty->isMetadataTy())
  2498. return Error(ID.Loc, "metadata value must have metadata type");
  2499. V = ID.MDStringVal;
  2500. return false;
  2501. case ValID::t_GlobalName:
  2502. V = GetGlobalVal(ID.StrVal, Ty, ID.Loc);
  2503. return V == 0;
  2504. case ValID::t_GlobalID:
  2505. V = GetGlobalVal(ID.UIntVal, Ty, ID.Loc);
  2506. return V == 0;
  2507. case ValID::t_APSInt:
  2508. if (!Ty->isIntegerTy())
  2509. return Error(ID.Loc, "integer constant must have integer type");
  2510. ID.APSIntVal = ID.APSIntVal.extOrTrunc(Ty->getPrimitiveSizeInBits());
  2511. V = ConstantInt::get(Context, ID.APSIntVal);
  2512. return false;
  2513. case ValID::t_APFloat:
  2514. if (!Ty->isFloatingPointTy() ||
  2515. !ConstantFP::isValueValidForType(Ty, ID.APFloatVal))
  2516. return Error(ID.Loc, "floating point constant invalid for type");
  2517. // The lexer has no type info, so builds all half, float, and double FP
  2518. // constants as double. Fix this here. Long double does not need this.
  2519. if (&ID.APFloatVal.getSemantics() == &APFloat::IEEEdouble) {
  2520. bool Ignored;
  2521. if (Ty->isHalfTy())
  2522. ID.APFloatVal.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven,
  2523. &Ignored);
  2524. else if (Ty->isFloatTy())
  2525. ID.APFloatVal.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
  2526. &Ignored);
  2527. }
  2528. V = ConstantFP::get(Context, ID.APFloatVal);
  2529. if (V->getType() != Ty)
  2530. return Error(ID.Loc, "floating point constant does not have type '" +
  2531. getTypeString(Ty) + "'");
  2532. return false;
  2533. case ValID::t_Null:
  2534. if (!Ty->isPointerTy())
  2535. return Error(ID.Loc, "null must be a pointer type");
  2536. V = ConstantPointerNull::get(cast<PointerType>(Ty));
  2537. return false;
  2538. case ValID::t_Undef:
  2539. // FIXME: LabelTy should not be a first-class type.
  2540. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  2541. return Error(ID.Loc, "invalid type for undef constant");
  2542. V = UndefValue::get(Ty);
  2543. return false;
  2544. case ValID::t_EmptyArray:
  2545. if (!Ty->isArrayTy() || cast<ArrayType>(Ty)->getNumElements() != 0)
  2546. return Error(ID.Loc, "invalid empty array initializer");
  2547. V = UndefValue::get(Ty);
  2548. return false;
  2549. case ValID::t_Zero:
  2550. // FIXME: LabelTy should not be a first-class type.
  2551. if (!Ty->isFirstClassType() || Ty->isLabelTy())
  2552. return Error(ID.Loc, "invalid type for null constant");
  2553. V = Constant::getNullValue(Ty);
  2554. return false;
  2555. case ValID::t_Constant:
  2556. if (ID.ConstantVal->getType() != Ty)
  2557. return Error(ID.Loc, "constant expression type mismatch");
  2558. V = ID.ConstantVal;
  2559. return false;
  2560. case ValID::t_ConstantStruct:
  2561. case ValID::t_PackedConstantStruct:
  2562. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2563. if (ST->getNumElements() != ID.UIntVal)
  2564. return Error(ID.Loc,
  2565. "initializer with struct type has wrong # elements");
  2566. if (ST->isPacked() != (ID.Kind == ValID::t_PackedConstantStruct))
  2567. return Error(ID.Loc, "packed'ness of initializer and type don't match");
  2568. // Verify that the elements are compatible with the structtype.
  2569. for (unsigned i = 0, e = ID.UIntVal; i != e; ++i)
  2570. if (ID.ConstantStructElts[i]->getType() != ST->getElementType(i))
  2571. return Error(ID.Loc, "element " + Twine(i) +
  2572. " of struct initializer doesn't match struct element type");
  2573. V = ConstantStruct::get(ST, makeArrayRef(ID.ConstantStructElts,
  2574. ID.UIntVal));
  2575. } else
  2576. return Error(ID.Loc, "constant expression type mismatch");
  2577. return false;
  2578. }
  2579. llvm_unreachable("Invalid ValID");
  2580. }
  2581. bool LLParser::ParseValue(Type *Ty, Value *&V, PerFunctionState *PFS) {
  2582. V = 0;
  2583. ValID ID;
  2584. return ParseValID(ID, PFS) ||
  2585. ConvertValIDToValue(Ty, ID, V, PFS);
  2586. }
  2587. bool LLParser::ParseTypeAndValue(Value *&V, PerFunctionState *PFS) {
  2588. Type *Ty = 0;
  2589. return ParseType(Ty) ||
  2590. ParseValue(Ty, V, PFS);
  2591. }
  2592. bool LLParser::ParseTypeAndBasicBlock(BasicBlock *&BB, LocTy &Loc,
  2593. PerFunctionState &PFS) {
  2594. Value *V;
  2595. Loc = Lex.getLoc();
  2596. if (ParseTypeAndValue(V, PFS)) return true;
  2597. if (!isa<BasicBlock>(V))
  2598. return Error(Loc, "expected a basic block");
  2599. BB = cast<BasicBlock>(V);
  2600. return false;
  2601. }
  2602. /// FunctionHeader
  2603. /// ::= OptionalLinkage OptionalVisibility OptionalCallingConv OptRetAttrs
  2604. /// OptUnnamedAddr Type GlobalName '(' ArgList ')' OptFuncAttrs OptSection
  2605. /// OptionalAlign OptGC OptionalPrefix
  2606. bool LLParser::ParseFunctionHeader(Function *&Fn, bool isDefine) {
  2607. // Parse the linkage.
  2608. LocTy LinkageLoc = Lex.getLoc();
  2609. unsigned Linkage;
  2610. unsigned Visibility;
  2611. unsigned DLLStorageClass;
  2612. AttrBuilder RetAttrs;
  2613. CallingConv::ID CC;
  2614. Type *RetType = 0;
  2615. LocTy RetTypeLoc = Lex.getLoc();
  2616. if (ParseOptionalLinkage(Linkage) ||
  2617. ParseOptionalVisibility(Visibility) ||
  2618. ParseOptionalDLLStorageClass(DLLStorageClass) ||
  2619. ParseOptionalCallingConv(CC) ||
  2620. ParseOptionalReturnAttrs(RetAttrs) ||
  2621. ParseType(RetType, RetTypeLoc, true /*void allowed*/))
  2622. return true;
  2623. // Verify that the linkage is ok.
  2624. switch ((GlobalValue::LinkageTypes)Linkage) {
  2625. case GlobalValue::ExternalLinkage:
  2626. break; // always ok.
  2627. case GlobalValue::ExternalWeakLinkage:
  2628. if (isDefine)
  2629. return Error(LinkageLoc, "invalid linkage for function definition");
  2630. break;
  2631. case GlobalValue::PrivateLinkage:
  2632. case GlobalValue::InternalLinkage:
  2633. case GlobalValue::AvailableExternallyLinkage:
  2634. case GlobalValue::LinkOnceAnyLinkage:
  2635. case GlobalValue::LinkOnceODRLinkage:
  2636. case GlobalValue::WeakAnyLinkage:
  2637. case GlobalValue::WeakODRLinkage:
  2638. if (!isDefine)
  2639. return Error(LinkageLoc, "invalid linkage for function declaration");
  2640. break;
  2641. case GlobalValue::AppendingLinkage:
  2642. case GlobalValue::CommonLinkage:
  2643. return Error(LinkageLoc, "invalid function linkage type");
  2644. }
  2645. if (!FunctionType::isValidReturnType(RetType))
  2646. return Error(RetTypeLoc, "invalid function return type");
  2647. LocTy NameLoc = Lex.getLoc();
  2648. std::string FunctionName;
  2649. if (Lex.getKind() == lltok::GlobalVar) {
  2650. FunctionName = Lex.getStrVal();
  2651. } else if (Lex.getKind() == lltok::GlobalID) { // @42 is ok.
  2652. unsigned NameID = Lex.getUIntVal();
  2653. if (NameID != NumberedVals.size())
  2654. return TokError("function expected to be numbered '%" +
  2655. Twine(NumberedVals.size()) + "'");
  2656. } else {
  2657. return TokError("expected function name");
  2658. }
  2659. Lex.Lex();
  2660. if (Lex.getKind() != lltok::lparen)
  2661. return TokError("expected '(' in function argument list");
  2662. SmallVector<ArgInfo, 8> ArgList;
  2663. bool isVarArg;
  2664. AttrBuilder FuncAttrs;
  2665. std::vector<unsigned> FwdRefAttrGrps;
  2666. LocTy BuiltinLoc;
  2667. std::string Section;
  2668. unsigned Alignment;
  2669. std::string GC;
  2670. bool UnnamedAddr;
  2671. LocTy UnnamedAddrLoc;
  2672. Constant *Prefix = 0;
  2673. if (ParseArgumentList(ArgList, isVarArg) ||
  2674. ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
  2675. &UnnamedAddrLoc) ||
  2676. ParseFnAttributeValuePairs(FuncAttrs, FwdRefAttrGrps, false,
  2677. BuiltinLoc) ||
  2678. (EatIfPresent(lltok::kw_section) &&
  2679. ParseStringConstant(Section)) ||
  2680. ParseOptionalAlignment(Alignment) ||
  2681. (EatIfPresent(lltok::kw_gc) &&
  2682. ParseStringConstant(GC)) ||
  2683. (EatIfPresent(lltok::kw_prefix) &&
  2684. ParseGlobalTypeAndValue(Prefix)))
  2685. return true;
  2686. if (FuncAttrs.contains(Attribute::Builtin))
  2687. return Error(BuiltinLoc, "'builtin' attribute not valid on function");
  2688. // If the alignment was parsed as an attribute, move to the alignment field.
  2689. if (FuncAttrs.hasAlignmentAttr()) {
  2690. Alignment = FuncAttrs.getAlignment();
  2691. FuncAttrs.removeAttribute(Attribute::Alignment);
  2692. }
  2693. // Okay, if we got here, the function is syntactically valid. Convert types
  2694. // and do semantic checks.
  2695. std::vector<Type*> ParamTypeList;
  2696. SmallVector<AttributeSet, 8> Attrs;
  2697. if (RetAttrs.hasAttributes())
  2698. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  2699. AttributeSet::ReturnIndex,
  2700. RetAttrs));
  2701. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  2702. ParamTypeList.push_back(ArgList[i].Ty);
  2703. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  2704. AttrBuilder B(ArgList[i].Attrs, i + 1);
  2705. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  2706. }
  2707. }
  2708. if (FuncAttrs.hasAttributes())
  2709. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  2710. AttributeSet::FunctionIndex,
  2711. FuncAttrs));
  2712. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  2713. if (PAL.hasAttribute(1, Attribute::StructRet) && !RetType->isVoidTy())
  2714. return Error(RetTypeLoc, "functions with 'sret' argument must return void");
  2715. FunctionType *FT =
  2716. FunctionType::get(RetType, ParamTypeList, isVarArg);
  2717. PointerType *PFT = PointerType::getUnqual(FT);
  2718. Fn = 0;
  2719. if (!FunctionName.empty()) {
  2720. // If this was a definition of a forward reference, remove the definition
  2721. // from the forward reference table and fill in the forward ref.
  2722. std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator FRVI =
  2723. ForwardRefVals.find(FunctionName);
  2724. if (FRVI != ForwardRefVals.end()) {
  2725. Fn = M->getFunction(FunctionName);
  2726. if (!Fn)
  2727. return Error(FRVI->second.second, "invalid forward reference to "
  2728. "function as global value!");
  2729. if (Fn->getType() != PFT)
  2730. return Error(FRVI->second.second, "invalid forward reference to "
  2731. "function '" + FunctionName + "' with wrong type!");
  2732. ForwardRefVals.erase(FRVI);
  2733. } else if ((Fn = M->getFunction(FunctionName))) {
  2734. // Reject redefinitions.
  2735. return Error(NameLoc, "invalid redefinition of function '" +
  2736. FunctionName + "'");
  2737. } else if (M->getNamedValue(FunctionName)) {
  2738. return Error(NameLoc, "redefinition of function '@" + FunctionName + "'");
  2739. }
  2740. } else {
  2741. // If this is a definition of a forward referenced function, make sure the
  2742. // types agree.
  2743. std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator I
  2744. = ForwardRefValIDs.find(NumberedVals.size());
  2745. if (I != ForwardRefValIDs.end()) {
  2746. Fn = cast<Function>(I->second.first);
  2747. if (Fn->getType() != PFT)
  2748. return Error(NameLoc, "type of definition and forward reference of '@" +
  2749. Twine(NumberedVals.size()) + "' disagree");
  2750. ForwardRefValIDs.erase(I);
  2751. }
  2752. }
  2753. if (Fn == 0)
  2754. Fn = Function::Create(FT, GlobalValue::ExternalLinkage, FunctionName, M);
  2755. else // Move the forward-reference to the correct spot in the module.
  2756. M->getFunctionList().splice(M->end(), M->getFunctionList(), Fn);
  2757. if (FunctionName.empty())
  2758. NumberedVals.push_back(Fn);
  2759. Fn->setLinkage((GlobalValue::LinkageTypes)Linkage);
  2760. Fn->setVisibility((GlobalValue::VisibilityTypes)Visibility);
  2761. Fn->setDLLStorageClass((GlobalValue::DLLStorageClassTypes)DLLStorageClass);
  2762. Fn->setCallingConv(CC);
  2763. Fn->setAttributes(PAL);
  2764. Fn->setUnnamedAddr(UnnamedAddr);
  2765. Fn->setAlignment(Alignment);
  2766. Fn->setSection(Section);
  2767. if (!GC.empty()) Fn->setGC(GC.c_str());
  2768. Fn->setPrefixData(Prefix);
  2769. ForwardRefAttrGroups[Fn] = FwdRefAttrGrps;
  2770. // Add all of the arguments we parsed to the function.
  2771. Function::arg_iterator ArgIt = Fn->arg_begin();
  2772. for (unsigned i = 0, e = ArgList.size(); i != e; ++i, ++ArgIt) {
  2773. // If the argument has a name, insert it into the argument symbol table.
  2774. if (ArgList[i].Name.empty()) continue;
  2775. // Set the name, if it conflicted, it will be auto-renamed.
  2776. ArgIt->setName(ArgList[i].Name);
  2777. if (ArgIt->getName() != ArgList[i].Name)
  2778. return Error(ArgList[i].Loc, "redefinition of argument '%" +
  2779. ArgList[i].Name + "'");
  2780. }
  2781. return false;
  2782. }
  2783. /// ParseFunctionBody
  2784. /// ::= '{' BasicBlock+ '}'
  2785. ///
  2786. bool LLParser::ParseFunctionBody(Function &Fn) {
  2787. if (Lex.getKind() != lltok::lbrace)
  2788. return TokError("expected '{' in function body");
  2789. Lex.Lex(); // eat the {.
  2790. int FunctionNumber = -1;
  2791. if (!Fn.hasName()) FunctionNumber = NumberedVals.size()-1;
  2792. PerFunctionState PFS(*this, Fn, FunctionNumber);
  2793. // We need at least one basic block.
  2794. if (Lex.getKind() == lltok::rbrace)
  2795. return TokError("function body requires at least one basic block");
  2796. while (Lex.getKind() != lltok::rbrace)
  2797. if (ParseBasicBlock(PFS)) return true;
  2798. // Eat the }.
  2799. Lex.Lex();
  2800. // Verify function is ok.
  2801. return PFS.FinishFunction();
  2802. }
  2803. /// ParseBasicBlock
  2804. /// ::= LabelStr? Instruction*
  2805. bool LLParser::ParseBasicBlock(PerFunctionState &PFS) {
  2806. // If this basic block starts out with a name, remember it.
  2807. std::string Name;
  2808. LocTy NameLoc = Lex.getLoc();
  2809. if (Lex.getKind() == lltok::LabelStr) {
  2810. Name = Lex.getStrVal();
  2811. Lex.Lex();
  2812. }
  2813. BasicBlock *BB = PFS.DefineBB(Name, NameLoc);
  2814. if (BB == 0) return true;
  2815. std::string NameStr;
  2816. // Parse the instructions in this block until we get a terminator.
  2817. Instruction *Inst;
  2818. do {
  2819. // This instruction may have three possibilities for a name: a) none
  2820. // specified, b) name specified "%foo =", c) number specified: "%4 =".
  2821. LocTy NameLoc = Lex.getLoc();
  2822. int NameID = -1;
  2823. NameStr = "";
  2824. if (Lex.getKind() == lltok::LocalVarID) {
  2825. NameID = Lex.getUIntVal();
  2826. Lex.Lex();
  2827. if (ParseToken(lltok::equal, "expected '=' after instruction id"))
  2828. return true;
  2829. } else if (Lex.getKind() == lltok::LocalVar) {
  2830. NameStr = Lex.getStrVal();
  2831. Lex.Lex();
  2832. if (ParseToken(lltok::equal, "expected '=' after instruction name"))
  2833. return true;
  2834. }
  2835. switch (ParseInstruction(Inst, BB, PFS)) {
  2836. default: llvm_unreachable("Unknown ParseInstruction result!");
  2837. case InstError: return true;
  2838. case InstNormal:
  2839. BB->getInstList().push_back(Inst);
  2840. // With a normal result, we check to see if the instruction is followed by
  2841. // a comma and metadata.
  2842. if (EatIfPresent(lltok::comma))
  2843. if (ParseInstructionMetadata(Inst, &PFS))
  2844. return true;
  2845. break;
  2846. case InstExtraComma:
  2847. BB->getInstList().push_back(Inst);
  2848. // If the instruction parser ate an extra comma at the end of it, it
  2849. // *must* be followed by metadata.
  2850. if (ParseInstructionMetadata(Inst, &PFS))
  2851. return true;
  2852. break;
  2853. }
  2854. // Set the name on the instruction.
  2855. if (PFS.SetInstName(NameID, NameStr, NameLoc, Inst)) return true;
  2856. } while (!isa<TerminatorInst>(Inst));
  2857. return false;
  2858. }
  2859. //===----------------------------------------------------------------------===//
  2860. // Instruction Parsing.
  2861. //===----------------------------------------------------------------------===//
  2862. /// ParseInstruction - Parse one of the many different instructions.
  2863. ///
  2864. int LLParser::ParseInstruction(Instruction *&Inst, BasicBlock *BB,
  2865. PerFunctionState &PFS) {
  2866. lltok::Kind Token = Lex.getKind();
  2867. if (Token == lltok::Eof)
  2868. return TokError("found end of file when expecting more instructions");
  2869. LocTy Loc = Lex.getLoc();
  2870. unsigned KeywordVal = Lex.getUIntVal();
  2871. Lex.Lex(); // Eat the keyword.
  2872. switch (Token) {
  2873. default: return Error(Loc, "expected instruction opcode");
  2874. // Terminator Instructions.
  2875. case lltok::kw_unreachable: Inst = new UnreachableInst(Context); return false;
  2876. case lltok::kw_ret: return ParseRet(Inst, BB, PFS);
  2877. case lltok::kw_br: return ParseBr(Inst, PFS);
  2878. case lltok::kw_switch: return ParseSwitch(Inst, PFS);
  2879. case lltok::kw_indirectbr: return ParseIndirectBr(Inst, PFS);
  2880. case lltok::kw_invoke: return ParseInvoke(Inst, PFS);
  2881. case lltok::kw_resume: return ParseResume(Inst, PFS);
  2882. // Binary Operators.
  2883. case lltok::kw_add:
  2884. case lltok::kw_sub:
  2885. case lltok::kw_mul:
  2886. case lltok::kw_shl: {
  2887. bool NUW = EatIfPresent(lltok::kw_nuw);
  2888. bool NSW = EatIfPresent(lltok::kw_nsw);
  2889. if (!NUW) NUW = EatIfPresent(lltok::kw_nuw);
  2890. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  2891. if (NUW) cast<BinaryOperator>(Inst)->setHasNoUnsignedWrap(true);
  2892. if (NSW) cast<BinaryOperator>(Inst)->setHasNoSignedWrap(true);
  2893. return false;
  2894. }
  2895. case lltok::kw_fadd:
  2896. case lltok::kw_fsub:
  2897. case lltok::kw_fmul:
  2898. case lltok::kw_fdiv:
  2899. case lltok::kw_frem: {
  2900. FastMathFlags FMF = EatFastMathFlagsIfPresent();
  2901. int Res = ParseArithmetic(Inst, PFS, KeywordVal, 2);
  2902. if (Res != 0)
  2903. return Res;
  2904. if (FMF.any())
  2905. Inst->setFastMathFlags(FMF);
  2906. return 0;
  2907. }
  2908. case lltok::kw_sdiv:
  2909. case lltok::kw_udiv:
  2910. case lltok::kw_lshr:
  2911. case lltok::kw_ashr: {
  2912. bool Exact = EatIfPresent(lltok::kw_exact);
  2913. if (ParseArithmetic(Inst, PFS, KeywordVal, 1)) return true;
  2914. if (Exact) cast<BinaryOperator>(Inst)->setIsExact(true);
  2915. return false;
  2916. }
  2917. case lltok::kw_urem:
  2918. case lltok::kw_srem: return ParseArithmetic(Inst, PFS, KeywordVal, 1);
  2919. case lltok::kw_and:
  2920. case lltok::kw_or:
  2921. case lltok::kw_xor: return ParseLogical(Inst, PFS, KeywordVal);
  2922. case lltok::kw_icmp:
  2923. case lltok::kw_fcmp: return ParseCompare(Inst, PFS, KeywordVal);
  2924. // Casts.
  2925. case lltok::kw_trunc:
  2926. case lltok::kw_zext:
  2927. case lltok::kw_sext:
  2928. case lltok::kw_fptrunc:
  2929. case lltok::kw_fpext:
  2930. case lltok::kw_bitcast:
  2931. case lltok::kw_addrspacecast:
  2932. case lltok::kw_uitofp:
  2933. case lltok::kw_sitofp:
  2934. case lltok::kw_fptoui:
  2935. case lltok::kw_fptosi:
  2936. case lltok::kw_inttoptr:
  2937. case lltok::kw_ptrtoint: return ParseCast(Inst, PFS, KeywordVal);
  2938. // Other.
  2939. case lltok::kw_select: return ParseSelect(Inst, PFS);
  2940. case lltok::kw_va_arg: return ParseVA_Arg(Inst, PFS);
  2941. case lltok::kw_extractelement: return ParseExtractElement(Inst, PFS);
  2942. case lltok::kw_insertelement: return ParseInsertElement(Inst, PFS);
  2943. case lltok::kw_shufflevector: return ParseShuffleVector(Inst, PFS);
  2944. case lltok::kw_phi: return ParsePHI(Inst, PFS);
  2945. case lltok::kw_landingpad: return ParseLandingPad(Inst, PFS);
  2946. case lltok::kw_call: return ParseCall(Inst, PFS, false);
  2947. case lltok::kw_tail: return ParseCall(Inst, PFS, true);
  2948. // Memory.
  2949. case lltok::kw_alloca: return ParseAlloc(Inst, PFS);
  2950. case lltok::kw_load: return ParseLoad(Inst, PFS);
  2951. case lltok::kw_store: return ParseStore(Inst, PFS);
  2952. case lltok::kw_cmpxchg: return ParseCmpXchg(Inst, PFS);
  2953. case lltok::kw_atomicrmw: return ParseAtomicRMW(Inst, PFS);
  2954. case lltok::kw_fence: return ParseFence(Inst, PFS);
  2955. case lltok::kw_getelementptr: return ParseGetElementPtr(Inst, PFS);
  2956. case lltok::kw_extractvalue: return ParseExtractValue(Inst, PFS);
  2957. case lltok::kw_insertvalue: return ParseInsertValue(Inst, PFS);
  2958. }
  2959. }
  2960. /// ParseCmpPredicate - Parse an integer or fp predicate, based on Kind.
  2961. bool LLParser::ParseCmpPredicate(unsigned &P, unsigned Opc) {
  2962. if (Opc == Instruction::FCmp) {
  2963. switch (Lex.getKind()) {
  2964. default: return TokError("expected fcmp predicate (e.g. 'oeq')");
  2965. case lltok::kw_oeq: P = CmpInst::FCMP_OEQ; break;
  2966. case lltok::kw_one: P = CmpInst::FCMP_ONE; break;
  2967. case lltok::kw_olt: P = CmpInst::FCMP_OLT; break;
  2968. case lltok::kw_ogt: P = CmpInst::FCMP_OGT; break;
  2969. case lltok::kw_ole: P = CmpInst::FCMP_OLE; break;
  2970. case lltok::kw_oge: P = CmpInst::FCMP_OGE; break;
  2971. case lltok::kw_ord: P = CmpInst::FCMP_ORD; break;
  2972. case lltok::kw_uno: P = CmpInst::FCMP_UNO; break;
  2973. case lltok::kw_ueq: P = CmpInst::FCMP_UEQ; break;
  2974. case lltok::kw_une: P = CmpInst::FCMP_UNE; break;
  2975. case lltok::kw_ult: P = CmpInst::FCMP_ULT; break;
  2976. case lltok::kw_ugt: P = CmpInst::FCMP_UGT; break;
  2977. case lltok::kw_ule: P = CmpInst::FCMP_ULE; break;
  2978. case lltok::kw_uge: P = CmpInst::FCMP_UGE; break;
  2979. case lltok::kw_true: P = CmpInst::FCMP_TRUE; break;
  2980. case lltok::kw_false: P = CmpInst::FCMP_FALSE; break;
  2981. }
  2982. } else {
  2983. switch (Lex.getKind()) {
  2984. default: return TokError("expected icmp predicate (e.g. 'eq')");
  2985. case lltok::kw_eq: P = CmpInst::ICMP_EQ; break;
  2986. case lltok::kw_ne: P = CmpInst::ICMP_NE; break;
  2987. case lltok::kw_slt: P = CmpInst::ICMP_SLT; break;
  2988. case lltok::kw_sgt: P = CmpInst::ICMP_SGT; break;
  2989. case lltok::kw_sle: P = CmpInst::ICMP_SLE; break;
  2990. case lltok::kw_sge: P = CmpInst::ICMP_SGE; break;
  2991. case lltok::kw_ult: P = CmpInst::ICMP_ULT; break;
  2992. case lltok::kw_ugt: P = CmpInst::ICMP_UGT; break;
  2993. case lltok::kw_ule: P = CmpInst::ICMP_ULE; break;
  2994. case lltok::kw_uge: P = CmpInst::ICMP_UGE; break;
  2995. }
  2996. }
  2997. Lex.Lex();
  2998. return false;
  2999. }
  3000. //===----------------------------------------------------------------------===//
  3001. // Terminator Instructions.
  3002. //===----------------------------------------------------------------------===//
  3003. /// ParseRet - Parse a return instruction.
  3004. /// ::= 'ret' void (',' !dbg, !1)*
  3005. /// ::= 'ret' TypeAndValue (',' !dbg, !1)*
  3006. bool LLParser::ParseRet(Instruction *&Inst, BasicBlock *BB,
  3007. PerFunctionState &PFS) {
  3008. SMLoc TypeLoc = Lex.getLoc();
  3009. Type *Ty = 0;
  3010. if (ParseType(Ty, true /*void allowed*/)) return true;
  3011. Type *ResType = PFS.getFunction().getReturnType();
  3012. if (Ty->isVoidTy()) {
  3013. if (!ResType->isVoidTy())
  3014. return Error(TypeLoc, "value doesn't match function result type '" +
  3015. getTypeString(ResType) + "'");
  3016. Inst = ReturnInst::Create(Context);
  3017. return false;
  3018. }
  3019. Value *RV;
  3020. if (ParseValue(Ty, RV, PFS)) return true;
  3021. if (ResType != RV->getType())
  3022. return Error(TypeLoc, "value doesn't match function result type '" +
  3023. getTypeString(ResType) + "'");
  3024. Inst = ReturnInst::Create(Context, RV);
  3025. return false;
  3026. }
  3027. /// ParseBr
  3028. /// ::= 'br' TypeAndValue
  3029. /// ::= 'br' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  3030. bool LLParser::ParseBr(Instruction *&Inst, PerFunctionState &PFS) {
  3031. LocTy Loc, Loc2;
  3032. Value *Op0;
  3033. BasicBlock *Op1, *Op2;
  3034. if (ParseTypeAndValue(Op0, Loc, PFS)) return true;
  3035. if (BasicBlock *BB = dyn_cast<BasicBlock>(Op0)) {
  3036. Inst = BranchInst::Create(BB);
  3037. return false;
  3038. }
  3039. if (Op0->getType() != Type::getInt1Ty(Context))
  3040. return Error(Loc, "branch condition must have 'i1' type");
  3041. if (ParseToken(lltok::comma, "expected ',' after branch condition") ||
  3042. ParseTypeAndBasicBlock(Op1, Loc, PFS) ||
  3043. ParseToken(lltok::comma, "expected ',' after true destination") ||
  3044. ParseTypeAndBasicBlock(Op2, Loc2, PFS))
  3045. return true;
  3046. Inst = BranchInst::Create(Op1, Op2, Op0);
  3047. return false;
  3048. }
  3049. /// ParseSwitch
  3050. /// Instruction
  3051. /// ::= 'switch' TypeAndValue ',' TypeAndValue '[' JumpTable ']'
  3052. /// JumpTable
  3053. /// ::= (TypeAndValue ',' TypeAndValue)*
  3054. bool LLParser::ParseSwitch(Instruction *&Inst, PerFunctionState &PFS) {
  3055. LocTy CondLoc, BBLoc;
  3056. Value *Cond;
  3057. BasicBlock *DefaultBB;
  3058. if (ParseTypeAndValue(Cond, CondLoc, PFS) ||
  3059. ParseToken(lltok::comma, "expected ',' after switch condition") ||
  3060. ParseTypeAndBasicBlock(DefaultBB, BBLoc, PFS) ||
  3061. ParseToken(lltok::lsquare, "expected '[' with switch table"))
  3062. return true;
  3063. if (!Cond->getType()->isIntegerTy())
  3064. return Error(CondLoc, "switch condition must have integer type");
  3065. // Parse the jump table pairs.
  3066. SmallPtrSet<Value*, 32> SeenCases;
  3067. SmallVector<std::pair<ConstantInt*, BasicBlock*>, 32> Table;
  3068. while (Lex.getKind() != lltok::rsquare) {
  3069. Value *Constant;
  3070. BasicBlock *DestBB;
  3071. if (ParseTypeAndValue(Constant, CondLoc, PFS) ||
  3072. ParseToken(lltok::comma, "expected ',' after case value") ||
  3073. ParseTypeAndBasicBlock(DestBB, PFS))
  3074. return true;
  3075. if (!SeenCases.insert(Constant))
  3076. return Error(CondLoc, "duplicate case value in switch");
  3077. if (!isa<ConstantInt>(Constant))
  3078. return Error(CondLoc, "case value is not a constant integer");
  3079. Table.push_back(std::make_pair(cast<ConstantInt>(Constant), DestBB));
  3080. }
  3081. Lex.Lex(); // Eat the ']'.
  3082. SwitchInst *SI = SwitchInst::Create(Cond, DefaultBB, Table.size());
  3083. for (unsigned i = 0, e = Table.size(); i != e; ++i)
  3084. SI->addCase(Table[i].first, Table[i].second);
  3085. Inst = SI;
  3086. return false;
  3087. }
  3088. /// ParseIndirectBr
  3089. /// Instruction
  3090. /// ::= 'indirectbr' TypeAndValue ',' '[' LabelList ']'
  3091. bool LLParser::ParseIndirectBr(Instruction *&Inst, PerFunctionState &PFS) {
  3092. LocTy AddrLoc;
  3093. Value *Address;
  3094. if (ParseTypeAndValue(Address, AddrLoc, PFS) ||
  3095. ParseToken(lltok::comma, "expected ',' after indirectbr address") ||
  3096. ParseToken(lltok::lsquare, "expected '[' with indirectbr"))
  3097. return true;
  3098. if (!Address->getType()->isPointerTy())
  3099. return Error(AddrLoc, "indirectbr address must have pointer type");
  3100. // Parse the destination list.
  3101. SmallVector<BasicBlock*, 16> DestList;
  3102. if (Lex.getKind() != lltok::rsquare) {
  3103. BasicBlock *DestBB;
  3104. if (ParseTypeAndBasicBlock(DestBB, PFS))
  3105. return true;
  3106. DestList.push_back(DestBB);
  3107. while (EatIfPresent(lltok::comma)) {
  3108. if (ParseTypeAndBasicBlock(DestBB, PFS))
  3109. return true;
  3110. DestList.push_back(DestBB);
  3111. }
  3112. }
  3113. if (ParseToken(lltok::rsquare, "expected ']' at end of block list"))
  3114. return true;
  3115. IndirectBrInst *IBI = IndirectBrInst::Create(Address, DestList.size());
  3116. for (unsigned i = 0, e = DestList.size(); i != e; ++i)
  3117. IBI->addDestination(DestList[i]);
  3118. Inst = IBI;
  3119. return false;
  3120. }
  3121. /// ParseInvoke
  3122. /// ::= 'invoke' OptionalCallingConv OptionalAttrs Type Value ParamList
  3123. /// OptionalAttrs 'to' TypeAndValue 'unwind' TypeAndValue
  3124. bool LLParser::ParseInvoke(Instruction *&Inst, PerFunctionState &PFS) {
  3125. LocTy CallLoc = Lex.getLoc();
  3126. AttrBuilder RetAttrs, FnAttrs;
  3127. std::vector<unsigned> FwdRefAttrGrps;
  3128. LocTy NoBuiltinLoc;
  3129. CallingConv::ID CC;
  3130. Type *RetType = 0;
  3131. LocTy RetTypeLoc;
  3132. ValID CalleeID;
  3133. SmallVector<ParamInfo, 16> ArgList;
  3134. BasicBlock *NormalBB, *UnwindBB;
  3135. if (ParseOptionalCallingConv(CC) ||
  3136. ParseOptionalReturnAttrs(RetAttrs) ||
  3137. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  3138. ParseValID(CalleeID) ||
  3139. ParseParameterList(ArgList, PFS) ||
  3140. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  3141. NoBuiltinLoc) ||
  3142. ParseToken(lltok::kw_to, "expected 'to' in invoke") ||
  3143. ParseTypeAndBasicBlock(NormalBB, PFS) ||
  3144. ParseToken(lltok::kw_unwind, "expected 'unwind' in invoke") ||
  3145. ParseTypeAndBasicBlock(UnwindBB, PFS))
  3146. return true;
  3147. // If RetType is a non-function pointer type, then this is the short syntax
  3148. // for the call, which means that RetType is just the return type. Infer the
  3149. // rest of the function argument types from the arguments that are present.
  3150. PointerType *PFTy = 0;
  3151. FunctionType *Ty = 0;
  3152. if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
  3153. !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
  3154. // Pull out the types of all of the arguments...
  3155. std::vector<Type*> ParamTypes;
  3156. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  3157. ParamTypes.push_back(ArgList[i].V->getType());
  3158. if (!FunctionType::isValidReturnType(RetType))
  3159. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  3160. Ty = FunctionType::get(RetType, ParamTypes, false);
  3161. PFTy = PointerType::getUnqual(Ty);
  3162. }
  3163. // Look up the callee.
  3164. Value *Callee;
  3165. if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
  3166. // Set up the Attribute for the function.
  3167. SmallVector<AttributeSet, 8> Attrs;
  3168. if (RetAttrs.hasAttributes())
  3169. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  3170. AttributeSet::ReturnIndex,
  3171. RetAttrs));
  3172. SmallVector<Value*, 8> Args;
  3173. // Loop through FunctionType's arguments and ensure they are specified
  3174. // correctly. Also, gather any parameter attributes.
  3175. FunctionType::param_iterator I = Ty->param_begin();
  3176. FunctionType::param_iterator E = Ty->param_end();
  3177. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  3178. Type *ExpectedTy = 0;
  3179. if (I != E) {
  3180. ExpectedTy = *I++;
  3181. } else if (!Ty->isVarArg()) {
  3182. return Error(ArgList[i].Loc, "too many arguments specified");
  3183. }
  3184. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  3185. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  3186. getTypeString(ExpectedTy) + "'");
  3187. Args.push_back(ArgList[i].V);
  3188. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  3189. AttrBuilder B(ArgList[i].Attrs, i + 1);
  3190. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  3191. }
  3192. }
  3193. if (I != E)
  3194. return Error(CallLoc, "not enough parameters specified for call");
  3195. if (FnAttrs.hasAttributes())
  3196. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  3197. AttributeSet::FunctionIndex,
  3198. FnAttrs));
  3199. // Finish off the Attribute and check them
  3200. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  3201. InvokeInst *II = InvokeInst::Create(Callee, NormalBB, UnwindBB, Args);
  3202. II->setCallingConv(CC);
  3203. II->setAttributes(PAL);
  3204. ForwardRefAttrGroups[II] = FwdRefAttrGrps;
  3205. Inst = II;
  3206. return false;
  3207. }
  3208. /// ParseResume
  3209. /// ::= 'resume' TypeAndValue
  3210. bool LLParser::ParseResume(Instruction *&Inst, PerFunctionState &PFS) {
  3211. Value *Exn; LocTy ExnLoc;
  3212. if (ParseTypeAndValue(Exn, ExnLoc, PFS))
  3213. return true;
  3214. ResumeInst *RI = ResumeInst::Create(Exn);
  3215. Inst = RI;
  3216. return false;
  3217. }
  3218. //===----------------------------------------------------------------------===//
  3219. // Binary Operators.
  3220. //===----------------------------------------------------------------------===//
  3221. /// ParseArithmetic
  3222. /// ::= ArithmeticOps TypeAndValue ',' Value
  3223. ///
  3224. /// If OperandType is 0, then any FP or integer operand is allowed. If it is 1,
  3225. /// then any integer operand is allowed, if it is 2, any fp operand is allowed.
  3226. bool LLParser::ParseArithmetic(Instruction *&Inst, PerFunctionState &PFS,
  3227. unsigned Opc, unsigned OperandType) {
  3228. LocTy Loc; Value *LHS, *RHS;
  3229. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  3230. ParseToken(lltok::comma, "expected ',' in arithmetic operation") ||
  3231. ParseValue(LHS->getType(), RHS, PFS))
  3232. return true;
  3233. bool Valid;
  3234. switch (OperandType) {
  3235. default: llvm_unreachable("Unknown operand type!");
  3236. case 0: // int or FP.
  3237. Valid = LHS->getType()->isIntOrIntVectorTy() ||
  3238. LHS->getType()->isFPOrFPVectorTy();
  3239. break;
  3240. case 1: Valid = LHS->getType()->isIntOrIntVectorTy(); break;
  3241. case 2: Valid = LHS->getType()->isFPOrFPVectorTy(); break;
  3242. }
  3243. if (!Valid)
  3244. return Error(Loc, "invalid operand type for instruction");
  3245. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3246. return false;
  3247. }
  3248. /// ParseLogical
  3249. /// ::= ArithmeticOps TypeAndValue ',' Value {
  3250. bool LLParser::ParseLogical(Instruction *&Inst, PerFunctionState &PFS,
  3251. unsigned Opc) {
  3252. LocTy Loc; Value *LHS, *RHS;
  3253. if (ParseTypeAndValue(LHS, Loc, PFS) ||
  3254. ParseToken(lltok::comma, "expected ',' in logical operation") ||
  3255. ParseValue(LHS->getType(), RHS, PFS))
  3256. return true;
  3257. if (!LHS->getType()->isIntOrIntVectorTy())
  3258. return Error(Loc,"instruction requires integer or integer vector operands");
  3259. Inst = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3260. return false;
  3261. }
  3262. /// ParseCompare
  3263. /// ::= 'icmp' IPredicates TypeAndValue ',' Value
  3264. /// ::= 'fcmp' FPredicates TypeAndValue ',' Value
  3265. bool LLParser::ParseCompare(Instruction *&Inst, PerFunctionState &PFS,
  3266. unsigned Opc) {
  3267. // Parse the integer/fp comparison predicate.
  3268. LocTy Loc;
  3269. unsigned Pred;
  3270. Value *LHS, *RHS;
  3271. if (ParseCmpPredicate(Pred, Opc) ||
  3272. ParseTypeAndValue(LHS, Loc, PFS) ||
  3273. ParseToken(lltok::comma, "expected ',' after compare value") ||
  3274. ParseValue(LHS->getType(), RHS, PFS))
  3275. return true;
  3276. if (Opc == Instruction::FCmp) {
  3277. if (!LHS->getType()->isFPOrFPVectorTy())
  3278. return Error(Loc, "fcmp requires floating point operands");
  3279. Inst = new FCmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  3280. } else {
  3281. assert(Opc == Instruction::ICmp && "Unknown opcode for CmpInst!");
  3282. if (!LHS->getType()->isIntOrIntVectorTy() &&
  3283. !LHS->getType()->getScalarType()->isPointerTy())
  3284. return Error(Loc, "icmp requires integer operands");
  3285. Inst = new ICmpInst(CmpInst::Predicate(Pred), LHS, RHS);
  3286. }
  3287. return false;
  3288. }
  3289. //===----------------------------------------------------------------------===//
  3290. // Other Instructions.
  3291. //===----------------------------------------------------------------------===//
  3292. /// ParseCast
  3293. /// ::= CastOpc TypeAndValue 'to' Type
  3294. bool LLParser::ParseCast(Instruction *&Inst, PerFunctionState &PFS,
  3295. unsigned Opc) {
  3296. LocTy Loc;
  3297. Value *Op;
  3298. Type *DestTy = 0;
  3299. if (ParseTypeAndValue(Op, Loc, PFS) ||
  3300. ParseToken(lltok::kw_to, "expected 'to' after cast value") ||
  3301. ParseType(DestTy))
  3302. return true;
  3303. if (!CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy)) {
  3304. CastInst::castIsValid((Instruction::CastOps)Opc, Op, DestTy);
  3305. return Error(Loc, "invalid cast opcode for cast from '" +
  3306. getTypeString(Op->getType()) + "' to '" +
  3307. getTypeString(DestTy) + "'");
  3308. }
  3309. Inst = CastInst::Create((Instruction::CastOps)Opc, Op, DestTy);
  3310. return false;
  3311. }
  3312. /// ParseSelect
  3313. /// ::= 'select' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  3314. bool LLParser::ParseSelect(Instruction *&Inst, PerFunctionState &PFS) {
  3315. LocTy Loc;
  3316. Value *Op0, *Op1, *Op2;
  3317. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  3318. ParseToken(lltok::comma, "expected ',' after select condition") ||
  3319. ParseTypeAndValue(Op1, PFS) ||
  3320. ParseToken(lltok::comma, "expected ',' after select value") ||
  3321. ParseTypeAndValue(Op2, PFS))
  3322. return true;
  3323. if (const char *Reason = SelectInst::areInvalidOperands(Op0, Op1, Op2))
  3324. return Error(Loc, Reason);
  3325. Inst = SelectInst::Create(Op0, Op1, Op2);
  3326. return false;
  3327. }
  3328. /// ParseVA_Arg
  3329. /// ::= 'va_arg' TypeAndValue ',' Type
  3330. bool LLParser::ParseVA_Arg(Instruction *&Inst, PerFunctionState &PFS) {
  3331. Value *Op;
  3332. Type *EltTy = 0;
  3333. LocTy TypeLoc;
  3334. if (ParseTypeAndValue(Op, PFS) ||
  3335. ParseToken(lltok::comma, "expected ',' after vaarg operand") ||
  3336. ParseType(EltTy, TypeLoc))
  3337. return true;
  3338. if (!EltTy->isFirstClassType())
  3339. return Error(TypeLoc, "va_arg requires operand with first class type");
  3340. Inst = new VAArgInst(Op, EltTy);
  3341. return false;
  3342. }
  3343. /// ParseExtractElement
  3344. /// ::= 'extractelement' TypeAndValue ',' TypeAndValue
  3345. bool LLParser::ParseExtractElement(Instruction *&Inst, PerFunctionState &PFS) {
  3346. LocTy Loc;
  3347. Value *Op0, *Op1;
  3348. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  3349. ParseToken(lltok::comma, "expected ',' after extract value") ||
  3350. ParseTypeAndValue(Op1, PFS))
  3351. return true;
  3352. if (!ExtractElementInst::isValidOperands(Op0, Op1))
  3353. return Error(Loc, "invalid extractelement operands");
  3354. Inst = ExtractElementInst::Create(Op0, Op1);
  3355. return false;
  3356. }
  3357. /// ParseInsertElement
  3358. /// ::= 'insertelement' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  3359. bool LLParser::ParseInsertElement(Instruction *&Inst, PerFunctionState &PFS) {
  3360. LocTy Loc;
  3361. Value *Op0, *Op1, *Op2;
  3362. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  3363. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  3364. ParseTypeAndValue(Op1, PFS) ||
  3365. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  3366. ParseTypeAndValue(Op2, PFS))
  3367. return true;
  3368. if (!InsertElementInst::isValidOperands(Op0, Op1, Op2))
  3369. return Error(Loc, "invalid insertelement operands");
  3370. Inst = InsertElementInst::Create(Op0, Op1, Op2);
  3371. return false;
  3372. }
  3373. /// ParseShuffleVector
  3374. /// ::= 'shufflevector' TypeAndValue ',' TypeAndValue ',' TypeAndValue
  3375. bool LLParser::ParseShuffleVector(Instruction *&Inst, PerFunctionState &PFS) {
  3376. LocTy Loc;
  3377. Value *Op0, *Op1, *Op2;
  3378. if (ParseTypeAndValue(Op0, Loc, PFS) ||
  3379. ParseToken(lltok::comma, "expected ',' after shuffle mask") ||
  3380. ParseTypeAndValue(Op1, PFS) ||
  3381. ParseToken(lltok::comma, "expected ',' after shuffle value") ||
  3382. ParseTypeAndValue(Op2, PFS))
  3383. return true;
  3384. if (!ShuffleVectorInst::isValidOperands(Op0, Op1, Op2))
  3385. return Error(Loc, "invalid shufflevector operands");
  3386. Inst = new ShuffleVectorInst(Op0, Op1, Op2);
  3387. return false;
  3388. }
  3389. /// ParsePHI
  3390. /// ::= 'phi' Type '[' Value ',' Value ']' (',' '[' Value ',' Value ']')*
  3391. int LLParser::ParsePHI(Instruction *&Inst, PerFunctionState &PFS) {
  3392. Type *Ty = 0; LocTy TypeLoc;
  3393. Value *Op0, *Op1;
  3394. if (ParseType(Ty, TypeLoc) ||
  3395. ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  3396. ParseValue(Ty, Op0, PFS) ||
  3397. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  3398. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  3399. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  3400. return true;
  3401. bool AteExtraComma = false;
  3402. SmallVector<std::pair<Value*, BasicBlock*>, 16> PHIVals;
  3403. while (1) {
  3404. PHIVals.push_back(std::make_pair(Op0, cast<BasicBlock>(Op1)));
  3405. if (!EatIfPresent(lltok::comma))
  3406. break;
  3407. if (Lex.getKind() == lltok::MetadataVar) {
  3408. AteExtraComma = true;
  3409. break;
  3410. }
  3411. if (ParseToken(lltok::lsquare, "expected '[' in phi value list") ||
  3412. ParseValue(Ty, Op0, PFS) ||
  3413. ParseToken(lltok::comma, "expected ',' after insertelement value") ||
  3414. ParseValue(Type::getLabelTy(Context), Op1, PFS) ||
  3415. ParseToken(lltok::rsquare, "expected ']' in phi value list"))
  3416. return true;
  3417. }
  3418. if (!Ty->isFirstClassType())
  3419. return Error(TypeLoc, "phi node must have first class type");
  3420. PHINode *PN = PHINode::Create(Ty, PHIVals.size());
  3421. for (unsigned i = 0, e = PHIVals.size(); i != e; ++i)
  3422. PN->addIncoming(PHIVals[i].first, PHIVals[i].second);
  3423. Inst = PN;
  3424. return AteExtraComma ? InstExtraComma : InstNormal;
  3425. }
  3426. /// ParseLandingPad
  3427. /// ::= 'landingpad' Type 'personality' TypeAndValue 'cleanup'? Clause+
  3428. /// Clause
  3429. /// ::= 'catch' TypeAndValue
  3430. /// ::= 'filter'
  3431. /// ::= 'filter' TypeAndValue ( ',' TypeAndValue )*
  3432. bool LLParser::ParseLandingPad(Instruction *&Inst, PerFunctionState &PFS) {
  3433. Type *Ty = 0; LocTy TyLoc;
  3434. Value *PersFn; LocTy PersFnLoc;
  3435. if (ParseType(Ty, TyLoc) ||
  3436. ParseToken(lltok::kw_personality, "expected 'personality'") ||
  3437. ParseTypeAndValue(PersFn, PersFnLoc, PFS))
  3438. return true;
  3439. LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, 0);
  3440. LP->setCleanup(EatIfPresent(lltok::kw_cleanup));
  3441. while (Lex.getKind() == lltok::kw_catch || Lex.getKind() == lltok::kw_filter){
  3442. LandingPadInst::ClauseType CT;
  3443. if (EatIfPresent(lltok::kw_catch))
  3444. CT = LandingPadInst::Catch;
  3445. else if (EatIfPresent(lltok::kw_filter))
  3446. CT = LandingPadInst::Filter;
  3447. else
  3448. return TokError("expected 'catch' or 'filter' clause type");
  3449. Value *V; LocTy VLoc;
  3450. if (ParseTypeAndValue(V, VLoc, PFS)) {
  3451. delete LP;
  3452. return true;
  3453. }
  3454. // A 'catch' type expects a non-array constant. A filter clause expects an
  3455. // array constant.
  3456. if (CT == LandingPadInst::Catch) {
  3457. if (isa<ArrayType>(V->getType()))
  3458. Error(VLoc, "'catch' clause has an invalid type");
  3459. } else {
  3460. if (!isa<ArrayType>(V->getType()))
  3461. Error(VLoc, "'filter' clause has an invalid type");
  3462. }
  3463. LP->addClause(V);
  3464. }
  3465. Inst = LP;
  3466. return false;
  3467. }
  3468. /// ParseCall
  3469. /// ::= 'tail'? 'call' OptionalCallingConv OptionalAttrs Type Value
  3470. /// ParameterList OptionalAttrs
  3471. bool LLParser::ParseCall(Instruction *&Inst, PerFunctionState &PFS,
  3472. bool isTail) {
  3473. AttrBuilder RetAttrs, FnAttrs;
  3474. std::vector<unsigned> FwdRefAttrGrps;
  3475. LocTy BuiltinLoc;
  3476. CallingConv::ID CC;
  3477. Type *RetType = 0;
  3478. LocTy RetTypeLoc;
  3479. ValID CalleeID;
  3480. SmallVector<ParamInfo, 16> ArgList;
  3481. LocTy CallLoc = Lex.getLoc();
  3482. if ((isTail && ParseToken(lltok::kw_call, "expected 'tail call'")) ||
  3483. ParseOptionalCallingConv(CC) ||
  3484. ParseOptionalReturnAttrs(RetAttrs) ||
  3485. ParseType(RetType, RetTypeLoc, true /*void allowed*/) ||
  3486. ParseValID(CalleeID) ||
  3487. ParseParameterList(ArgList, PFS) ||
  3488. ParseFnAttributeValuePairs(FnAttrs, FwdRefAttrGrps, false,
  3489. BuiltinLoc))
  3490. return true;
  3491. // If RetType is a non-function pointer type, then this is the short syntax
  3492. // for the call, which means that RetType is just the return type. Infer the
  3493. // rest of the function argument types from the arguments that are present.
  3494. PointerType *PFTy = 0;
  3495. FunctionType *Ty = 0;
  3496. if (!(PFTy = dyn_cast<PointerType>(RetType)) ||
  3497. !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
  3498. // Pull out the types of all of the arguments...
  3499. std::vector<Type*> ParamTypes;
  3500. for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
  3501. ParamTypes.push_back(ArgList[i].V->getType());
  3502. if (!FunctionType::isValidReturnType(RetType))
  3503. return Error(RetTypeLoc, "Invalid result type for LLVM function");
  3504. Ty = FunctionType::get(RetType, ParamTypes, false);
  3505. PFTy = PointerType::getUnqual(Ty);
  3506. }
  3507. // Look up the callee.
  3508. Value *Callee;
  3509. if (ConvertValIDToValue(PFTy, CalleeID, Callee, &PFS)) return true;
  3510. // Set up the Attribute for the function.
  3511. SmallVector<AttributeSet, 8> Attrs;
  3512. if (RetAttrs.hasAttributes())
  3513. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  3514. AttributeSet::ReturnIndex,
  3515. RetAttrs));
  3516. SmallVector<Value*, 8> Args;
  3517. // Loop through FunctionType's arguments and ensure they are specified
  3518. // correctly. Also, gather any parameter attributes.
  3519. FunctionType::param_iterator I = Ty->param_begin();
  3520. FunctionType::param_iterator E = Ty->param_end();
  3521. for (unsigned i = 0, e = ArgList.size(); i != e; ++i) {
  3522. Type *ExpectedTy = 0;
  3523. if (I != E) {
  3524. ExpectedTy = *I++;
  3525. } else if (!Ty->isVarArg()) {
  3526. return Error(ArgList[i].Loc, "too many arguments specified");
  3527. }
  3528. if (ExpectedTy && ExpectedTy != ArgList[i].V->getType())
  3529. return Error(ArgList[i].Loc, "argument is not of expected type '" +
  3530. getTypeString(ExpectedTy) + "'");
  3531. Args.push_back(ArgList[i].V);
  3532. if (ArgList[i].Attrs.hasAttributes(i + 1)) {
  3533. AttrBuilder B(ArgList[i].Attrs, i + 1);
  3534. Attrs.push_back(AttributeSet::get(RetType->getContext(), i + 1, B));
  3535. }
  3536. }
  3537. if (I != E)
  3538. return Error(CallLoc, "not enough parameters specified for call");
  3539. if (FnAttrs.hasAttributes())
  3540. Attrs.push_back(AttributeSet::get(RetType->getContext(),
  3541. AttributeSet::FunctionIndex,
  3542. FnAttrs));
  3543. // Finish off the Attribute and check them
  3544. AttributeSet PAL = AttributeSet::get(Context, Attrs);
  3545. CallInst *CI = CallInst::Create(Callee, Args);
  3546. CI->setTailCall(isTail);
  3547. CI->setCallingConv(CC);
  3548. CI->setAttributes(PAL);
  3549. ForwardRefAttrGroups[CI] = FwdRefAttrGrps;
  3550. Inst = CI;
  3551. return false;
  3552. }
  3553. //===----------------------------------------------------------------------===//
  3554. // Memory Instructions.
  3555. //===----------------------------------------------------------------------===//
  3556. /// ParseAlloc
  3557. /// ::= 'alloca' 'inalloca'? Type (',' TypeAndValue)? (',' 'align' i32)?
  3558. int LLParser::ParseAlloc(Instruction *&Inst, PerFunctionState &PFS) {
  3559. Value *Size = 0;
  3560. LocTy SizeLoc;
  3561. unsigned Alignment = 0;
  3562. Type *Ty = 0;
  3563. bool IsInAlloca = EatIfPresent(lltok::kw_inalloca);
  3564. if (ParseType(Ty)) return true;
  3565. bool AteExtraComma = false;
  3566. if (EatIfPresent(lltok::comma)) {
  3567. if (Lex.getKind() == lltok::kw_align) {
  3568. if (ParseOptionalAlignment(Alignment)) return true;
  3569. } else if (Lex.getKind() == lltok::MetadataVar) {
  3570. AteExtraComma = true;
  3571. } else {
  3572. if (ParseTypeAndValue(Size, SizeLoc, PFS) ||
  3573. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  3574. return true;
  3575. }
  3576. }
  3577. if (Size && !Size->getType()->isIntegerTy())
  3578. return Error(SizeLoc, "element count must have integer type");
  3579. AllocaInst *AI = new AllocaInst(Ty, Size, Alignment);
  3580. AI->setUsedWithInAlloca(IsInAlloca);
  3581. Inst = AI;
  3582. return AteExtraComma ? InstExtraComma : InstNormal;
  3583. }
  3584. /// ParseLoad
  3585. /// ::= 'load' 'volatile'? TypeAndValue (',' 'align' i32)?
  3586. /// ::= 'load' 'atomic' 'volatile'? TypeAndValue
  3587. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  3588. int LLParser::ParseLoad(Instruction *&Inst, PerFunctionState &PFS) {
  3589. Value *Val; LocTy Loc;
  3590. unsigned Alignment = 0;
  3591. bool AteExtraComma = false;
  3592. bool isAtomic = false;
  3593. AtomicOrdering Ordering = NotAtomic;
  3594. SynchronizationScope Scope = CrossThread;
  3595. if (Lex.getKind() == lltok::kw_atomic) {
  3596. isAtomic = true;
  3597. Lex.Lex();
  3598. }
  3599. bool isVolatile = false;
  3600. if (Lex.getKind() == lltok::kw_volatile) {
  3601. isVolatile = true;
  3602. Lex.Lex();
  3603. }
  3604. if (ParseTypeAndValue(Val, Loc, PFS) ||
  3605. ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
  3606. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  3607. return true;
  3608. if (!Val->getType()->isPointerTy() ||
  3609. !cast<PointerType>(Val->getType())->getElementType()->isFirstClassType())
  3610. return Error(Loc, "load operand must be a pointer to a first class type");
  3611. if (isAtomic && !Alignment)
  3612. return Error(Loc, "atomic load must have explicit non-zero alignment");
  3613. if (Ordering == Release || Ordering == AcquireRelease)
  3614. return Error(Loc, "atomic load cannot use Release ordering");
  3615. Inst = new LoadInst(Val, "", isVolatile, Alignment, Ordering, Scope);
  3616. return AteExtraComma ? InstExtraComma : InstNormal;
  3617. }
  3618. /// ParseStore
  3619. /// ::= 'store' 'volatile'? TypeAndValue ',' TypeAndValue (',' 'align' i32)?
  3620. /// ::= 'store' 'atomic' 'volatile'? TypeAndValue ',' TypeAndValue
  3621. /// 'singlethread'? AtomicOrdering (',' 'align' i32)?
  3622. int LLParser::ParseStore(Instruction *&Inst, PerFunctionState &PFS) {
  3623. Value *Val, *Ptr; LocTy Loc, PtrLoc;
  3624. unsigned Alignment = 0;
  3625. bool AteExtraComma = false;
  3626. bool isAtomic = false;
  3627. AtomicOrdering Ordering = NotAtomic;
  3628. SynchronizationScope Scope = CrossThread;
  3629. if (Lex.getKind() == lltok::kw_atomic) {
  3630. isAtomic = true;
  3631. Lex.Lex();
  3632. }
  3633. bool isVolatile = false;
  3634. if (Lex.getKind() == lltok::kw_volatile) {
  3635. isVolatile = true;
  3636. Lex.Lex();
  3637. }
  3638. if (ParseTypeAndValue(Val, Loc, PFS) ||
  3639. ParseToken(lltok::comma, "expected ',' after store operand") ||
  3640. ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  3641. ParseScopeAndOrdering(isAtomic, Scope, Ordering) ||
  3642. ParseOptionalCommaAlign(Alignment, AteExtraComma))
  3643. return true;
  3644. if (!Ptr->getType()->isPointerTy())
  3645. return Error(PtrLoc, "store operand must be a pointer");
  3646. if (!Val->getType()->isFirstClassType())
  3647. return Error(Loc, "store operand must be a first class value");
  3648. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  3649. return Error(Loc, "stored value and pointer type do not match");
  3650. if (isAtomic && !Alignment)
  3651. return Error(Loc, "atomic store must have explicit non-zero alignment");
  3652. if (Ordering == Acquire || Ordering == AcquireRelease)
  3653. return Error(Loc, "atomic store cannot use Acquire ordering");
  3654. Inst = new StoreInst(Val, Ptr, isVolatile, Alignment, Ordering, Scope);
  3655. return AteExtraComma ? InstExtraComma : InstNormal;
  3656. }
  3657. /// ParseCmpXchg
  3658. /// ::= 'cmpxchg' 'volatile'? TypeAndValue ',' TypeAndValue ',' TypeAndValue
  3659. /// 'singlethread'? AtomicOrdering AtomicOrdering
  3660. int LLParser::ParseCmpXchg(Instruction *&Inst, PerFunctionState &PFS) {
  3661. Value *Ptr, *Cmp, *New; LocTy PtrLoc, CmpLoc, NewLoc;
  3662. bool AteExtraComma = false;
  3663. AtomicOrdering SuccessOrdering = NotAtomic;
  3664. AtomicOrdering FailureOrdering = NotAtomic;
  3665. SynchronizationScope Scope = CrossThread;
  3666. bool isVolatile = false;
  3667. if (EatIfPresent(lltok::kw_volatile))
  3668. isVolatile = true;
  3669. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  3670. ParseToken(lltok::comma, "expected ',' after cmpxchg address") ||
  3671. ParseTypeAndValue(Cmp, CmpLoc, PFS) ||
  3672. ParseToken(lltok::comma, "expected ',' after cmpxchg cmp operand") ||
  3673. ParseTypeAndValue(New, NewLoc, PFS) ||
  3674. ParseScopeAndOrdering(true /*Always atomic*/, Scope, SuccessOrdering) ||
  3675. ParseOrdering(FailureOrdering))
  3676. return true;
  3677. if (SuccessOrdering == Unordered || FailureOrdering == Unordered)
  3678. return TokError("cmpxchg cannot be unordered");
  3679. if (SuccessOrdering < FailureOrdering)
  3680. return TokError("cmpxchg must be at least as ordered on success as failure");
  3681. if (FailureOrdering == Release || FailureOrdering == AcquireRelease)
  3682. return TokError("cmpxchg failure ordering cannot include release semantics");
  3683. if (!Ptr->getType()->isPointerTy())
  3684. return Error(PtrLoc, "cmpxchg operand must be a pointer");
  3685. if (cast<PointerType>(Ptr->getType())->getElementType() != Cmp->getType())
  3686. return Error(CmpLoc, "compare value and pointer type do not match");
  3687. if (cast<PointerType>(Ptr->getType())->getElementType() != New->getType())
  3688. return Error(NewLoc, "new value and pointer type do not match");
  3689. if (!New->getType()->isIntegerTy())
  3690. return Error(NewLoc, "cmpxchg operand must be an integer");
  3691. unsigned Size = New->getType()->getPrimitiveSizeInBits();
  3692. if (Size < 8 || (Size & (Size - 1)))
  3693. return Error(NewLoc, "cmpxchg operand must be power-of-two byte-sized"
  3694. " integer");
  3695. AtomicCmpXchgInst *CXI = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
  3696. FailureOrdering, Scope);
  3697. CXI->setVolatile(isVolatile);
  3698. Inst = CXI;
  3699. return AteExtraComma ? InstExtraComma : InstNormal;
  3700. }
  3701. /// ParseAtomicRMW
  3702. /// ::= 'atomicrmw' 'volatile'? BinOp TypeAndValue ',' TypeAndValue
  3703. /// 'singlethread'? AtomicOrdering
  3704. int LLParser::ParseAtomicRMW(Instruction *&Inst, PerFunctionState &PFS) {
  3705. Value *Ptr, *Val; LocTy PtrLoc, ValLoc;
  3706. bool AteExtraComma = false;
  3707. AtomicOrdering Ordering = NotAtomic;
  3708. SynchronizationScope Scope = CrossThread;
  3709. bool isVolatile = false;
  3710. AtomicRMWInst::BinOp Operation;
  3711. if (EatIfPresent(lltok::kw_volatile))
  3712. isVolatile = true;
  3713. switch (Lex.getKind()) {
  3714. default: return TokError("expected binary operation in atomicrmw");
  3715. case lltok::kw_xchg: Operation = AtomicRMWInst::Xchg; break;
  3716. case lltok::kw_add: Operation = AtomicRMWInst::Add; break;
  3717. case lltok::kw_sub: Operation = AtomicRMWInst::Sub; break;
  3718. case lltok::kw_and: Operation = AtomicRMWInst::And; break;
  3719. case lltok::kw_nand: Operation = AtomicRMWInst::Nand; break;
  3720. case lltok::kw_or: Operation = AtomicRMWInst::Or; break;
  3721. case lltok::kw_xor: Operation = AtomicRMWInst::Xor; break;
  3722. case lltok::kw_max: Operation = AtomicRMWInst::Max; break;
  3723. case lltok::kw_min: Operation = AtomicRMWInst::Min; break;
  3724. case lltok::kw_umax: Operation = AtomicRMWInst::UMax; break;
  3725. case lltok::kw_umin: Operation = AtomicRMWInst::UMin; break;
  3726. }
  3727. Lex.Lex(); // Eat the operation.
  3728. if (ParseTypeAndValue(Ptr, PtrLoc, PFS) ||
  3729. ParseToken(lltok::comma, "expected ',' after atomicrmw address") ||
  3730. ParseTypeAndValue(Val, ValLoc, PFS) ||
  3731. ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
  3732. return true;
  3733. if (Ordering == Unordered)
  3734. return TokError("atomicrmw cannot be unordered");
  3735. if (!Ptr->getType()->isPointerTy())
  3736. return Error(PtrLoc, "atomicrmw operand must be a pointer");
  3737. if (cast<PointerType>(Ptr->getType())->getElementType() != Val->getType())
  3738. return Error(ValLoc, "atomicrmw value and pointer type do not match");
  3739. if (!Val->getType()->isIntegerTy())
  3740. return Error(ValLoc, "atomicrmw operand must be an integer");
  3741. unsigned Size = Val->getType()->getPrimitiveSizeInBits();
  3742. if (Size < 8 || (Size & (Size - 1)))
  3743. return Error(ValLoc, "atomicrmw operand must be power-of-two byte-sized"
  3744. " integer");
  3745. AtomicRMWInst *RMWI =
  3746. new AtomicRMWInst(Operation, Ptr, Val, Ordering, Scope);
  3747. RMWI->setVolatile(isVolatile);
  3748. Inst = RMWI;
  3749. return AteExtraComma ? InstExtraComma : InstNormal;
  3750. }
  3751. /// ParseFence
  3752. /// ::= 'fence' 'singlethread'? AtomicOrdering
  3753. int LLParser::ParseFence(Instruction *&Inst, PerFunctionState &PFS) {
  3754. AtomicOrdering Ordering = NotAtomic;
  3755. SynchronizationScope Scope = CrossThread;
  3756. if (ParseScopeAndOrdering(true /*Always atomic*/, Scope, Ordering))
  3757. return true;
  3758. if (Ordering == Unordered)
  3759. return TokError("fence cannot be unordered");
  3760. if (Ordering == Monotonic)
  3761. return TokError("fence cannot be monotonic");
  3762. Inst = new FenceInst(Context, Ordering, Scope);
  3763. return InstNormal;
  3764. }
  3765. /// ParseGetElementPtr
  3766. /// ::= 'getelementptr' 'inbounds'? TypeAndValue (',' TypeAndValue)*
  3767. int LLParser::ParseGetElementPtr(Instruction *&Inst, PerFunctionState &PFS) {
  3768. Value *Ptr = 0;
  3769. Value *Val = 0;
  3770. LocTy Loc, EltLoc;
  3771. bool InBounds = EatIfPresent(lltok::kw_inbounds);
  3772. if (ParseTypeAndValue(Ptr, Loc, PFS)) return true;
  3773. Type *BaseType = Ptr->getType();
  3774. PointerType *BasePointerType = dyn_cast<PointerType>(BaseType->getScalarType());
  3775. if (!BasePointerType)
  3776. return Error(Loc, "base of getelementptr must be a pointer");
  3777. SmallVector<Value*, 16> Indices;
  3778. bool AteExtraComma = false;
  3779. while (EatIfPresent(lltok::comma)) {
  3780. if (Lex.getKind() == lltok::MetadataVar) {
  3781. AteExtraComma = true;
  3782. break;
  3783. }
  3784. if (ParseTypeAndValue(Val, EltLoc, PFS)) return true;
  3785. if (!Val->getType()->getScalarType()->isIntegerTy())
  3786. return Error(EltLoc, "getelementptr index must be an integer");
  3787. if (Val->getType()->isVectorTy() != Ptr->getType()->isVectorTy())
  3788. return Error(EltLoc, "getelementptr index type missmatch");
  3789. if (Val->getType()->isVectorTy()) {
  3790. unsigned ValNumEl = cast<VectorType>(Val->getType())->getNumElements();
  3791. unsigned PtrNumEl = cast<VectorType>(Ptr->getType())->getNumElements();
  3792. if (ValNumEl != PtrNumEl)
  3793. return Error(EltLoc,
  3794. "getelementptr vector index has a wrong number of elements");
  3795. }
  3796. Indices.push_back(Val);
  3797. }
  3798. if (!Indices.empty() && !BasePointerType->getElementType()->isSized())
  3799. return Error(Loc, "base element of getelementptr must be sized");
  3800. if (!GetElementPtrInst::getIndexedType(BaseType, Indices))
  3801. return Error(Loc, "invalid getelementptr indices");
  3802. Inst = GetElementPtrInst::Create(Ptr, Indices);
  3803. if (InBounds)
  3804. cast<GetElementPtrInst>(Inst)->setIsInBounds(true);
  3805. return AteExtraComma ? InstExtraComma : InstNormal;
  3806. }
  3807. /// ParseExtractValue
  3808. /// ::= 'extractvalue' TypeAndValue (',' uint32)+
  3809. int LLParser::ParseExtractValue(Instruction *&Inst, PerFunctionState &PFS) {
  3810. Value *Val; LocTy Loc;
  3811. SmallVector<unsigned, 4> Indices;
  3812. bool AteExtraComma;
  3813. if (ParseTypeAndValue(Val, Loc, PFS) ||
  3814. ParseIndexList(Indices, AteExtraComma))
  3815. return true;
  3816. if (!Val->getType()->isAggregateType())
  3817. return Error(Loc, "extractvalue operand must be aggregate type");
  3818. if (!ExtractValueInst::getIndexedType(Val->getType(), Indices))
  3819. return Error(Loc, "invalid indices for extractvalue");
  3820. Inst = ExtractValueInst::Create(Val, Indices);
  3821. return AteExtraComma ? InstExtraComma : InstNormal;
  3822. }
  3823. /// ParseInsertValue
  3824. /// ::= 'insertvalue' TypeAndValue ',' TypeAndValue (',' uint32)+
  3825. int LLParser::ParseInsertValue(Instruction *&Inst, PerFunctionState &PFS) {
  3826. Value *Val0, *Val1; LocTy Loc0, Loc1;
  3827. SmallVector<unsigned, 4> Indices;
  3828. bool AteExtraComma;
  3829. if (ParseTypeAndValue(Val0, Loc0, PFS) ||
  3830. ParseToken(lltok::comma, "expected comma after insertvalue operand") ||
  3831. ParseTypeAndValue(Val1, Loc1, PFS) ||
  3832. ParseIndexList(Indices, AteExtraComma))
  3833. return true;
  3834. if (!Val0->getType()->isAggregateType())
  3835. return Error(Loc0, "insertvalue operand must be aggregate type");
  3836. if (!ExtractValueInst::getIndexedType(Val0->getType(), Indices))
  3837. return Error(Loc0, "invalid indices for insertvalue");
  3838. Inst = InsertValueInst::Create(Val0, Val1, Indices);
  3839. return AteExtraComma ? InstExtraComma : InstNormal;
  3840. }
  3841. //===----------------------------------------------------------------------===//
  3842. // Embedded metadata.
  3843. //===----------------------------------------------------------------------===//
  3844. /// ParseMDNodeVector
  3845. /// ::= Element (',' Element)*
  3846. /// Element
  3847. /// ::= 'null' | TypeAndValue
  3848. bool LLParser::ParseMDNodeVector(SmallVectorImpl<Value*> &Elts,
  3849. PerFunctionState *PFS) {
  3850. // Check for an empty list.
  3851. if (Lex.getKind() == lltok::rbrace)
  3852. return false;
  3853. do {
  3854. // Null is a special case since it is typeless.
  3855. if (EatIfPresent(lltok::kw_null)) {
  3856. Elts.push_back(0);
  3857. continue;
  3858. }
  3859. Value *V = 0;
  3860. if (ParseTypeAndValue(V, PFS)) return true;
  3861. Elts.push_back(V);
  3862. } while (EatIfPresent(lltok::comma));
  3863. return false;
  3864. }