LLParser.cpp 130 KB

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