LLParser.cpp 134 KB

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